viveworker 0.7.0-beta.3 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +33 -4
  2. package/package.json +7 -3
  3. package/scripts/lib/remote-pairing/README.md +164 -0
  4. package/scripts/lib/remote-pairing/_browser-bundle-entry.mjs +86 -0
  5. package/scripts/lib/remote-pairing/audit.mjs +122 -0
  6. package/scripts/lib/remote-pairing/bridge-relay-client.mjs +737 -0
  7. package/scripts/lib/remote-pairing/control.mjs +156 -0
  8. package/scripts/lib/remote-pairing/envelope.mjs +224 -0
  9. package/scripts/lib/remote-pairing/http-dispatch.mjs +530 -0
  10. package/scripts/lib/remote-pairing/keys-core.mjs +110 -0
  11. package/scripts/lib/remote-pairing/keys.mjs +181 -0
  12. package/scripts/lib/remote-pairing/noise.mjs +436 -0
  13. package/scripts/lib/remote-pairing/orchestrator.mjs +356 -0
  14. package/scripts/lib/remote-pairing/pairings.mjs +446 -0
  15. package/scripts/lib/remote-pairing/rpc.mjs +381 -0
  16. package/scripts/moltbook-scout-auto.sh +16 -8
  17. package/scripts/share-cli.mjs +14 -130
  18. package/scripts/viveworker-bridge.mjs +1696 -223
  19. package/scripts/viveworker.mjs +27 -6
  20. package/web/app.css +727 -9
  21. package/web/app.js +1810 -232
  22. package/web/i18n.js +207 -17
  23. package/web/index.html +115 -1
  24. package/web/remote-pairing/api-router.js +873 -0
  25. package/web/remote-pairing/keys.js +237 -0
  26. package/web/remote-pairing/pairing-state.js +313 -0
  27. package/web/remote-pairing/rpc-client.js +765 -0
  28. package/web/remote-pairing/transport.js +804 -0
  29. package/web/remote-pairing/wake.js +149 -0
  30. package/web/remote-pairing-test.html +400 -0
  31. package/web/remote-pairing.bundle.js +3 -0
  32. package/web/remote-pairing.bundle.js.LEGAL.txt +15 -0
  33. package/web/remote-pairing.bundle.js.map +7 -0
  34. package/web/sw.js +190 -20
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../node_modules/@noble/hashes/src/_assert.ts", "../node_modules/@noble/hashes/src/crypto.ts", "../node_modules/@noble/hashes/src/utils.ts", "../node_modules/@noble/hashes/src/_sha2.ts", "../node_modules/@noble/hashes/src/_u64.ts", "../node_modules/@noble/hashes/src/sha512.ts", "../node_modules/@noble/curves/src/abstract/utils.ts", "../node_modules/@noble/curves/src/abstract/modular.ts", "../node_modules/@noble/curves/src/abstract/curve.ts", "../node_modules/@noble/curves/src/abstract/edwards.ts", "../node_modules/@noble/curves/src/abstract/montgomery.ts", "../node_modules/@noble/curves/src/ed25519.ts", "../node_modules/@noble/ciphers/src/utils.ts", "../node_modules/@noble/ciphers/src/_arx.ts", "../node_modules/@noble/ciphers/src/_poly1305.ts", "../node_modules/@noble/ciphers/src/chacha.ts", "../node_modules/@noble/hashes/src/sha256.ts", "../node_modules/@noble/hashes/src/hmac.ts", "../node_modules/@noble/hashes/src/hkdf.ts", "../scripts/lib/remote-pairing/noise.mjs", "../scripts/lib/remote-pairing/envelope.mjs", "../scripts/lib/remote-pairing/keys-core.mjs", "../scripts/lib/remote-pairing/rpc.mjs"],
4
+ "sourcesContent": ["function number(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error(`Wrong positive integer: ${n}`);\n}\n\nfunction bool(b: boolean) {\n if (typeof b !== 'boolean') throw new Error(`Expected boolean, not ${b}`);\n}\n\nfunction bytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!(b instanceof Uint8Array)) throw new Error('Expected Uint8Array');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);\n}\n\ntype Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction hash(hash: Hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\n\nfunction exists(instance: any, checkFinished = true) {\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}\nfunction output(out: any, instance: any) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\n\nexport { number, bool, bytes, hash, exists, output };\n\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n", "// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// See utils.ts for details.\ndeclare const globalThis: Record<string, any> | undefined;\nexport const crypto =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n", "/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated, we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\nconst u8a = (a: any): a is Uint8Array => a instanceof Uint8Array;\n// Cast array to different type\nexport const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr: TypedArray) =>\n new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\n// Cast array to view\nexport const createView = (arr: TypedArray) =>\n new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word: number, shift: number) => (word << (32 - shift)) | (word >>> shift);\n\n// big-endian hardware is rare. Just in case someone still decides to run hashes:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE) throw new Error('Non little-endian hardware is not supported');\n\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n if (!u8a(bytes)) throw new Error('Uint8Array expected');\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/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const len = hex.length;\n if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n const array = new Uint8Array(len / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\n\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => {};\n\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n if (!u8a(data)) throw new Error(`expected Uint8Array, got ${typeof data}`);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n let pad = 0; // walk through each item, ensure they have proper type\n arrays.forEach((a) => {\n if (!u8a(a)) throw new Error('Uint8Array expected');\n r.set(a, pad);\n pad += a.length;\n });\n return r;\n}\n\n// For runtime check if class implements interface\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\nconst toStr = {}.toString;\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\nexport type CHash = ReturnType<typeof wrapConstructor>;\n\nexport function wrapConstructor<T extends Hash<T>>(hashCons: () => Hash<T>) {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function wrapConstructorWithOpts<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\nexport function wrapXOFConstructorWithOpts<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n", "import { exists, output } from './_assert.js';\nimport { Hash, createView, Input, toBytes } from './utils.js';\n\n// Polyfill for Safari 14\nfunction setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n// Base SHA2 class (RFC 6234)\nexport abstract class SHA2<T extends SHA2<T>> extends Hash<T> {\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 // 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(\n readonly blockLen: number,\n public outputLen: number,\n readonly padOffset: number,\n readonly isLE: boolean\n ) {\n super();\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\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: we have at least one block in input, cast it to view and process\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: Uint8Array) {\n exists(this);\n output(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 this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in 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 // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, 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 should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should 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() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\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.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n", "const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n: bigint, le = false) {\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\nfunction split(lst: bigint[], le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number) => h >>> s;\nconst shrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number) => l;\nconst rotr32L = (h: number, _l: number) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number) => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah: number, Al: number, Bh: number, Bl: number) {\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\nconst add3L = (Al: number, Bl: number, Cl: number) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number) =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number) =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number) =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number) =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\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// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n", "import { SHA2 } from './_sha2.js';\nimport u64 from './_u64.js';\nimport { wrapConstructor } from './utils.js';\n\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__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))))();\n\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends SHA2<SHA512> {\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x6a09e667 | 0;\n Al = 0xf3bcc908 | 0;\n Bh = 0xbb67ae85 | 0;\n Bl = 0x84caa73b | 0;\n Ch = 0x3c6ef372 | 0;\n Cl = 0xfe94f82b | 0;\n Dh = 0xa54ff53a | 0;\n Dl = 0x5f1d36f1 | 0;\n Eh = 0x510e527f | 0;\n El = 0xade682d1 | 0;\n Fh = 0x9b05688c | 0;\n Fl = 0x2b3e6c1f | 0;\n Gh = 0x1f83d9ab | 0;\n Gl = 0xfb41bd6b | 0;\n Hh = 0x5be0cd19 | 0;\n Hl = 0x137e2179 | 0;\n\n constructor() {\n super(128, 64, 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 ) {\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) {\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 // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_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() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nclass SHA512_224 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x8c3d37c8 | 0;\n Al = 0x19544da2 | 0;\n Bh = 0x73e19966 | 0;\n Bl = 0x89dcd4d6 | 0;\n Ch = 0x1dfab7ae | 0;\n Cl = 0x32ff9c82 | 0;\n Dh = 0x679dd514 | 0;\n Dl = 0x582f9fcf | 0;\n Eh = 0x0f6d2b69 | 0;\n El = 0x7bd44da8 | 0;\n Fh = 0x77e36f73 | 0;\n Fl = 0x04c48942 | 0;\n Gh = 0x3f9d85a8 | 0;\n Gl = 0x6a1d36c8 | 0;\n Hh = 0x1112e6ad | 0;\n Hl = 0x91d692a1 | 0;\n\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\nclass SHA512_256 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x22312194 | 0;\n Al = 0xfc2bf72c | 0;\n Bh = 0x9f555fa3 | 0;\n Bl = 0xc84c64c2 | 0;\n Ch = 0x2393b86b | 0;\n Cl = 0x6f53b151 | 0;\n Dh = 0x96387719 | 0;\n Dl = 0x5940eabd | 0;\n Eh = 0x96283ee2 | 0;\n El = 0xa88effe3 | 0;\n Fh = 0xbe5e1e25 | 0;\n Fl = 0x53863992 | 0;\n Gh = 0x2b0199fc | 0;\n Gl = 0x2c85b8aa | 0;\n Hh = 0x0eb72ddc | 0;\n Hl = 0x81c52ca2 | 0;\n\n constructor() {\n super();\n this.outputLen = 32;\n }\n}\n\nclass SHA384 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0xcbbb9d5d | 0;\n Al = 0xc1059ed8 | 0;\n Bh = 0x629a292a | 0;\n Bl = 0x367cd507 | 0;\n Ch = 0x9159015a | 0;\n Cl = 0x3070dd17 | 0;\n Dh = 0x152fecd8 | 0;\n Dl = 0xf70e5939 | 0;\n Eh = 0x67332667 | 0;\n El = 0xffc00b31 | 0;\n Fh = 0x8eb44a87 | 0;\n Fl = 0x68581511 | 0;\n Gh = 0xdb0c2e0d | 0;\n Gl = 0x64f98fa7 | 0;\n Hh = 0x47b5481d | 0;\n Hl = 0xbefa4fa4 | 0;\n\n constructor() {\n super();\n this.outputLen = 48;\n }\n}\n\nexport const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());\nexport const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\nexport const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\nexport const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst u8a = (a: any): a is Uint8Array => a instanceof Uint8Array;\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n (message: Uint8Array | string): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n if (!u8a(bytes)) throw new Error('Uint8Array expected');\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\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const len = hex.length;\n if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n const array = new Uint8Array(len / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n if (!u8a(bytes)) throw new Error('Uint8Array expected');\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes(numberToHexUnpadded(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n let res: Uint8Array;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n } catch (e) {\n throw new Error(`${title} must be valid hex string, got \"${hex}\". Cause: ${e}`);\n }\n } else if (u8a(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n } else {\n throw new Error(`${title} must be hex string or Uint8Array`);\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);\n return res;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n let pad = 0; // walk through each item, ensure they have proper type\n arrays.forEach((a) => {\n if (!u8a(a)) throw new Error('Uint8Array expected');\n r.set(a, pad);\n pad += a.length;\n });\n return r;\n}\n\nexport function equalBytes(b1: Uint8Array, b2: Uint8Array) {\n // We don't care about timing attacks here\n if (b1.length !== b2.length) return false;\n for (let i = 0; i < b1.length; i++) if (b1[i] !== b2[i]) return false;\n return true;\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n: bigint) {\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 */\nexport function bitGet(n: bigint, pos: number) {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport const bitSet = (n: bigint, pos: number, value: boolean) => {\n return n | ((value ? _1n : _0n) << BigInt(pos));\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 */\nexport const bitMask = (n: number) => (_2n << BigInt(n - 1)) - _1n;\n\n// DRBG\n\nconst u8n = (data?: any) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr: any) => Uint8Array.from(arr); // another shortcut\ntype Pred<T> = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG<Key>(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg<T>(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred<T>) => T {\n if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\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 const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(u8fr([0x01]), 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++ >= 1000) throw new Error('drbg: tried 1000 values');\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: Uint8Array, pred: Pred<T>): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\n// Validating curves and fields\n\nconst validatorFns = {\n bigint: (val: any) => typeof val === 'bigint',\n function: (val: any) => typeof val === 'function',\n boolean: (val: any) => typeof val === 'boolean',\n string: (val: any) => typeof val === 'string',\n stringOrUint8Array: (val: any) => typeof val === 'string' || val instanceof Uint8Array,\n isSafeInteger: (val: any) => Number.isSafeInteger(val),\n array: (val: any) => Array.isArray(val),\n field: (val: any, object: any) => (object as any).Fp.isValid(val),\n hash: (val: any) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap<T extends Record<string, any>> = { [K in keyof T]?: Validator };\n// type Record<K extends string | number | symbol, T> = { [P in K]: T; }\n\nexport function validateObject<T extends Record<string, any>>(\n object: T,\n validators: ValMap<T>,\n optValidators: ValMap<T> = {}\n) {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error(`Invalid validator \"${type}\", expected function`);\n\n const val = object[fieldName as keyof typeof object];\n if (isOptional && val === undefined) return;\n if (!checkVal(val, object)) {\n throw new Error(\n `Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`\n );\n }\n };\n for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport {\n bitMask,\n numberToBytesBE,\n numberToBytesLE,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n validateObject,\n} from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);\n// prettier-ignore\nconst _9n = BigInt(9), _16n = BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n if (modulo <= _0n || power < _0n) throw new Error('Expected power/modulo > 0');\n if (modulo === _1n) return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n) res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n// Inverses number over modulo\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\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 // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\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\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) \u2261 1 if a is a square (mod p)\n // (a | p) \u2261 -1 if a is not a square (mod p)\n // (a | p) \u2261 0 if a \u2261 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n\n let Q: bigint, S: number, Z: bigint;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++);\n\n // Step 2: Select a non-square z such that (z | p) \u2261 -1 and set c \u2261 zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++);\n\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast<T>(Fp: IField<T>, n: T) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow<T>(Fp: IField<T>, n: T): T {\n // Step 0: Check that n is indeed a square: (n | p) should not be \u2261 -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE)) break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\n\nexport function FpSqrt(P: bigint) {\n // NOTE: 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 choice root based on oddness (used for hash-to-curve).\n\n // P \u2261 3 (mod 4)\n // \u221An = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4<T>(Fp: IField<T>, n: T) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Atkin algorithm for q \u2261 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8<T>(Fp: IField<T>, n: T) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // P \u2261 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(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 // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint) => (mod(num, modulo) & _1n) === _1n;\n\n// Field is not always over prime: for example, Fp2 has ORDER(q)=p^m\nexport interface IField<T> {\n ORDER: bigint;\n BYTES: number;\n BITS: number;\n MASK: bigint;\n ZERO: T;\n ONE: T;\n // 1-arg\n create: (num: T) => T;\n isValid: (num: T) => boolean;\n is0: (num: T) => boolean;\n neg(num: T): T;\n inv(num: T): T;\n sqrt(num: T): T;\n sqr(num: T): T;\n // 2-args\n eql(lhs: T, rhs: T): boolean;\n add(lhs: T, rhs: T): T;\n sub(lhs: T, rhs: T): T;\n mul(lhs: T, rhs: T | bigint): T;\n pow(lhs: T, power: bigint): T;\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n addN(lhs: T, rhs: T): T;\n subN(lhs: T, rhs: T): T;\n mulN(lhs: T, rhs: T | bigint): T;\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 same as odd. And negative in LE is kinda strange definition anyway.\n isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n // legendre?(num: T): T;\n pow(lhs: T, power: bigint): T;\n invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\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;\nexport function validateField<T>(field: IField<T>) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n } as Record<string, string>;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\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 */\nexport function FpPow<T>(f: IField<T>, num: T, power: bigint): T {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n) throw new Error('Expected power > 0');\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 * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch<T>(f: IField<T>, nums: T[]): T[] {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\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 tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\n\nexport function FpDiv<T>(f: IField<T>, lhs: T, rhs: T | bigint): T {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare<T>(f: IField<T>) {\n const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic\n return (x: T): boolean => {\n const p = f.pow(x, legendreConst);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n ORDER: bigint,\n bitLen?: number,\n isLE = false,\n redef: Partial<IField<bigint>> = {}\n): Readonly<FpField> {\n if (ORDER <= _0n) throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048) throw new Error('Field lengths over 2048 bytes are not supported');\n const sqrtP = FpSqrt(ORDER);\n const f: Readonly<FpField> = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt || ((n) => sqrtP(f, n)),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n } as FpField);\n return Object.freeze(f);\n}\n\nexport function FpSqrtOdd<T>(Fp: IField<T>, elm: T) {\n if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven<T>(Fp: IField<T>, elm: T) {\n if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(\n hash: string | Uint8Array,\n groupOrder: bigint,\n isLE = false\n): bigint {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\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\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\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 * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\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.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);\n const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(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", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { IField, validateField, nLength } from './modular.js';\nimport { validateObject } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint<T> = {\n x: T;\n y: T;\n} & { z?: never; t?: never };\n\nexport interface Group<T extends Group<T>> {\n double(): T;\n negate(): T;\n add(other: T): T;\n subtract(other: T): T;\n equals(other: T): boolean;\n multiply(scalar: bigint): T;\n}\n\nexport type GroupConstructor<T> = {\n BASE: T;\n ZERO: T;\n};\nexport type Mapper<T> = (i: T[]) => T[];\n\n// Elliptic curve multiplication of Point by scalar. Fragile.\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// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF<T extends Group<T>>(c: GroupConstructor<T>, bits: number) {\n const constTimeNegate = (condition: boolean, item: T): T => {\n const neg = item.negate();\n return condition ? neg : item;\n };\n const opts = (W: number) => {\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n };\n return {\n constTimeNegate,\n // non-const time multiplication ladder\n unsafeLadder(elm: T, n: bigint) {\n let p = c.ZERO;\n let d: T = 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 * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm: T, W: number): Group<T>[] {\n const { windows, windowSize } = opts(W);\n const points: T[] = [];\n let p: T = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\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 * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T } {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = opts(W);\n\n let p = c.ZERO;\n let f = c.BASE;\n\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n\n // Shift number by W bits.\n n >>= shiftBy;\n\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n\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\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n } else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n\n wNAFCached(P: T, precomputesMap: Map<T, T[]>, n: bigint, transform: Mapper<T>): { p: T; f: T } {\n // @ts-ignore\n const W: number = P._WINDOW_SIZE || 1;\n // Calculate precomputes on a first run, reuse them after\n let comp = precomputesMap.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W) as T[];\n if (W !== 1) {\n precomputesMap.set(P, transform(comp));\n }\n }\n return this.wNAF(W, comp, n);\n },\n };\n}\n\n// Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n// Though generator can be different (Fp2 / Fp6 for BLS).\nexport type BasicCurve<T> = {\n Fp: IField<T>; // Field over which we'll do calculations (Fp)\n n: bigint; // Curve order, total count of valid points in the field\n nBitLength?: number; // bit length of curve order\n nByteLength?: number; // byte length of curve order\n h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n hEff?: bigint; // Number to multiply to clear cofactor\n Gx: T; // base point X coordinate\n Gy: T; // base point Y coordinate\n allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\nexport function validateBasic<FP, T>(curve: BasicCurve<FP> & T) {\n validateField(curve.Fp);\n validateObject(\n curve,\n {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n },\n {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n }\n );\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n } as const);\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Twisted Edwards curve. The formula is: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2\nimport { mod } from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes, FHash, Hex } from './utils.js';\nimport { Group, GroupConstructor, wNAF, BasicCurve, validateBasic, AffinePoint } from './curve.js';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n\n// Edwards curves must declare params a & d.\nexport type CurveType = BasicCurve<bigint> & {\n a: bigint; // curve param a\n d: bigint; // curve param d\n hash: FHash; // Hashing\n randomBytes: (bytesLength?: number) => Uint8Array; // CSPRNG\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing\n uvRatio?: (u: bigint, v: bigint) => { isValid: boolean; value: bigint }; // Ratio \u221A(u/v)\n prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify()\n mapToCurve?: (scalar: bigint[]) => AffinePoint<bigint>; // for hash-to-curve standard\n};\n\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\n\nfunction validateOpts(curve: CurveType) {\n const opts = validateBasic(curve);\n ut.validateObject(\n curve,\n {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n },\n {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n }\n );\n // Set defaults\n return Object.freeze({ ...opts } as const);\n}\n\n// Instance of Extended Point with coordinates in X, Y, Z, T\nexport interface ExtPointType extends Group<ExtPointType> {\n readonly ex: bigint;\n readonly ey: bigint;\n readonly ez: bigint;\n readonly et: bigint;\n get x(): bigint;\n get y(): bigint;\n assertValidity(): void;\n multiply(scalar: bigint): ExtPointType;\n multiplyUnsafe(scalar: bigint): ExtPointType;\n isSmallOrder(): boolean;\n isTorsionFree(): boolean;\n clearCofactor(): ExtPointType;\n toAffine(iz?: bigint): AffinePoint<bigint>;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n}\n// Static methods of Extended Point with coordinates in X, Y, Z, T\nexport interface ExtPointConstructor extends GroupConstructor<ExtPointType> {\n new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType;\n fromAffine(p: AffinePoint<bigint>): ExtPointType;\n fromHex(hex: Hex): ExtPointType;\n fromPrivateKey(privateKey: Hex): ExtPointType;\n}\n\nexport type CurveFn = {\n CURVE: ReturnType<typeof validateOpts>;\n getPublicKey: (privateKey: Hex) => Uint8Array;\n sign: (message: Hex, privateKey: Hex, options?: { context?: Hex }) => Uint8Array;\n verify: (\n sig: Hex,\n message: Hex,\n publicKey: Hex,\n options?: { context?: Hex; zip215: boolean }\n ) => boolean;\n ExtendedPoint: ExtPointConstructor;\n utils: {\n randomPrivateKey: () => Uint8Array;\n getExtendedPublicKey: (key: Hex) => {\n head: Uint8Array;\n prefix: Uint8Array;\n scalar: bigint;\n point: ExtPointType;\n pointBytes: Uint8Array;\n };\n };\n};\n\n// It is not generic twisted curve for now, but ed25519/ed448 generic implementation\nexport function twistedEdwards(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType<typeof validateOpts>;\n const {\n Fp,\n n: CURVE_ORDER,\n prehash: prehash,\n hash: cHash,\n randomBytes,\n nByteLength,\n h: cofactor,\n } = CURVE;\n const MASK = _2n << (BigInt(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n\n // sqrt(u/v)\n const uvRatio =\n CURVE.uvRatio ||\n ((u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes); // NOOP\n const domain =\n CURVE.domain ||\n ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => {\n if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n const inBig = (n: bigint) => typeof n === 'bigint' && _0n < n; // n in [1..]\n const inRange = (n: bigint, max: bigint) => inBig(n) && inBig(max) && n < max; // n in [1..max-1]\n const in0MaskRange = (n: bigint) => n === _0n || inRange(n, MASK); // n in [0..MASK-1]\n function assertInRange(n: bigint, max: bigint) {\n // n in [1..max-1]\n if (inRange(n, max)) return n;\n throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`);\n }\n function assertGE0(n: bigint) {\n // n in [0..CURVE_ORDER-1]\n return n === _0n ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group\n }\n const pointPrecomputes = new Map<Point, Point[]>();\n function isPoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ExtendedPoint expected');\n }\n // Extended Point works in extended coordinates: (x, y, z, t) \u220B (x=x/z, y=y/z, t=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point implements ExtPointType {\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n\n constructor(\n readonly ex: bigint,\n readonly ey: bigint,\n readonly ez: bigint,\n readonly et: bigint\n ) {\n if (!in0MaskRange(ex)) throw new Error('x required');\n if (!in0MaskRange(ey)) throw new Error('y required');\n if (!in0MaskRange(ez)) throw new Error('z required');\n if (!in0MaskRange(et)) throw new Error('t required');\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n static fromAffine(p: AffinePoint<bigint>): Point {\n if (p instanceof Point) throw new Error('extended point not allowed');\n const { x, y } = p || {};\n if (!in0MaskRange(x) || !in0MaskRange(y)) throw new Error('invalid affine point');\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points: Point[]): Point[] {\n const toInv = Fp.invertBatch(points.map((p) => p.ez));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\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 _WINDOW_SIZE?: number;\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity(): void {\n const { a, d } = CURVE;\n if (this.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX\u00B2 + Y\u00B2)Z\u00B2 = Z\u2074 + dX\u00B2Y\u00B2\n const { ex: X, ey: Y, ez: Z, et: T } = this;\n const X2 = modP(X * X); // X\u00B2\n const Y2 = modP(Y * Y); // Y\u00B2\n const Z2 = modP(Z * Z); // Z\u00B2\n const Z4 = modP(Z2 * Z2); // Z\u2074\n const aX2 = modP(X2 * a); // aX\u00B2\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX\u00B2 + Y\u00B2)Z\u00B2\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z\u2074 + dX\u00B2Y\u00B2\n if (left !== right) throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT) throw new Error('bad point: equation left != right (2)');\n }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n isPoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n\n protected is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n negate(): Point {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));\n }\n\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double(): Point {\n const { a } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other: Point) {\n isPoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;\n // Faster algo for adding 2 Extended Points when curve's a=-1.\n // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4\n // Cost: 8M + 8add + 2*2.\n // Note: It does not check whether the `other` point is valid.\n if (a === BigInt(-1)) {\n const A = modP((Y1 - X1) * (Y2 + X2));\n const B = modP((Y1 + X1) * (Y2 - X2));\n const F = modP(B - A);\n if (F === _0n) return this.double(); // Same point. Tests say it doesn't affect timing\n const C = modP(Z1 * _2n * T2);\n const D = modP(T1 * _2n * Z2);\n const E = D + C;\n const G = B + A;\n const H = D - C;\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n\n return new Point(X3, Y3, Z3, T3);\n }\n\n subtract(other: Point): Point {\n return this.add(other.negate());\n }\n\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ);\n }\n\n // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER));\n return Point.normalizeZ([p, f])[0];\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 private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n multiplyUnsafe(scalar: bigint): Point {\n let n = assertGE0(scalar); // 0 <= scalar < CURVE.n\n if (n === _0n) return I;\n if (this.equals(I) || n === _1n) return this;\n if (this.equals(G)) return this.wNAF(n).p;\n return wnaf.unsafeLadder(this, n);\n }\n\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder(): boolean {\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree(): boolean {\n return wnaf.unsafeLadder(this, CURVE_ORDER).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz?: bigint): AffinePoint<bigint> {\n const { ex: x, ey: y, ez: z } = this;\n const is0 = this.is0();\n if (iz == null) iz = is0 ? _8n : (Fp.inv(z) as bigint); // 8 was chosen arbitrarily\n const ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n }\n\n clearCofactor(): Point {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex: Hex, zip215 = false): Point {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = ensureBytes('pointHex', hex, len); // copy hex to a new array\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = ut.bytesToNumberLE(normed);\n if (y === _0n) {\n // y=0 is allowed\n } else {\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n if (zip215) assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519)\n else assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519)\n }\n\n // Ed25519: x\u00B2 = (y\u00B2-1)/(dy\u00B2+1) mod p. Ed448: x\u00B2 = (y\u00B2-1)/(dy\u00B2-1) mod p. Generic case:\n // ax\u00B2+y\u00B2=1+dx\u00B2y\u00B2 => y\u00B2-1=dx\u00B2y\u00B2-ax\u00B2 => y\u00B2-1=x\u00B2(dy\u00B2-a) => x\u00B2=(y\u00B2-1)/(dy\u00B2-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y\u00B2 - 1\n const v = modP(d * y2 - a); // v = d y\u00B2 + 1.\n let { isValid, value: x } = uvRatio(u, v); // \u221A(u/v)\n if (!isValid) throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('Point.fromHex: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromPrivateKey(privKey: Hex) {\n return getExtendedPublicKey(privKey).point;\n }\n toRawBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex(): string {\n return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n const { BASE: G, ZERO: I } = Point;\n const wnaf = wNAF(Point, nByteLength * 8);\n\n function modN(a: bigint) {\n return mod(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash: Uint8Array): bigint {\n return modN(ut.bytesToNumberLE(hash));\n }\n\n /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */\n function getExtendedPublicKey(key: Hex) {\n const len = nByteLength;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey: Hex): Uint8Array {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context: Hex = new Uint8Array(), ...msgs: Uint8Array[]) {\n const msg = ut.concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg: Hex, privKey: Hex, options: { context?: Hex } = {}): Uint8Array {\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n assertGE0(s); // 0 <= s < l\n const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES));\n return ensureBytes('result', res, nByteLength * 2); // 64-byte signature\n }\n\n const verifyOpts: { context?: Hex; zip215?: boolean } = VERIFY_DEFAULT;\n function verify(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const s = ut.bytesToNumberLE(sig.slice(len, 2 * len));\n // zip215: true is good for consensus-critical apps and allows points < 2^256\n // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p\n let A, R, SB;\n try {\n A = Point.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder()) return false;\n\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);\n }\n\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n\n const utils = {\n getExtendedPublicKey,\n // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.\n randomPrivateKey: (): Uint8Array => randomBytes(Fp.BYTES),\n\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { mod, pow } from './modular.js';\nimport { bytesToNumberLE, ensureBytes, numberToBytesLE, validateObject } from './utils.js';\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\ntype Hex = string | Uint8Array;\n\nexport type CurveType = {\n P: bigint; // finite field prime\n nByteLength: number;\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array;\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array;\n a: bigint;\n montgomeryBits: number;\n powPminus2?: (x: bigint) => bigint;\n xyToU?: (x: bigint, y: bigint) => bigint;\n Gu: bigint;\n randomBytes?: (bytesLength?: number) => Uint8Array;\n};\nexport type CurveFn = {\n scalarMult: (scalar: Hex, u: Hex) => Uint8Array;\n scalarMultBase: (scalar: Hex) => Uint8Array;\n getSharedSecret: (privateKeyA: Hex, publicKeyB: Hex) => Uint8Array;\n getPublicKey: (privateKey: Hex) => Uint8Array;\n utils: { randomPrivateKey: () => Uint8Array };\n GuBytes: Uint8Array;\n};\n\nfunction validateOpts(curve: CurveType) {\n validateObject(\n curve,\n {\n a: 'bigint',\n },\n {\n montgomeryBits: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n adjustScalarBytes: 'function',\n domain: 'function',\n powPminus2: 'function',\n Gu: 'bigint',\n }\n );\n // Set defaults\n return Object.freeze({ ...curve } as const);\n}\n\n// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748)\n// Uses only one coordinate instead of two\nexport function montgomery(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef);\n const { P } = CURVE;\n const modP = (n: bigint) => mod(n, P);\n const montgomeryBits = CURVE.montgomeryBits;\n const montgomeryBytes = Math.ceil(montgomeryBits / 8);\n const fieldLen = CURVE.nByteLength;\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes);\n const powPminus2 = CURVE.powPminus2 || ((x: bigint) => pow(x, P - BigInt(2), P));\n\n // cswap from RFC7748. But it is not from RFC7748!\n /*\n cswap(swap, x_2, x_3):\n dummy = mask(swap) AND (x_2 XOR x_3)\n x_2 = x_2 XOR dummy\n x_3 = x_3 XOR dummy\n Return (x_2, x_3)\n Where mask(swap) is the all-1 or all-0 word of the same length as x_2\n and x_3, computed, e.g., as mask(swap) = 0 - swap.\n */\n function cswap(swap: bigint, x_2: bigint, x_3: bigint): [bigint, bigint] {\n const dummy = modP(swap * (x_2 - x_3));\n x_2 = modP(x_2 - dummy);\n x_3 = modP(x_3 + dummy);\n return [x_2, x_3];\n }\n\n // Accepts 0 as well\n function assertFieldElement(n: bigint): bigint {\n if (typeof n === 'bigint' && _0n <= n && n < P) return n;\n throw new Error('Expected valid scalar 0 < scalar < CURVE.P');\n }\n\n // x25519 from 4\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519\n const a24 = (CURVE.a - BigInt(2)) / BigInt(4);\n /**\n *\n * @param pointU u coordinate (x) on Montgomery Curve 25519\n * @param scalar by which the point would be multiplied\n * @returns new Point on Montgomery curve\n */\n function montgomeryLadder(pointU: bigint, scalar: bigint): bigint {\n const u = assertFieldElement(pointU);\n // Section 5: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime.\n const k = assertFieldElement(scalar);\n const x_1 = u;\n let x_2 = _1n;\n let z_2 = _0n;\n let x_3 = u;\n let z_3 = _1n;\n let swap = _0n;\n let sw: [bigint, bigint];\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const k_t = (k >> t) & _1n;\n swap ^= k_t;\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n swap = k_t;\n\n const A = x_2 + z_2;\n const AA = modP(A * A);\n const B = x_2 - z_2;\n const BB = modP(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = modP(D * A);\n const CB = modP(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = modP(dacb * dacb);\n z_3 = modP(x_1 * modP(da_cb * da_cb));\n x_2 = modP(AA * BB);\n z_2 = modP(E * (AA + modP(a24 * E)));\n }\n // (x_2, x_3) = cswap(swap, x_2, x_3)\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n // (z_2, z_3) = cswap(swap, z_2, z_3)\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n // z_2^(p - 2)\n const z2 = powPminus2(z_2);\n // Return x_2 * (z_2^(p - 2))\n return modP(x_2 * z2);\n }\n\n function encodeUCoordinate(u: bigint): Uint8Array {\n return numberToBytesLE(modP(u), montgomeryBytes);\n }\n\n function decodeUCoordinate(uEnc: Hex): bigint {\n // Section 5: When receiving such an array, implementations of X25519\n // MUST mask the most significant bit in the final byte.\n // This is very ugly way, but it works because fieldLen-1 is outside of bounds for X448, so this becomes NOOP\n // fieldLen - scalaryBytes = 1 for X448 and = 0 for X25519\n const u = ensureBytes('u coordinate', uEnc, montgomeryBytes);\n // u[fieldLen-1] crashes QuickJS (TypeError: out-of-bound numeric index)\n if (fieldLen === montgomeryBytes) u[fieldLen - 1] &= 127; // 0b0111_1111\n return bytesToNumberLE(u);\n }\n function decodeScalar(n: Hex): bigint {\n const bytes = ensureBytes('scalar', n);\n if (bytes.length !== montgomeryBytes && bytes.length !== fieldLen)\n throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${bytes.length}`);\n return bytesToNumberLE(adjustScalarBytes(bytes));\n }\n function scalarMult(scalar: Hex, u: Hex): Uint8Array {\n const pointU = decodeUCoordinate(u);\n const _scalar = decodeScalar(scalar);\n const pu = montgomeryLadder(pointU, _scalar);\n // The result was not contributory\n // https://cr.yp.to/ecdh.html#validate\n if (pu === _0n) throw new Error('Invalid private or public key received');\n return encodeUCoordinate(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n const GuBytes = encodeUCoordinate(CURVE.Gu);\n function scalarMultBase(scalar: Hex): Uint8Array {\n return scalarMult(scalar, GuBytes);\n }\n\n return {\n scalarMult,\n scalarMultBase,\n getSharedSecret: (privateKey: Hex, publicKey: Hex) => scalarMult(privateKey, publicKey),\n getPublicKey: (privateKey: Hex): Uint8Array => scalarMultBase(privateKey),\n utils: { randomPrivateKey: () => CURVE.randomBytes!(CURVE.nByteLength) },\n GuBytes: GuBytes,\n };\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha512';\nimport { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils';\nimport { ExtPointType, twistedEdwards } from './abstract/edwards.js';\nimport { montgomery } from './abstract/montgomery.js';\nimport { Field, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.js';\nimport {\n bytesToHex,\n bytesToNumberLE,\n ensureBytes,\n equalBytes,\n Hex,\n numberToBytesLE,\n} from './abstract/utils.js';\nimport { createHasher, htfBasicOpts, expand_message_xmd } from './abstract/hash-to-curve.js';\nimport { AffinePoint } from './abstract/curve.js';\n\n/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n */\n\nconst ED25519_P = BigInt(\n '57896044618658097711785492504343953926634992332820282019728792003956564819949'\n);\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\nconst ED25519_SQRT_M1 = BigInt(\n '19681161376707505956807079304988542015446066515923890162744021073123829784752'\n);\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _5n = BigInt(5);\n// prettier-ignore\nconst _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n\nfunction ed25519_pow_2_252_3(x: bigint) {\n const P = ED25519_P;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\n\nfunction adjustScalarBytes(bytes: Uint8Array): Uint8Array {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n\n// sqrt(u/v)\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ED25519_P;\n const v3 = mod(v * v * v, P); // v\u00B3\n const v7 = mod(v3 * v3 * v, P); // v\u2077\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv\u00B3)(uv\u2077)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx\u00B2\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx\u00B2 = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx\u00B2 = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx\u00B2 = -u\u221A(-1)\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P)) x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n\n// Just in case\nexport const ED25519_TORSION_SUBGROUP = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n\nconst Fp = Field(ED25519_P, undefined, true);\n\nconst ed25519Defaults = {\n // Param: a\n a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster\n // d is equal to -121665/121666 over finite field.\n // Negative number is P - number, and division is invert(number, P)\n d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),\n // Finite field \uD835\uDD3Dp over which we'll do calculations; 2n**255n - 19n\n Fp,\n // Subgroup order: how many points curve has\n // 2n**252n + 27742317777372353535851937790883648493n;\n n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),\n // Cofactor\n h: BigInt(8),\n // Base point (x, y) aka generator point\n Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),\n Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),\n hash: sha512,\n randomBytes,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/\u221Av\n uvRatio,\n} as const;\n\nexport const ed25519 = /* @__PURE__ */ twistedEdwards(ed25519Defaults);\n\nfunction ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) {\n if (ctx.length > 255) throw new Error('Context is too big');\n return concatBytes(\n utf8ToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n );\n}\n\nexport const ed25519ctx = /* @__PURE__ */ twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n});\nexport const ed25519ph = /* @__PURE__ */ twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n prehash: sha512,\n});\n\nexport const x25519 = /* @__PURE__ */ (() =>\n montgomery({\n P: ED25519_P,\n a: BigInt(486662),\n montgomeryBits: 255, // n is 253 bits\n nByteLength: 32,\n Gu: BigInt(9),\n powPminus2: (x: bigint): bigint => {\n const P = ED25519_P;\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, BigInt(3), P) * b2, P);\n },\n adjustScalarBytes,\n randomBytes,\n }))();\n\n/**\n * Converts ed25519 public key to x25519 public key. Uses formula:\n * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * @example\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());\n * const aPriv = x25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub))\n */\nexport function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array {\n const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y)));\n}\nexport const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated\n\n/**\n * Converts ed25519 secret key to x25519 secret key.\n * @example\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey());\n * const aPriv = ed25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub)\n */\nexport function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array {\n const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32));\n return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32);\n}\n\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\n\nconst ELL2_C1 = (Fp.ORDER + BigInt(3)) / BigInt(8); // 1. c1 = (q + 3) / 8 # Integer arithmetic\n\nconst ELL2_C2 = Fp.pow(_2n, ELL2_C1); // 2. c2 = 2^c1\nconst ELL2_C3 = Fp.sqrt(Fp.neg(Fp.ONE)); // 3. c3 = sqrt(-1)\nconst ELL2_C4 = (Fp.ORDER - BigInt(5)) / BigInt(8); // 4. c4 = (q - 5) / 8 # Integer arithmetic\nconst ELL2_J = BigInt(486662);\n\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u: bigint) {\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\n\nconst ELL2_C1_EDWARDS = FpSqrtEven(Fp, Fp.neg(BigInt(486664))); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u: bigint) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n\n const inv = Fp.invertBatch([xd, yd]); // batch division\n return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd)\n}\n\nconst htf = /* @__PURE__ */ (() =>\n createHasher(\n ed25519.ExtendedPoint,\n (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]),\n {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\n ))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n\nfunction assertRstPoint(other: unknown) {\n if (!(other instanceof RistPoint)) throw new Error('RistrettoPoint expected');\n}\n\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// \u221A(ad - 1)\nconst SQRT_AD_MINUS_ONE = BigInt(\n '25063068953384623474111414158702152701244531502492656460079210482610430750235'\n);\n// 1 / \u221A(a-d)\nconst INVSQRT_A_MINUS_D = BigInt(\n '54469307008909316920995813868745141605393597292927456921205312896311721017578'\n);\n// 1-d\u00B2\nconst ONE_MINUS_D_SQ = BigInt(\n '1159843021668779879193775521855586647937357759715417654439879720876111806838'\n);\n// (d-1)\u00B2\nconst D_MINUS_ONE_SQ = BigInt(\n '40440834346308536858101042469323190826248399146238708352240133220865137265952'\n);\n// Calculates 1/\u221A(number)\nconst invertSqrt = (number: bigint) => uvRatio(_1n, number);\n\nconst MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst bytes255ToNumberLE = (bytes: Uint8Array) =>\n ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\ntype ExtendedPoint = ExtPointType;\n\n// Computes Elligator map for Ristretto\n// https://ristretto.group/formulas/elligator.html\nfunction calcElligatorRistrettoMap(r0: bigint): ExtendedPoint {\n const { d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P)) s_ = mod(-s_);\n if (!Ns_D_is_sq) s = s_; // 7\n if (!Ns_D_is_sq) c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\n/**\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448\n */\nclass RistPoint {\n static BASE: RistPoint;\n static ZERO: RistPoint;\n // Private property to discourage combining ExtendedPoint + RistrettoPoint\n // Always use Ristretto encoding/decoding instead.\n constructor(private readonly ep: ExtendedPoint) {}\n\n static fromAffine(ap: AffinePoint<bigint>) {\n return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap));\n }\n\n /**\n * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\n * https://ristretto.group/formulas/elligator.html\n * @param hex 64-byte output of a hash function\n */\n static hashToCurve(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHash', hex, 64);\n const r1 = bytes255ToNumberLE(hex.slice(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(hex.slice(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new RistPoint(R1.add(R2));\n }\n\n /**\n * Converts ristretto-encoded string to ristretto point.\n * https://ristretto.group/formulas/decoding.html\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHex', hex, 32);\n const { a, d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';\n const s = bytes255ToNumberLE(hex);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P)) throw new Error(emsg);\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P)) x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n) throw new Error(emsg);\n return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t));\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * https://ristretto.group/formulas/encoding.html\n */\n toRawBytes(): Uint8Array {\n let { ex: x, ey: y, ez: z, et: t } = this.ep;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const u1 = mod(mod(z + y) * mod(z - y)); // 1\n const u2 = mod(x * y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * t); // 6\n let D: bigint; // 7\n if (isNegativeLE(t * zInv, P)) {\n let _x = mod(y * SQRT_M1);\n let _y = mod(x * SQRT_M1);\n x = _x;\n y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n } else {\n D = D2; // 8\n }\n if (isNegativeLE(x * zInv, P)) y = mod(-y); // 9\n let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P)) s = mod(-s);\n return numberToBytesLE(s, 32); // 11\n }\n\n toHex(): string {\n return bytesToHex(this.toRawBytes());\n }\n\n toString(): string {\n return this.toHex();\n }\n\n // Compare one point to another.\n equals(other: RistPoint): boolean {\n assertRstPoint(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed25519.CURVE.Fp.create;\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n\n add(other: RistPoint): RistPoint {\n assertRstPoint(other);\n return new RistPoint(this.ep.add(other.ep));\n }\n\n subtract(other: RistPoint): RistPoint {\n assertRstPoint(other);\n return new RistPoint(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiplyUnsafe(scalar));\n }\n}\nexport const RistrettoPoint = /* @__PURE__ */ (() => {\n if (!RistPoint.BASE) RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE);\n if (!RistPoint.ZERO) RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO);\n return RistPoint;\n})();\n\n// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B\nexport const hashToRistretto255 = (msg: Uint8Array, options: htfBasicOpts) => {\n const d = options.DST;\n const DST = typeof d === 'string' ? utf8ToBytes(d) : d;\n const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512);\n const P = RistPoint.hashToCurve(uniform_bytes);\n return P;\n};\nexport const hash_to_ristretto255 = hashToRistretto255; // legacy\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is boolean. */\nexport function abool(b: boolean): void {\n if (typeof b !== 'boolean') throw new Error(`boolean expected, not ${b}`);\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/**\n * Asserts something is hash\n * TODO: remove\n * @deprecated\n */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\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/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n\nexport type IHash = {\n (data: string | Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\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. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('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 Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n// Used in micro\nexport function 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// Used in ff1\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\n\n// Used in micro, ff1\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n\n// TODO: remove\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async (): Promise<void> => {};\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n// TODO: remove\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: string | Uint8Array): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n else if (isBytes(data)) data = copyBytes(data);\n else throw new Error('Uint8Array expected, got ' + typeof data);\n return data;\n}\n\n/**\n * Checks if two U8A use same underlying buffer and overlaps.\n * This is invalid and can corrupt data.\n */\nexport function overlapBytes(a: Uint8Array, b: Uint8Array): boolean {\n return (\n a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy\n a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end\n b.byteOffset < a.byteOffset + a.byteLength // b starts before a end\n );\n}\n\n/**\n * If input and output overlap and input starts before output, we will overwrite end of input before\n * we start processing it, so this is not supported for most ciphers (except chacha/salse, which designed with this)\n */\nexport function complexOverlapBytes(input: Uint8Array, output: Uint8Array): void {\n // This is very cursed. It works somehow, but I'm completely unsure,\n // reasoning about overlapping aligned windows is very hard.\n if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)\n throw new Error('complex overlap of input and output is not supported');\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n// Used in ARX only\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts: T2\n): T1 & T2 {\n if (opts == null || typeof opts !== 'object') throw new Error('options must be defined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Compares 2 uint8array-s in kinda constant time. */\nexport function equalBytes(a: Uint8Array, b: Uint8Array): 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// TODO: remove\n/** For runtime check if class implements interface. */\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: string | Uint8Array): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n}\n\n// This will allow to re-use with composable things like packed & base encoders\n// Also, we probably can make tags composable\n\n/** Sync cipher: takes byte array and returns byte array. */\nexport type Cipher = {\n encrypt(plaintext: Uint8Array): Uint8Array;\n decrypt(ciphertext: Uint8Array): Uint8Array;\n};\n\n/** Async cipher e.g. from built-in WebCrypto. */\nexport type AsyncCipher = {\n encrypt(plaintext: Uint8Array): Promise<Uint8Array>;\n decrypt(ciphertext: Uint8Array): Promise<Uint8Array>;\n};\n\n/** Cipher with `output` argument which can optimize by doing 1 less allocation. */\nexport type CipherWithOutput = Cipher & {\n encrypt(plaintext: Uint8Array, output?: Uint8Array): Uint8Array;\n decrypt(ciphertext: Uint8Array, output?: Uint8Array): Uint8Array;\n};\n\n/**\n * Params are outside of return type, so it is accessible before calling constructor.\n * If function support multiple nonceLength's, we return the best one.\n */\nexport type CipherParams = {\n blockSize: number;\n nonceLength?: number;\n tagLength?: number;\n varSizeNonce?: boolean;\n};\n/** ARX cipher, like salsa or chacha. */\nexport type ARXCipher = ((\n key: Uint8Array,\n nonce: Uint8Array,\n AAD?: Uint8Array\n) => CipherWithOutput) & {\n blockSize: number;\n nonceLength: number;\n tagLength: number;\n};\nexport type CipherCons<T extends any[]> = (key: Uint8Array, ...args: T) => Cipher;\n/**\n * Wraps a cipher: validates args, ensures encrypt() can only be called once.\n * @__NO_SIDE_EFFECTS__\n */\nexport const wrapCipher = <C extends CipherCons<any>, P extends CipherParams>(\n params: P,\n constructor: C\n): C & P => {\n function wrappedCipher(key: Uint8Array, ...args: any[]): CipherWithOutput {\n // Validate key\n abytes(key);\n\n // Big-Endian hardware is rare. Just in case someone still decides to run ciphers:\n if (!isLE) throw new Error('Non little-endian hardware is not yet supported');\n\n // Validate nonce if nonceLength is present\n if (params.nonceLength !== undefined) {\n const nonce = args[0];\n if (!nonce) throw new Error('nonce / iv required');\n if (params.varSizeNonce) abytes(nonce);\n else abytes(nonce, params.nonceLength);\n }\n\n // Validate AAD if tagLength present\n const tagl = params.tagLength;\n if (tagl && args[1] !== undefined) {\n abytes(args[1]);\n }\n\n const cipher = constructor(key, ...args);\n const checkOutput = (fnLength: number, output?: Uint8Array) => {\n if (output !== undefined) {\n if (fnLength !== 2) throw new Error('cipher output not supported');\n abytes(output);\n }\n };\n // Create wrapped cipher with validation and single-use encryption\n let called = false;\n const wrCipher = {\n encrypt(data: Uint8Array, output?: Uint8Array) {\n if (called) throw new Error('cannot encrypt() twice with same key + nonce');\n called = true;\n abytes(data);\n checkOutput(cipher.encrypt.length, output);\n return (cipher as CipherWithOutput).encrypt(data, output);\n },\n decrypt(data: Uint8Array, output?: Uint8Array) {\n abytes(data);\n if (tagl && data.length < tagl)\n throw new Error('invalid ciphertext length: smaller than tagLength=' + tagl);\n checkOutput(cipher.decrypt.length, output);\n return (cipher as CipherWithOutput).decrypt(data, output);\n },\n };\n\n return wrCipher;\n }\n\n Object.assign(wrappedCipher, params);\n return wrappedCipher as C & P;\n};\n\n/** Represents salsa / chacha stream. */\nexport type XorStream = (\n key: Uint8Array,\n nonce: Uint8Array,\n data: Uint8Array,\n output?: Uint8Array,\n counter?: number\n) => Uint8Array;\n\n/**\n * By default, returns u8a of length.\n * When out is available, it checks it for validity and uses it.\n */\nexport function getOutput(\n expectedLength: number,\n out?: Uint8Array,\n onlyAligned = true\n): Uint8Array {\n if (out === undefined) return new Uint8Array(expectedLength);\n if (out.length !== expectedLength)\n throw new Error('invalid output length, expected ' + expectedLength + ', got: ' + out.length);\n if (onlyAligned && !isAligned32(out)) throw new Error('invalid output, must be aligned');\n return out;\n}\n\n/** Polyfill for Safari 14. */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\nexport function u64Lengths(dataLength: number, aadLength: number, isLE: boolean): Uint8Array {\n abool(isLE);\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(aadLength), isLE);\n setBigUint64(view, 8, BigInt(dataLength), isLE);\n return num;\n}\n\n// Is byte array aligned to 4 byte offset (u32)?\nexport function isAligned32(bytes: Uint8Array): boolean {\n return bytes.byteOffset % 4 === 0;\n}\n\n// copy bytes to new u8a (aligned). Because Buffer.slice is broken.\nexport function copyBytes(bytes: Uint8Array): Uint8Array {\n return Uint8Array.from(bytes);\n}\n", "/**\n * Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.\n\nRFC8439 requires multi-step cipher stream, where\nauthKey starts with counter: 0, actual msg with counter: 1.\n\nFor this, we need a way to re-use nonce / counter:\n\n const counter = new Uint8Array(4);\n chacha(..., counter, ...); // counter is now 1\n chacha(..., counter, ...); // counter is now 2\n\nThis is complicated:\n\n- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB\n- Original papers don't allow mutating counters\n- Counter overflow is undefined [^1]\n- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it\n- Caveat: Cannot be re-used through all cases:\n- * chacha has (counter | nonce)\n- * xchacha has (nonce16 | counter | nonce16)\n- Idea B: separate nonce / counter and provide separate API for counter re-use\n- Caveat: there are different counter sizes depending on an algorithm.\n- salsa & chacha also differ in structures of key & sigma:\n salsa20: s[0] | k(4) | s[1] | nonce(2) | ctr(2) | s[2] | k(4) | s[3]\n chacha: s(4) | k(8) | ctr(1) | nonce(3)\n chacha20orig: s(4) | k(8) | ctr(2) | nonce(2)\n- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`\n- Caveat: we can't re-use counter array\n\nxchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal\n(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce).\n\n[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/\n[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2\n\n * @module\n */\n// prettier-ignore\nimport {\n type XorStream, abool, abytes, anumber, checkOpts, clean, copyBytes, u32\n} from './utils.ts';\n\n// We can't make top-level var depend on utils.utf8ToBytes\n// because it's not present in all envs. Creating a similar fn here\nconst _utf8ToBytes = (str: string) => Uint8Array.from(str.split('').map((c) => c.charCodeAt(0)));\nconst sigma16 = _utf8ToBytes('expand 16-byte k');\nconst sigma32 = _utf8ToBytes('expand 32-byte k');\nconst sigma16_32 = u32(sigma16);\nconst sigma32_32 = u32(sigma32);\n\nexport function rotl(a: number, b: number): number {\n return (a << b) | (a >>> (32 - b));\n}\n\n/** Ciphers must use u32 for efficiency. */\nexport type CipherCoreFn = (\n sigma: Uint32Array,\n key: Uint32Array,\n nonce: Uint32Array,\n output: Uint32Array,\n counter: number,\n rounds?: number\n) => void;\n\n/** Method which extends key + short nonce into larger nonce / diff key. */\nexport type ExtendNonceFn = (\n sigma: Uint32Array,\n key: Uint32Array,\n input: Uint32Array,\n output: Uint32Array\n) => void;\n\n/** ARX cipher options.\n * * `allowShortKeys` for 16-byte keys\n * * `counterLength` in bytes\n * * `counterRight`: right: `nonce|counter`; left: `counter|nonce`\n * */\nexport type CipherOpts = {\n allowShortKeys?: boolean; // Original salsa / chacha allow 16-byte keys\n extendNonceFn?: ExtendNonceFn;\n counterLength?: number;\n counterRight?: boolean;\n rounds?: number;\n};\n\n// Is byte array aligned to 4 byte offset (u32)?\nfunction isAligned32(b: Uint8Array) {\n return b.byteOffset % 4 === 0;\n}\n\n// Salsa and Chacha block length is always 512-bit\nconst BLOCK_LEN = 64;\nconst BLOCK_LEN32 = 16;\n\n// new Uint32Array([2**32]) // => Uint32Array(1) [ 0 ]\n// new Uint32Array([2**32-1]) // => Uint32Array(1) [ 4294967295 ]\nconst MAX_COUNTER = 2 ** 32 - 1;\n\nconst U32_EMPTY = new Uint32Array();\nfunction runCipher(\n core: CipherCoreFn,\n sigma: Uint32Array,\n key: Uint32Array,\n nonce: Uint32Array,\n data: Uint8Array,\n output: Uint8Array,\n counter: number,\n rounds: number\n): void {\n const len = data.length;\n const block = new Uint8Array(BLOCK_LEN);\n const b32 = u32(block);\n // Make sure that buffers aligned to 4 bytes\n const isAligned = isAligned32(data) && isAligned32(output);\n const d32 = isAligned ? u32(data) : U32_EMPTY;\n const o32 = isAligned ? u32(output) : U32_EMPTY;\n for (let pos = 0; pos < len; counter++) {\n core(sigma, key, nonce, b32, counter, rounds);\n if (counter >= MAX_COUNTER) throw new Error('arx: counter overflow');\n const take = Math.min(BLOCK_LEN, len - pos);\n // aligned to 4 bytes\n if (isAligned && take === BLOCK_LEN) {\n const pos32 = pos / 4;\n if (pos % 4 !== 0) throw new Error('arx: invalid block position');\n for (let j = 0, posj: number; j < BLOCK_LEN32; j++) {\n posj = pos32 + j;\n o32[posj] = d32[posj] ^ b32[j];\n }\n pos += BLOCK_LEN;\n continue;\n }\n for (let j = 0, posj; j < take; j++) {\n posj = pos + j;\n output[posj] = data[posj] ^ block[j];\n }\n pos += take;\n }\n}\n\n/** Creates ARX-like (ChaCha, Salsa) cipher stream from core function. */\nexport function createCipher(core: CipherCoreFn, opts: CipherOpts): XorStream {\n const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts(\n { allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 },\n opts\n );\n if (typeof core !== 'function') throw new Error('core must be a function');\n anumber(counterLength);\n anumber(rounds);\n abool(counterRight);\n abool(allowShortKeys);\n return (\n key: Uint8Array,\n nonce: Uint8Array,\n data: Uint8Array,\n output?: Uint8Array,\n counter = 0\n ): Uint8Array => {\n abytes(key);\n abytes(nonce);\n abytes(data);\n const len = data.length;\n if (output === undefined) output = new Uint8Array(len);\n abytes(output);\n anumber(counter);\n if (counter < 0 || counter >= MAX_COUNTER) throw new Error('arx: counter overflow');\n if (output.length < len)\n throw new Error(`arx: output (${output.length}) is shorter than data (${len})`);\n const toClean = [];\n\n // Key & sigma\n // key=16 -> sigma16, k=key|key\n // key=32 -> sigma32, k=key\n let l = key.length;\n let k: Uint8Array;\n let sigma: Uint32Array;\n if (l === 32) {\n toClean.push((k = copyBytes(key)));\n sigma = sigma32_32;\n } else if (l === 16 && allowShortKeys) {\n k = new Uint8Array(32);\n k.set(key);\n k.set(key, 16);\n sigma = sigma16_32;\n toClean.push(k);\n } else {\n throw new Error(`arx: invalid 32-byte key, got length=${l}`);\n }\n\n // Nonce\n // salsa20: 8 (8-byte counter)\n // chacha20orig: 8 (8-byte counter)\n // chacha20: 12 (4-byte counter)\n // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)\n // xchacha20: 24 (16 -> hchacha, 8 -> old nonce)\n // Align nonce to 4 bytes\n if (!isAligned32(nonce)) toClean.push((nonce = copyBytes(nonce)));\n\n const k32 = u32(k);\n // hsalsa & hchacha: handle extended nonce\n if (extendNonceFn) {\n if (nonce.length !== 24) throw new Error(`arx: extended nonce must be 24 bytes`);\n extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32);\n nonce = nonce.subarray(16);\n }\n\n // Handle nonce counter\n const nonceNcLen = 16 - counterLength;\n if (nonceNcLen !== nonce.length)\n throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);\n\n // Pad counter when nonce is 64 bit\n if (nonceNcLen !== 12) {\n const nc = new Uint8Array(12);\n nc.set(nonce, counterRight ? 0 : 12 - nonce.length);\n nonce = nc;\n toClean.push(nonce);\n }\n const n32 = u32(nonce);\n runCipher(core, sigma, k32, n32, data, output, counter, rounds);\n clean(...toClean);\n return output;\n };\n}\n", "/**\n * Poly1305 ([PDF](https://cr.yp.to/mac/poly1305-20050329.pdf),\n * [wiki](https://en.wikipedia.org/wiki/Poly1305))\n * is a fast and parallel secret-key message-authentication code suitable for\n * a wide variety of applications. It was standardized in\n * [RFC 8439](https://datatracker.ietf.org/doc/html/rfc8439) and is now used in TLS 1.3.\n *\n * Polynomial MACs are not perfect for every situation:\n * they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.\n * See [invisible salamanders attack](https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/).\n * To combat invisible salamanders, `hash(key)` can be included in ciphertext,\n * however, this would violate ciphertext indistinguishability:\n * an attacker would know which key was used - so `HKDF(key, i)`\n * could be used instead.\n *\n * Check out [original website](https://cr.yp.to/mac.html).\n * @module\n */\nimport { Hash, type Input, abytes, aexists, aoutput, clean, toBytes } from './utils.ts';\n\n// Based on Public Domain poly1305-donna https://github.com/floodyberry/poly1305-donna\nconst u8to16 = (a: Uint8Array, i: number) => (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);\nclass Poly1305 implements Hash<Poly1305> {\n readonly blockLen = 16;\n readonly outputLen = 16;\n private buffer = new Uint8Array(16);\n private r = new Uint16Array(10);\n private h = new Uint16Array(10);\n private pad = new Uint16Array(8);\n private pos = 0;\n protected finished = false;\n\n constructor(key: Input) {\n key = toBytes(key);\n abytes(key, 32);\n const t0 = u8to16(key, 0);\n const t1 = u8to16(key, 2);\n const t2 = u8to16(key, 4);\n const t3 = u8to16(key, 6);\n const t4 = u8to16(key, 8);\n const t5 = u8to16(key, 10);\n const t6 = u8to16(key, 12);\n const t7 = u8to16(key, 14);\n\n // https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47\n this.r[0] = t0 & 0x1fff;\n this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this.r[5] = (t4 >>> 1) & 0x1ffe;\n this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this.r[9] = (t7 >>> 5) & 0x007f;\n for (let i = 0; i < 8; i++) this.pad[i] = u8to16(key, 16 + 2 * i);\n }\n\n private process(data: Uint8Array, offset: number, isLast = false) {\n const hibit = isLast ? 0 : 1 << 11;\n const { h, r } = this;\n const r0 = r[0];\n const r1 = r[1];\n const r2 = r[2];\n const r3 = r[3];\n const r4 = r[4];\n const r5 = r[5];\n const r6 = r[6];\n const r7 = r[7];\n const r8 = r[8];\n const r9 = r[9];\n\n const t0 = u8to16(data, offset + 0);\n const t1 = u8to16(data, offset + 2);\n const t2 = u8to16(data, offset + 4);\n const t3 = u8to16(data, offset + 6);\n const t4 = u8to16(data, offset + 8);\n const t5 = u8to16(data, offset + 10);\n const t6 = u8to16(data, offset + 12);\n const t7 = u8to16(data, offset + 14);\n\n let h0 = h[0] + (t0 & 0x1fff);\n let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);\n let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);\n let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);\n let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);\n let h5 = h[5] + ((t4 >>> 1) & 0x1fff);\n let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);\n let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);\n let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);\n let h9 = h[9] + ((t7 >>> 5) | hibit);\n\n let c = 0;\n\n let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);\n c = d0 >>> 13;\n d0 &= 0x1fff;\n d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);\n c += d0 >>> 13;\n d0 &= 0x1fff;\n\n let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);\n c = d1 >>> 13;\n d1 &= 0x1fff;\n d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);\n c += d1 >>> 13;\n d1 &= 0x1fff;\n\n let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);\n c = d2 >>> 13;\n d2 &= 0x1fff;\n d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);\n c += d2 >>> 13;\n d2 &= 0x1fff;\n\n let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);\n c = d3 >>> 13;\n d3 &= 0x1fff;\n d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);\n c += d3 >>> 13;\n d3 &= 0x1fff;\n\n let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;\n c = d4 >>> 13;\n d4 &= 0x1fff;\n d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);\n c += d4 >>> 13;\n d4 &= 0x1fff;\n\n let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;\n c = d5 >>> 13;\n d5 &= 0x1fff;\n d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);\n c += d5 >>> 13;\n d5 &= 0x1fff;\n\n let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;\n c = d6 >>> 13;\n d6 &= 0x1fff;\n d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);\n c += d6 >>> 13;\n d6 &= 0x1fff;\n\n let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;\n c = d7 >>> 13;\n d7 &= 0x1fff;\n d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);\n c += d7 >>> 13;\n d7 &= 0x1fff;\n\n let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;\n c = d8 >>> 13;\n d8 &= 0x1fff;\n d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);\n c += d8 >>> 13;\n d8 &= 0x1fff;\n\n let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;\n c = d9 >>> 13;\n d9 &= 0x1fff;\n d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;\n c += d9 >>> 13;\n d9 &= 0x1fff;\n\n c = ((c << 2) + c) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = c >>> 13;\n d1 += c;\n\n h[0] = d0;\n h[1] = d1;\n h[2] = d2;\n h[3] = d3;\n h[4] = d4;\n h[5] = d5;\n h[6] = d6;\n h[7] = d7;\n h[8] = d8;\n h[9] = d9;\n }\n\n private finalize() {\n const { h, pad } = this;\n const g = new Uint16Array(10);\n let c = h[1] >>> 13;\n h[1] &= 0x1fff;\n for (let i = 2; i < 10; i++) {\n h[i] += c;\n c = h[i] >>> 13;\n h[i] &= 0x1fff;\n }\n h[0] += c * 5;\n c = h[0] >>> 13;\n h[0] &= 0x1fff;\n h[1] += c;\n c = h[1] >>> 13;\n h[1] &= 0x1fff;\n h[2] += c;\n\n g[0] = h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (let i = 1; i < 10; i++) {\n g[i] = h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= 1 << 13;\n\n let mask = (c ^ 1) - 1;\n for (let i = 0; i < 10; i++) g[i] &= mask;\n mask = ~mask;\n for (let i = 0; i < 10; i++) h[i] = (h[i] & mask) | g[i];\n h[0] = (h[0] | (h[1] << 13)) & 0xffff;\n h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;\n h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;\n h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;\n h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;\n h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;\n h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;\n h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;\n\n let f = h[0] + pad[0];\n h[0] = f & 0xffff;\n for (let i = 1; i < 8; i++) {\n f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;\n h[i] = f & 0xffff;\n }\n clean(g);\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { buffer, blockLen } = this;\n const len = data.length;\n\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input\n if (take === blockLen) {\n for (; blockLen <= len - pos; pos += blockLen) this.process(data, 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(buffer, 0, false);\n this.pos = 0;\n }\n }\n return this;\n }\n destroy() {\n clean(this.h, this.r, this.buffer, this.pad);\n }\n digestInto(out: Uint8Array) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { buffer, h } = this;\n let { pos } = this;\n if (pos) {\n buffer[pos++] = 1;\n for (; pos < 16; pos++) buffer[pos] = 0;\n this.process(buffer, 0, true);\n }\n this.finalize();\n let opos = 0;\n for (let i = 0; i < 8; i++) {\n out[opos++] = h[i] >>> 0;\n out[opos++] = h[i] >>> 8;\n }\n return out;\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n}\n\nexport type CHash = ReturnType<typeof wrapConstructorWithKey>;\nexport function wrapConstructorWithKey<H extends Hash<H>>(\n hashCons: (key: Input) => Hash<H>\n): {\n (msg: Input, key: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(key: Input): Hash<H>;\n} {\n const hashC = (msg: Input, key: Input): Uint8Array => hashCons(key).update(toBytes(msg)).digest();\n const tmp = hashCons(new Uint8Array(32));\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (key: Input) => hashCons(key);\n return hashC;\n}\n\n/** Poly1305 MAC from RFC 8439. */\nexport const poly1305: CHash = wrapConstructorWithKey((key) => new Poly1305(key));\n", "/**\n * [ChaCha20](https://cr.yp.to/chacha.html) stream cipher, released\n * in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.\n * It was standardized in [RFC 8439](https://datatracker.ietf.org/doc/html/rfc8439) and\n * is now used in TLS 1.3.\n *\n * [XChaCha20](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha)\n * extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with\n * randomly-generated nonces.\n *\n * Check out [PDF](http://cr.yp.to/chacha/chacha-20080128.pdf) and\n * [wiki](https://en.wikipedia.org/wiki/Salsa20).\n * @module\n */\nimport { createCipher, rotl } from './_arx.ts';\nimport { poly1305 } from './_poly1305.ts';\nimport {\n type ARXCipher,\n type CipherWithOutput,\n type XorStream,\n clean,\n equalBytes,\n getOutput,\n u64Lengths,\n wrapCipher,\n} from './utils.ts';\n\n/**\n * ChaCha core function.\n */\n// prettier-ignore\nfunction chachaCore(\n s: Uint32Array, k: Uint32Array, n: Uint32Array, out: Uint32Array, cnt: number, rounds = 20\n): void {\n let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // \"expa\" \"nd 3\" \"2-by\" \"te k\"\n y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key\n y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key\n y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Counter\tNonce Nonce\n // Save state to temporary variables\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03,\n x04 = y04, x05 = y05, x06 = y06, x07 = y07,\n x08 = y08, x09 = y09, x10 = y10, x11 = y11,\n x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n for (let r = 0; r < rounds; r += 2) {\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);\n\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);\n\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);\n\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);\n\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);\n\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);\n\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);\n\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);\n }\n // Write output\n let oi = 0;\n out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0;\n}\n/**\n * hchacha helper method, used primarily in xchacha, to hash\n * key and nonce into key' and nonce'.\n * Same as chachaCore, but there doesn't seem to be a way to move the block\n * out without 25% performance hit.\n */\n// prettier-ignore\nexport function hchacha(\n s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array\n): void {\n let x00 = s[0], x01 = s[1], x02 = s[2], x03 = s[3],\n x04 = k[0], x05 = k[1], x06 = k[2], x07 = k[3],\n x08 = k[4], x09 = k[5], x10 = k[6], x11 = k[7],\n x12 = i[0], x13 = i[1], x14 = i[2], x15 = i[3];\n for (let r = 0; r < 20; r += 2) {\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);\n\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);\n\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);\n\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);\n\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);\n\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);\n\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);\n\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);\n }\n let oi = 0;\n o32[oi++] = x00; o32[oi++] = x01;\n o32[oi++] = x02; o32[oi++] = x03;\n o32[oi++] = x12; o32[oi++] = x13;\n o32[oi++] = x14; o32[oi++] = x15;\n}\n/**\n * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.\n */\nexport const chacha20orig: XorStream = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n allowShortKeys: true,\n});\n/**\n * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.\n * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.\n */\nexport const chacha20: XorStream = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n allowShortKeys: false,\n});\n\n/**\n * XChaCha eXtended-nonce ChaCha. 24-byte nonce.\n * With 24-byte nonce, it's safe to use fill it with random (CSPRNG).\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha\n */\nexport const xchacha20: XorStream = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n extendNonceFn: hchacha,\n allowShortKeys: false,\n});\n\n/**\n * Reduced 8-round chacha, described in original paper.\n */\nexport const chacha8: XorStream = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 8,\n});\n\n/**\n * Reduced 12-round chacha, described in original paper.\n */\nexport const chacha12: XorStream = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 12,\n});\n\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\n// Pad to digest size with zeros\nconst updatePadded = (h: ReturnType<typeof poly1305.create>, msg: Uint8Array) => {\n h.update(msg);\n const left = msg.length % 16;\n if (left) h.update(ZEROS16.subarray(left));\n};\n\nconst ZEROS32 = /* @__PURE__ */ new Uint8Array(32);\nfunction computeTag(\n fn: XorStream,\n key: Uint8Array,\n nonce: Uint8Array,\n data: Uint8Array,\n AAD?: Uint8Array\n): Uint8Array {\n const authKey = fn(key, nonce, ZEROS32);\n const h = poly1305.create(authKey);\n if (AAD) updatePadded(h, AAD);\n updatePadded(h, data);\n const num = u64Lengths(data.length, AAD ? AAD.length : 0, true);\n h.update(num);\n const res = h.digest();\n clean(authKey, num);\n return res;\n}\n\n/**\n * AEAD algorithm from RFC 8439.\n * Salsa20 and chacha (RFC 8439) use poly1305 differently.\n * We could have composed them similar to:\n * https://github.com/paulmillr/scure-base/blob/b266c73dde977b1dd7ef40ef7a23cc15aab526b3/index.ts#L250\n * But it's hard because of authKey:\n * In salsa20, authKey changes position in salsa stream.\n * In chacha, authKey can't be computed inside computeTag, it modifies the counter.\n */\nexport const _poly1305_aead =\n (xorStream: XorStream) =>\n (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): CipherWithOutput => {\n const tagLength = 16;\n return {\n encrypt(plaintext: Uint8Array, output?: Uint8Array) {\n const plength = plaintext.length;\n output = getOutput(plength + tagLength, output, false);\n output.set(plaintext);\n const oPlain = output.subarray(0, -tagLength);\n xorStream(key, nonce, oPlain, oPlain, 1);\n const tag = computeTag(xorStream, key, nonce, oPlain, AAD);\n output.set(tag, plength); // append tag\n clean(tag);\n return output;\n },\n decrypt(ciphertext: Uint8Array, output?: Uint8Array) {\n output = getOutput(ciphertext.length - tagLength, output, false);\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = computeTag(xorStream, key, nonce, data, AAD);\n if (!equalBytes(passedTag, tag)) throw new Error('invalid tag');\n output.set(ciphertext.subarray(0, -tagLength));\n xorStream(key, nonce, output, output, 1); // start stream with i=1\n clean(tag);\n return output;\n },\n };\n };\n\n/**\n * ChaCha20-Poly1305 from RFC 8439.\n *\n * Unsafe to use random nonces under the same key, due to collision chance.\n * Prefer XChaCha instead.\n */\nexport const chacha20poly1305: ARXCipher = /* @__PURE__ */ wrapCipher(\n { blockSize: 64, nonceLength: 12, tagLength: 16 },\n _poly1305_aead(chacha20)\n);\n/**\n * XChaCha20-Poly1305 extended-nonce chacha.\n *\n * Can be safely used with random nonces (CSPRNG).\n * See [IRTF draft](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha).\n */\nexport const xchacha20poly1305: ARXCipher = /* @__PURE__ */ wrapCipher(\n { blockSize: 64, nonceLength: 24, tagLength: 16 },\n _poly1305_aead(xchacha20)\n);\n", "import { SHA2 } from './_sha2.js';\nimport { rotr, wrapConstructor } from './utils.js';\n\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n\n// Choice: a ? b : c\nconst Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c);\n// Majority function, true if any two inpust is true\nconst Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c);\n\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */new Uint32Array([\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// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n// prettier-ignore\nconst IV = /* @__PURE__ */new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nclass SHA256 extends SHA2<SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = IV[0] | 0;\n B = IV[1] | 0;\n C = IV[2] | 0;\n D = IV[3] | 0;\n E = IV[4] | 0;\n F = IV[5] | 0;\n G = IV[6] | 0;\n H = IV[7] | 0;\n\n constructor() {\n super(64, 32, 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 ) {\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() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n A = 0xc1059ed8 | 0;\n B = 0x367cd507 | 0;\n C = 0x3070dd17 | 0;\n D = 0xf70e5939 | 0;\n E = 0xffc00b31 | 0;\n F = 0x68581511 | 0;\n G = 0x64f98fa7 | 0;\n H = 0xbefa4fa4 | 0;\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n", "import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js';\nimport { Hash, CHash, Input, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC<T extends Hash<T>> extends Hash<HMAC<T>> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: CHash, _key: Input) {\n super();\n assertHash(hash);\n const key = toBytes(_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 first block) of outer hash here 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 pad.fill(0);\n }\n update(buf: Input) {\n assertExists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array) {\n assertExists(this);\n assertBytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to?: HMAC<T>): HMAC<T> {\n // Create new instance without calling constructor since key 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 destroy() {\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 - message key\n * @param message - message data\n */\nexport const hmac = (hash: CHash, key: Input, message: Input): Uint8Array =>\n new HMAC<any>(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Input) => new HMAC<any>(hash, key);\n", "import { hash as assertHash, number as assertNumber } from './_assert.js';\nimport { CHash, Input, toBytes } from './utils.js';\nimport { hmac } from './hmac.js';\n\n// HKDF (RFC 5869)\n// https://soatok.blog/2021/11/17/understanding-hkdf/\n\n/**\n * HKDF-Extract(IKM, salt) -> PRK\n * Arguments position differs from spec (IKM is first one, since it is not optional)\n * @param hash\n * @param ikm\n * @param salt\n * @returns\n */\nexport function extract(hash: CHash, ikm: Input, salt?: Input) {\n assertHash(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); // if not provided, it is set to a string of HashLen zeros\n return hmac(hash, toBytes(salt), toBytes(ikm));\n}\n\n// HKDF-Expand(PRK, info, L) -> OKM\nconst HKDF_COUNTER = /* @__PURE__ */ new Uint8Array([0]);\nconst EMPTY_BUFFER = /* @__PURE__ */ new Uint8Array();\n\n/**\n * HKDF-expand from the spec.\n * @param prk - a pseudorandom key of at least HashLen octets (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 octets\n */\nexport function expand(hash: CHash, prk: Input, info?: Input, length: number = 32) {\n assertHash(hash);\n assertNumber(length);\n if (length > 255 * hash.outputLen) throw new Error('Length should be <= 255*HashLen');\n const blocks = Math.ceil(length / hash.outputLen);\n if (info === undefined) info = EMPTY_BUFFER;\n // first L(ength) octets of T\n const okm = new Uint8Array(blocks * hash.outputLen);\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, hash.outputLen * counter);\n HMAC._cloneInto(HMACTmp);\n }\n HMAC.destroy();\n HMACTmp.destroy();\n T.fill(0);\n HKDF_COUNTER.fill(0);\n return okm.slice(0, length);\n}\n\n/**\n * HKDF (RFC 5869): extract + 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\n * @param length - length of output keying material in octets\n */\nexport const hkdf = (\n hash: CHash,\n ikm: Input,\n salt: Input | undefined,\n info: Input | undefined,\n length: number\n) => expand(hash, extract(hash, ikm, salt), info, length);\n", "/**\n * noise.mjs \u2014 Noise_IK_25519_ChaChaPoly_SHA256 implementation for viveworker\n * remote pairing.\n *\n * Why IK:\n * - Initiator (phone) knows responder's (PC bridge's) static public key\n * a priori, established during LAN-bootstrap pairing. This lets us do a\n * 1-RTT handshake with mutual authentication (both sides' static keys\n * are bound into the transcript).\n * - The relay (CF Worker + Durable Object) carries Noise messages opaquely;\n * it cannot decrypt anything, only route by an outer envelope's `pairingId`.\n *\n * Wire layout (this module's responsibility ends at \"Noise transport message\"):\n *\n * WSS frame body\n * \u2514\u2500 outer envelope (relay sees this; defined elsewhere)\n * \u251C\u2500 seq, mid, type, ... \u2190 routing-only metadata\n * \u2514\u2500 payload: bytes \u2190 Noise transport message (this module)\n * \u2514\u2500 ciphertext + 16-byte Poly1305 tag\n *\n * Handshake:\n * pre-message: <- s (responder's static public key, OOB at pairing)\n * message 1 (i\u2192r): -> e, es, s, ss (initiator sends ephemeral, encrypts its static)\n * message 2 (r\u2192i): <- e, ee, se (responder sends ephemeral, completes auth)\n * then Split() yields cs1 (i\u2192r) and cs2 (r\u2192i) for transport.\n *\n * Reference: https://noiseprotocol.org/noise.html (revision 34)\n */\n\nimport { x25519 } from \"@noble/curves/ed25519\";\nimport { chacha20poly1305 } from \"@noble/ciphers/chacha\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport { hkdf } from \"@noble/hashes/hkdf\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nexport const PROTOCOL_NAME = \"Noise_IK_25519_ChaChaPoly_SHA256\";\nexport const HASHLEN = 32;\nexport const KEYLEN = 32;\nexport const DHLEN = 32;\nexport const TAGLEN = 16;\nexport const NONCE_MAX = 0xffff_ffff_ffff_ffffn; // 2^64 - 1; reserved as \"rekey\" in Noise\n\nconst PROTOCOL_NAME_BYTES = new TextEncoder().encode(PROTOCOL_NAME);\n\n// ---------------------------------------------------------------------------\n// Byte helpers (Uint8Array everywhere \u2014 no Buffer leakage so PWA can share)\n// ---------------------------------------------------------------------------\n\nfunction concat(...arrays) {\n let total = 0;\n for (const a of arrays) total += a.length;\n const out = new Uint8Array(total);\n let offset = 0;\n for (const a of arrays) {\n out.set(a, offset);\n offset += a.length;\n }\n return out;\n}\n\nfunction asBytes(input) {\n if (input == null) return new Uint8Array(0);\n if (input instanceof Uint8Array) return input;\n if (typeof input === \"string\") return new TextEncoder().encode(input);\n if (Array.isArray(input)) return new Uint8Array(input);\n throw new TypeError(`unsupported input type: ${typeof input}`);\n}\n\nfunction timingSafeEqual(a, 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// Noise primitives\n// ---------------------------------------------------------------------------\n\nfunction noiseHash(data) {\n return sha256(data);\n}\n\n/** HKDF with `n_outputs` 32-byte outputs, per Noise spec \u00A74.3. */\nfunction noiseHkdf(ck, ikm, nOutputs) {\n const length = nOutputs * HASHLEN;\n const out = hkdf(sha256, ikm, ck, new Uint8Array(0), length);\n const slices = [];\n for (let i = 0; i < nOutputs; i++) {\n slices.push(out.slice(i * HASHLEN, (i + 1) * HASHLEN));\n }\n return slices;\n}\n\nfunction generateKeypair() {\n const priv = x25519.utils.randomPrivateKey();\n const pub = x25519.getPublicKey(priv);\n return { priv, pub };\n}\n\nfunction dh(priv, pub) {\n return x25519.getSharedSecret(priv, pub);\n}\n\n/**\n * Format the AEAD nonce as 4 zero bytes (big-endian) followed by an 8-byte\n * little-endian counter. This matches the Noise spec \u00A75.1.\n */\nfunction formatNonce(counter) {\n const out = new Uint8Array(12);\n let v = BigInt(counter);\n for (let i = 4; i < 12; i++) {\n out[i] = Number(v & 0xffn);\n v >>= 8n;\n }\n return out;\n}\n\nfunction aeadEncrypt(key, counter, ad, plaintext) {\n const cipher = chacha20poly1305(key, formatNonce(counter), asBytes(ad));\n return cipher.encrypt(asBytes(plaintext));\n}\n\nfunction aeadDecrypt(key, counter, ad, ciphertext) {\n const cipher = chacha20poly1305(key, formatNonce(counter), asBytes(ad));\n return cipher.decrypt(asBytes(ciphertext));\n}\n\n// ---------------------------------------------------------------------------\n// CipherState\n// ---------------------------------------------------------------------------\n\n/**\n * A single-direction symmetric cipher with a counter nonce. Used as building\n * block for SymmetricState (during handshake) and standalone for transport\n * messages after Split().\n */\nclass CipherState {\n constructor(key = null) {\n /** @type {Uint8Array | null} */\n this.k = key;\n this.n = 0n;\n }\n\n hasKey() {\n return this.k != null;\n }\n\n setKey(key) {\n this.k = key;\n this.n = 0n;\n }\n\n encryptWithAd(ad, plaintext) {\n if (!this.hasKey()) return asBytes(plaintext);\n if (this.n >= NONCE_MAX) throw new Error(\"nonce exhausted\");\n const ct = aeadEncrypt(this.k, this.n, ad, plaintext);\n this.n += 1n;\n return ct;\n }\n\n decryptWithAd(ad, ciphertext) {\n if (!this.hasKey()) return asBytes(ciphertext);\n if (this.n >= NONCE_MAX) throw new Error(\"nonce exhausted\");\n const pt = aeadDecrypt(this.k, this.n, ad, ciphertext);\n this.n += 1n;\n return pt;\n }\n}\n\n// ---------------------------------------------------------------------------\n// SymmetricState\n// ---------------------------------------------------------------------------\n\n/**\n * Wraps a CipherState plus a chaining key (`ck`) and handshake hash (`h`).\n * Drives MixKey / MixHash / EncryptAndHash / DecryptAndHash.\n */\nclass SymmetricState {\n constructor(protocolName) {\n const nameBytes = asBytes(protocolName);\n if (nameBytes.length <= HASHLEN) {\n this.h = new Uint8Array(HASHLEN);\n this.h.set(nameBytes, 0);\n } else {\n this.h = noiseHash(nameBytes);\n }\n this.ck = this.h.slice();\n this.cipher = new CipherState();\n }\n\n mixKey(ikm) {\n const [ck, tempK] = noiseHkdf(this.ck, ikm, 2);\n this.ck = ck;\n // Per Noise \u00A75.2: truncate temp_k to KEYLEN (32). With SHA256 these are\n // already equal so this is a no-op, but keep the slice for clarity.\n this.cipher.setKey(tempK.slice(0, KEYLEN));\n }\n\n mixHash(data) {\n this.h = noiseHash(concat(this.h, asBytes(data)));\n }\n\n encryptAndHash(plaintext) {\n const ct = this.cipher.encryptWithAd(this.h, plaintext);\n this.mixHash(ct);\n return ct;\n }\n\n decryptAndHash(ciphertext) {\n const pt = this.cipher.decryptWithAd(this.h, ciphertext);\n this.mixHash(ciphertext);\n return pt;\n }\n\n /** Final step: produce two CipherStates for transport (initiator\u2192responder, responder\u2192initiator). */\n split() {\n const [k1, k2] = noiseHkdf(this.ck, new Uint8Array(0), 2);\n return [new CipherState(k1.slice(0, KEYLEN)), new CipherState(k2.slice(0, KEYLEN))];\n }\n}\n\n// ---------------------------------------------------------------------------\n// HandshakeState \u2014 Noise IK\n// ---------------------------------------------------------------------------\n\n/**\n * Drive an IK handshake. Caller wires the `writeMessage` / `readMessage` calls\n * to the underlying transport (WSS, in our production path; stdio pipes in\n * the Phase 0 test harness).\n *\n * @param {object} opts\n * @param {boolean} opts.initiator - True for phone, false for PC bridge.\n * @param {{priv: Uint8Array, pub: Uint8Array}} opts.staticKeypair - Long-term identity keypair.\n * @param {Uint8Array} [opts.remoteStatic] - Required if initiator; remote's identity public key.\n * @param {Uint8Array} [opts.prologue] - Pre-handshake context bytes hashed into both transcripts. Empty by default.\n */\nexport class HandshakeState {\n constructor({ initiator, staticKeypair, remoteStatic, prologue = new Uint8Array(0) }) {\n if (typeof initiator !== \"boolean\") throw new TypeError(\"initiator must be boolean\");\n if (!staticKeypair?.priv || !staticKeypair?.pub) throw new TypeError(\"staticKeypair required\");\n if (initiator && !remoteStatic) throw new Error(\"initiator requires remoteStatic (responder's public key)\");\n\n this.initiator = initiator;\n this.s = staticKeypair;\n this.rs = remoteStatic ? asBytes(remoteStatic) : null;\n /** @type {{priv: Uint8Array, pub: Uint8Array} | null} */\n this.e = null;\n /** @type {Uint8Array | null} */\n this.re = null;\n\n this.symmetric = new SymmetricState(PROTOCOL_NAME);\n this.symmetric.mixHash(prologue);\n\n // Pre-message: <- s (responder's static public key, both sides hash it)\n if (initiator) {\n this.symmetric.mixHash(this.rs);\n } else {\n this.symmetric.mixHash(this.s.pub);\n }\n\n /** @type {0|1|2} - 0 = waiting to send/recv message 1, 1 = ready for message 2, 2 = done */\n this.step = 0;\n /** @type {[CipherState, CipherState] | null} */\n this.transportCiphers = null;\n /** @type {Uint8Array | null} - Final h, can be used as channel binding */\n this.handshakeHash = null;\n }\n\n /** Write the next handshake message and return the bytes to put on the wire. */\n writeMessage(payload = new Uint8Array(0)) {\n const pt = asBytes(payload);\n if (this.step === 0 && this.initiator) {\n // -> e, es, s, ss\n this.e = generateKeypair();\n const buf = [];\n buf.push(this.e.pub);\n this.symmetric.mixHash(this.e.pub);\n this.symmetric.mixKey(dh(this.e.priv, this.rs)); // es\n buf.push(this.symmetric.encryptAndHash(this.s.pub)); // s (encrypted)\n this.symmetric.mixKey(dh(this.s.priv, this.rs)); // ss\n buf.push(this.symmetric.encryptAndHash(pt)); // payload\n this.step = 1;\n return concat(...buf);\n }\n if (this.step === 1 && !this.initiator) {\n // <- e, ee, se\n // Token names use Noise's \"first letter = initiator's key, second = responder's key\"\n // convention. So `se` = DH(initiator.s, responder.e). On the responder\n // side we compute that as DH(responder.e.priv, initiator.s.pub).\n this.e = generateKeypair();\n const buf = [];\n buf.push(this.e.pub);\n this.symmetric.mixHash(this.e.pub);\n this.symmetric.mixKey(dh(this.e.priv, this.re)); // ee = DH(responder.e.priv, initiator.e.pub)\n this.symmetric.mixKey(dh(this.e.priv, this.rs)); // se = DH(responder.e.priv, initiator.s.pub)\n buf.push(this.symmetric.encryptAndHash(pt)); // payload\n this._finalize();\n return concat(...buf);\n }\n throw new Error(`writeMessage called in unexpected state (step=${this.step}, initiator=${this.initiator})`);\n }\n\n /** Consume a received handshake message and return the decrypted payload. */\n readMessage(bytes) {\n const data = asBytes(bytes);\n let offset = 0;\n if (this.step === 0 && !this.initiator) {\n // -> e, es, s, ss (responder receiving)\n const re = data.slice(offset, offset + DHLEN);\n offset += DHLEN;\n this.re = re;\n this.symmetric.mixHash(re);\n this.symmetric.mixKey(dh(this.s.priv, re)); // es (responder uses its static)\n const sCiphertext = data.slice(offset, offset + DHLEN + TAGLEN);\n offset += DHLEN + TAGLEN;\n const remoteStatic = this.symmetric.decryptAndHash(sCiphertext);\n this.rs = remoteStatic;\n this.symmetric.mixKey(dh(this.s.priv, remoteStatic)); // ss\n const payload = this.symmetric.decryptAndHash(data.slice(offset));\n this.step = 1;\n return payload;\n }\n if (this.step === 1 && this.initiator) {\n // <- e, ee, se (initiator receiving)\n // `se` = DH(initiator.s, responder.e). On the initiator side we have\n // our own static priv plus responder's ephemeral pub from this message.\n const re = data.slice(offset, offset + DHLEN);\n offset += DHLEN;\n this.re = re;\n this.symmetric.mixHash(re);\n this.symmetric.mixKey(dh(this.e.priv, re)); // ee = DH(initiator.e.priv, responder.e.pub)\n this.symmetric.mixKey(dh(this.s.priv, re)); // se = DH(initiator.s.priv, responder.e.pub)\n const payload = this.symmetric.decryptAndHash(data.slice(offset));\n this._finalize();\n return payload;\n }\n throw new Error(`readMessage called in unexpected state (step=${this.step}, initiator=${this.initiator})`);\n }\n\n _finalize() {\n this.handshakeHash = this.symmetric.h.slice();\n const [cs1, cs2] = this.symmetric.split();\n // cs1 = initiator \u2192 responder, cs2 = responder \u2192 initiator\n this.transportCiphers = [cs1, cs2];\n this.step = 2;\n }\n\n isHandshakeFinished() {\n return this.step === 2;\n }\n\n /** After handshake, return a NoiseSession for transport messages. */\n intoSession() {\n if (!this.isHandshakeFinished()) throw new Error(\"handshake not finished\");\n const [cs1, cs2] = this.transportCiphers;\n return new NoiseSession({\n initiator: this.initiator,\n sendCipher: this.initiator ? cs1 : cs2,\n recvCipher: this.initiator ? cs2 : cs1,\n handshakeHash: this.handshakeHash,\n remoteStatic: this.initiator ? this.rs : this.rs, // for both, populated after handshake\n });\n }\n}\n\n// ---------------------------------------------------------------------------\n// NoiseSession \u2014 post-handshake transport\n// ---------------------------------------------------------------------------\n\n/**\n * Bidirectional encrypted session. Each direction has its own counter.\n *\n * Application-layer ad (associated data) is supported on every send/recv \u2014\n * upper layers (envelope) bind their routing metadata into the AEAD by\n * passing it as `ad` so a tampered envelope can't pair with valid ciphertext.\n */\nexport class NoiseSession {\n constructor({ initiator, sendCipher, recvCipher, handshakeHash, remoteStatic }) {\n this.initiator = initiator;\n this.sendCipher = sendCipher;\n this.recvCipher = recvCipher;\n this.handshakeHash = handshakeHash;\n this.remoteStatic = remoteStatic;\n }\n\n send(plaintext, ad = new Uint8Array(0)) {\n return this.sendCipher.encryptWithAd(asBytes(ad), plaintext);\n }\n\n recv(ciphertext, ad = new Uint8Array(0)) {\n return this.recvCipher.decryptWithAd(asBytes(ad), ciphertext);\n }\n\n /** Channel binding token suitable for pinning to higher-level auth (e.g. WebAuthn challenge). */\n getChannelBinding() {\n return this.handshakeHash.slice();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Convenience factories\n// ---------------------------------------------------------------------------\n\nexport function createInitiator({ staticKeypair, remoteStatic, prologue }) {\n return new HandshakeState({ initiator: true, staticKeypair, remoteStatic, prologue });\n}\n\nexport function createResponder({ staticKeypair, prologue }) {\n return new HandshakeState({ initiator: false, staticKeypair, prologue });\n}\n\n// ---------------------------------------------------------------------------\n// Identity keypair helpers (low-level \u2014 see keys.mjs for the persistence layer)\n// ---------------------------------------------------------------------------\n\nexport function generateIdentityKeypair() {\n return generateKeypair();\n}\n\n// Re-exports for tests / debug tooling\nexport const _internals = {\n concat,\n asBytes,\n timingSafeEqual,\n noiseHkdf,\n noiseHash,\n formatNonce,\n aeadEncrypt,\n aeadDecrypt,\n CipherState,\n SymmetricState,\n};\n", "/**\n * envelope.mjs \u2014 Wire envelope for the viveworker remote-pairing relay.\n *\n * Sits ABOVE the WSS framing and BELOW the Noise transport message.\n * The relay (CF Worker + Durable Object) reads the envelope to route\n * frames; it never decrypts the payload.\n *\n * WSS frame body\n * \u2514\u2500\u2500 envelope (this module) \u2190 visible to relay\n * \u251C\u2500\u2500 type (1 byte) \u2190 routes / control\n * \u251C\u2500\u2500 seq (4 bytes BE u32) \u2190 per-direction monotonic counter\n * \u251C\u2500\u2500 mid (16 bytes UUID) \u2190 dedup key\n * \u2514\u2500\u2500 payload (N bytes) \u2190 Noise transport message (opaque)\n *\n * Three classes of frame:\n *\n * DATA frames carry application payload (Noise ciphertext) plus seq + mid.\n * These are the frames that hit the replay buffer and earn ACKs.\n *\n * CONTROL frames (PING, PONG, ACK, RESUME_*) are short fixed-format frames\n * that the relay handles or echoes; they don't go in the replay buffer.\n *\n * The handshake itself rides as plain DATA frames \u2014 the relay can't tell\n * the difference between handshake and post-handshake transport, which is\n * exactly what we want (no special-cased path for sensitive moments).\n *\n * Byte ordering: big-endian u32 (network order \u2014 matches WSS / IETF\n * convention; one less footgun for anyone reading hex dumps).\n */\n\n// ---------------------------------------------------------------------------\n// Frame types\n// ---------------------------------------------------------------------------\n\nexport const FRAME_DATA = 0x01;\nexport const FRAME_ACK = 0x02;\nexport const FRAME_PING = 0x03;\nexport const FRAME_PONG = 0x04;\nexport const FRAME_RESUME_REQ = 0x05;\nexport const FRAME_RESUME_OK = 0x06;\nexport const FRAME_RESUME_FAIL = 0x07;\n\n// Reasons for RESUME_FAIL \u2014 picked to surface the right user-facing message.\nexport const RESUME_FAIL_BUFFER_EXPIRED = 0x01; // requested seq is older than buffer's earliest\nexport const RESUME_FAIL_UNKNOWN_PAIRING = 0x02; // DO has no record of this pairing\nexport const RESUME_FAIL_HIBERNATED = 0x03; // DO came back from cold; in-memory state lost\n\n// ---------------------------------------------------------------------------\n// Sizes\n// ---------------------------------------------------------------------------\n\nexport const MID_BYTES = 16;\nconst HEADER_DATA = 1 + 4 + MID_BYTES; // type + seq + mid = 21\nconst HEADER_ACK = 1 + 4;\nconst HEADER_PING = 1;\nconst HEADER_PONG = 1;\nconst HEADER_RESUME_REQ = 1 + 4;\nconst HEADER_RESUME_OK = 1 + 4;\nconst HEADER_RESUME_FAIL = 1 + 1;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction asU8(input) {\n if (input == null) return new Uint8Array(0);\n if (input instanceof Uint8Array) return input;\n if (input instanceof ArrayBuffer) return new Uint8Array(input);\n if (ArrayBuffer.isView(input)) return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);\n throw new TypeError(`unsupported envelope input: ${typeof input}`);\n}\n\nfunction readU32BE(view, offset) {\n return view.getUint32(offset, false);\n}\n\nfunction writeU32BE(view, offset, value) {\n if (value < 0 || value > 0xffff_ffff) throw new RangeError(`u32 out of range: ${value}`);\n view.setUint32(offset, value >>> 0, false);\n}\n\n/**\n * Generate a 16-byte random message id. Uses crypto.getRandomValues which is\n * available in Node 19+, browsers, and Cloudflare Workers.\n */\nexport function generateMid() {\n const out = new Uint8Array(MID_BYTES);\n if (typeof globalThis.crypto?.getRandomValues === \"function\") {\n globalThis.crypto.getRandomValues(out);\n } else {\n // Last-resort fallback (shouldn't trigger on supported targets).\n for (let i = 0; i < MID_BYTES; i++) out[i] = Math.floor(Math.random() * 256);\n }\n return out;\n}\n\nexport function midToHex(mid) {\n let out = \"\";\n for (let i = 0; i < mid.length; i++) out += mid[i].toString(16).padStart(2, \"0\");\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Encoders\n// ---------------------------------------------------------------------------\n\nexport function encodeData({ seq, mid, payload }) {\n const pl = asU8(payload);\n if (mid.length !== MID_BYTES) throw new RangeError(\"mid must be 16 bytes\");\n const out = new Uint8Array(HEADER_DATA + pl.length);\n const view = new DataView(out.buffer);\n out[0] = FRAME_DATA;\n writeU32BE(view, 1, seq);\n out.set(mid, 5);\n out.set(pl, HEADER_DATA);\n return out;\n}\n\nexport function encodeAck(seq) {\n const out = new Uint8Array(HEADER_ACK);\n const view = new DataView(out.buffer);\n out[0] = FRAME_ACK;\n writeU32BE(view, 1, seq);\n return out;\n}\n\nexport function encodePing() {\n return new Uint8Array([FRAME_PING]);\n}\n\nexport function encodePong() {\n return new Uint8Array([FRAME_PONG]);\n}\n\nexport function encodeResumeReq(lastSeenSeq) {\n const out = new Uint8Array(HEADER_RESUME_REQ);\n const view = new DataView(out.buffer);\n out[0] = FRAME_RESUME_REQ;\n writeU32BE(view, 1, lastSeenSeq);\n return out;\n}\n\nexport function encodeResumeOk(currentSeq) {\n const out = new Uint8Array(HEADER_RESUME_OK);\n const view = new DataView(out.buffer);\n out[0] = FRAME_RESUME_OK;\n writeU32BE(view, 1, currentSeq);\n return out;\n}\n\nexport function encodeResumeFail(reason) {\n return new Uint8Array([FRAME_RESUME_FAIL, reason & 0xff]);\n}\n\n// ---------------------------------------------------------------------------\n// Decoder\n// ---------------------------------------------------------------------------\n\n/**\n * Decode an envelope frame. Returns one of:\n * { type: FRAME_DATA, seq, mid, payload }\n * { type: FRAME_ACK, seq }\n * { type: FRAME_PING | FRAME_PONG }\n * { type: FRAME_RESUME_REQ, lastSeenSeq }\n * { type: FRAME_RESUME_OK, currentSeq }\n * { type: FRAME_RESUME_FAIL, reason }\n *\n * Throws on malformed input. Callers should treat throws as protocol\n * violations \u2014 log + close the WS with code 4001.\n */\nexport function decode(bytes) {\n const u8 = asU8(bytes);\n if (u8.length < 1) throw new Error(\"envelope: empty frame\");\n const view = new DataView(u8.buffer, u8.byteOffset, u8.byteLength);\n const type = u8[0];\n\n switch (type) {\n case FRAME_DATA: {\n if (u8.length < HEADER_DATA) throw new Error(\"envelope: DATA frame too short\");\n const seq = readU32BE(view, 1);\n const mid = u8.slice(5, 5 + MID_BYTES);\n const payload = u8.slice(HEADER_DATA);\n return { type, seq, mid, payload };\n }\n case FRAME_ACK: {\n if (u8.length !== HEADER_ACK) throw new Error(\"envelope: ACK frame wrong length\");\n return { type, seq: readU32BE(view, 1) };\n }\n case FRAME_PING:\n if (u8.length !== HEADER_PING) throw new Error(\"envelope: PING frame wrong length\");\n return { type };\n case FRAME_PONG:\n if (u8.length !== HEADER_PONG) throw new Error(\"envelope: PONG frame wrong length\");\n return { type };\n case FRAME_RESUME_REQ: {\n if (u8.length !== HEADER_RESUME_REQ) throw new Error(\"envelope: RESUME_REQ frame wrong length\");\n return { type, lastSeenSeq: readU32BE(view, 1) };\n }\n case FRAME_RESUME_OK: {\n if (u8.length !== HEADER_RESUME_OK) throw new Error(\"envelope: RESUME_OK frame wrong length\");\n return { type, currentSeq: readU32BE(view, 1) };\n }\n case FRAME_RESUME_FAIL: {\n if (u8.length !== HEADER_RESUME_FAIL) throw new Error(\"envelope: RESUME_FAIL frame wrong length\");\n return { type, reason: u8[1] };\n }\n default:\n throw new Error(`envelope: unknown frame type 0x${type.toString(16)}`);\n }\n}\n\n/** Stringify a frame type for logs. */\nexport function frameTypeName(type) {\n switch (type) {\n case FRAME_DATA: return \"DATA\";\n case FRAME_ACK: return \"ACK\";\n case FRAME_PING: return \"PING\";\n case FRAME_PONG: return \"PONG\";\n case FRAME_RESUME_REQ: return \"RESUME_REQ\";\n case FRAME_RESUME_OK: return \"RESUME_OK\";\n case FRAME_RESUME_FAIL: return \"RESUME_FAIL\";\n default: return `UNKNOWN(0x${type.toString(16)})`;\n }\n}\n", "/**\n * keys-core.mjs \u2014 Identity key helpers that run in both Node and the browser.\n *\n * Sibling of `keys.mjs` (Node-only persistence). Anything that touches\n * `node:fs`, `node:os`, or `node:path` belongs in keys.mjs; anything pure\n * (encoding, fingerprinting, key derivation) belongs here so the same\n * code path serves the PWA bundle and the bridge.\n *\n * Layered key model (recap \u2014 see keys.mjs comment for the full table):\n *\n * Wallet (secp256k1) \u2014 wallet UI [other module]\n * Identity (X25519 long-term) \u2014 Noise IK static `s` [this file + keys.mjs]\n * Session (X25519 ephemeral) \u2014 derived in Noise [noise.mjs]\n *\n * The browser implementation (`web/remote-pairing/keys.js`) layers\n * IndexedDB / non-extractable CryptoKey storage *over* this module.\n */\n\nimport { x25519 } from \"@noble/curves/ed25519\";\nimport { sha256 } from \"@noble/hashes/sha256\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nexport const IDENTITY_KEY_BYTES = 32;\n\n// ---------------------------------------------------------------------------\n// Encoding helpers\n// ---------------------------------------------------------------------------\n\nconst HEX_RE = /^[0-9a-fA-F]+$/;\n\nexport function bytesToHex(bytes) {\n if (!(bytes instanceof Uint8Array)) {\n throw new TypeError(\"bytesToHex expects Uint8Array\");\n }\n let hex = \"\";\n for (let i = 0; i < bytes.length; i++) {\n hex += bytes[i].toString(16).padStart(2, \"0\");\n }\n return hex;\n}\n\nexport function hexToBytes(hex) {\n if (typeof hex !== \"string\" || hex.length === 0 || hex.length % 2 !== 0 || !HEX_RE.test(hex)) {\n throw new TypeError(`invalid hex: ${typeof hex === \"string\" ? hex.slice(0, 16) : typeof hex}\u2026`);\n }\n const out = new Uint8Array(hex.length / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Generation\n// ---------------------------------------------------------------------------\n\n/**\n * Generate a fresh X25519 identity keypair. Caller owns persistence.\n */\nexport function generateIdentityKeypair() {\n const priv = x25519.utils.randomPrivateKey();\n const pub = x25519.getPublicKey(priv);\n return { priv, pub };\n}\n\n/**\n * Derive the public key from a stored private key. Microseconds \u2014 fine to\n * call on every load instead of persisting `pub` separately.\n */\nexport function publicFromPrivate(priv) {\n return x25519.getPublicKey(priv);\n}\n\n// ---------------------------------------------------------------------------\n// Fingerprint \u2014 short user-visible identifier for the pub key\n// ---------------------------------------------------------------------------\n\n/**\n * 12-character base32-ish fingerprint of the public key, formatted as\n * `XXXX-XXXX-XXXX`. Designed for the pairing screen so the human can\n * eyeball-confirm both sides see the same key (defends against MitM\n * during pairing-code flows).\n *\n * Encoding: SHA-256(pub) \u2192 first 60 bits \u2192 12 chars from a Crockford-like\n * alphabet (no easily-confused glyphs).\n */\nexport function fingerprintIdentity(pub) {\n if (!(pub instanceof Uint8Array)) throw new TypeError(\"pub must be Uint8Array\");\n if (pub.length !== IDENTITY_KEY_BYTES) throw new RangeError(\"pub must be 32 bytes\");\n\n const digest = sha256(pub);\n const alphabet = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\"; // Crockford-ish (no I/L/O/U)\n\n let acc = 0n;\n for (let i = 0; i < 8; i++) acc = (acc << 8n) | BigInt(digest[i]);\n // Take the high 60 bits \u2192 12 base32 chars\n acc >>= 4n;\n\n let out = \"\";\n for (let i = 0; i < 12; i++) {\n const idx = Number(acc & 31n);\n out = alphabet[idx] + out;\n acc >>= 5n;\n }\n // Insert a dash every 4 chars for legibility: XXXX-XXXX-XXXX\n return `${out.slice(0, 4)}-${out.slice(4, 8)}-${out.slice(8, 12)}`;\n}\n", "/**\n * rpc.mjs \u2014 Application-level RPC framing carried inside the Noise channel.\n *\n * The transport (Noise + envelope) gives us an authenticated, encrypted,\n * ordered byte stream between phone and bridge. On top of it we need an\n * HTTP-shaped request/response abstraction so the bridge can keep using\n * its existing `(req, res)` handlers and the phone PWA can keep doing\n * `fetch()` whether it's on LAN or going through the relay.\n *\n * Wire format (UTF-8 JSON, one frame per Noise transport message):\n *\n * // phone \u2192 bridge: HTTP-like request\n * { \"t\":\"req\", \"id\":\"r1\", \"method\":\"GET\", \"path\":\"/api/state\",\n * \"headers\":{\"cookie\":\"viveworker_session=...\"},\n * \"body\":\"\" }\n *\n * // bridge \u2192 phone: full response (single frame; chunked variant TBD)\n * { \"t\":\"res\", \"id\":\"r1\", \"status\":200,\n * \"headers\":{\"content-type\":\"application/json\"},\n * \"body\":\"{...}\" }\n *\n * // phone \u2192 bridge: cancel an in-flight request (e.g. user navigated\n * // away during a long-poll). The bridge MAY abort and skip sending res.\n * { \"t\":\"cancel\", \"id\":\"r1\" }\n *\n * // bridge \u2192 phone: server-pushed event, no client request to correlate\n * // against (e.g., \"new approval item arrived; refresh inbox\").\n * { \"t\":\"evt\", \"topic\":\"inbox-changed\", \"data\":{...} }\n *\n * Why JSON (not CBOR / Protobuf):\n * The Noise channel already gave us the cheap transport. Most viveworker\n * API payloads are JSON to begin with, so the only thing we save by\n * going binary is a few characters per request \u2014 not worth the parser\n * surface or the loss of ad-hoc debuggability. Bodies are always\n * strings; binary bodies (rare, e.g. /uploads) base64 themselves and\n * set `bodyEncoding: \"base64\"`.\n *\n * Validation philosophy:\n * We enforce types and a few bounds (max id length, max headers count,\n * max body size) so a misbehaving peer can't DoS the dispatcher. Past\n * those bounds we trust the peer because the Noise handshake already\n * gave us mutual auth \u2014 there's no value in being defensive against a\n * peer that's already inside the encrypted channel.\n */\n\nconst TEXT_ENCODER = new TextEncoder();\nconst TEXT_DECODER = new TextDecoder(\"utf-8\", { fatal: true });\n\n// ---------------------------------------------------------------------------\n// Limits \u2014 defensive caps. Generous enough to never bite real traffic but\n// tight enough to protect the dispatcher from a runaway peer.\n// ---------------------------------------------------------------------------\n\n/** Max ID length (UUIDs are 36 chars; 64 leaves room for prefixes). */\nexport const MAX_RPC_ID_LEN = 64;\n\n/** Max number of header entries we accept. */\nexport const MAX_HEADERS = 64;\n\n/** Max length of any single header name OR value. */\nexport const MAX_HEADER_LEN = 8 * 1024;\n\n/** Max method string length (`GET`, `OPTIONS`, etc. \u2014 16 covers everything reasonable). */\nexport const MAX_METHOD_LEN = 16;\n\n/** Max URL path length. */\nexport const MAX_PATH_LEN = 4 * 1024;\n\n/** Max body size \u2014 4 MiB. Fits long-poll JSONs, inbox dumps, x402 payloads. */\nexport const MAX_BODY_BYTES = 4 * 1024 * 1024;\n\n/** Max topic name length (server-pushed events). */\nexport const MAX_TOPIC_LEN = 128;\n\n/**\n * Frame type discriminators. Frozen so application code can compare with\n * `===` and not worry about typos surviving as silently-different strings.\n */\nexport const RPC = Object.freeze({\n REQUEST: \"req\",\n RESPONSE: \"res\",\n CANCEL: \"cancel\",\n EVENT: \"evt\",\n});\n\nconst VALID_TYPES = new Set([RPC.REQUEST, RPC.RESPONSE, RPC.CANCEL, RPC.EVENT]);\n\n// ---------------------------------------------------------------------------\n// Encoders\n// ---------------------------------------------------------------------------\n\n/**\n * @typedef {Object} RpcRequest\n * @property {string} id client-chosen correlation id\n * @property {string} method \"GET\" | \"POST\" | \u2026\n * @property {string} path URL path including query, e.g. \"/api/x?foo=1\"\n * @property {Record<string,string>} [headers]\n * @property {string} [body] UTF-8 string; binary callers must base64 + set bodyEncoding\n * @property {\"utf8\" | \"base64\"} [bodyEncoding]\n */\n\n/**\n * @typedef {Object} RpcResponse\n * @property {string} id\n * @property {number} status HTTP status code 100..599\n * @property {Record<string,string>} [headers]\n * @property {string} [body]\n * @property {\"utf8\" | \"base64\"} [bodyEncoding]\n */\n\n/**\n * @typedef {Object} RpcCancel\n * @property {string} id\n */\n\n/**\n * @typedef {Object} RpcEvent\n * @property {string} topic\n * @property {unknown} [data]\n */\n\n/** @param {RpcRequest} req @returns {Uint8Array} */\nexport function encodeRequest(req) {\n if (typeof req?.id !== \"string\") throw new TypeError(\"request.id required (string)\");\n if (typeof req.method !== \"string\") throw new TypeError(\"request.method required (string)\");\n if (typeof req.path !== \"string\") throw new TypeError(\"request.path required (string)\");\n assertIdLen(req.id);\n assertMethod(req.method);\n assertPath(req.path);\n const headers = normalizeHeaders(req.headers);\n const { body, bodyEncoding } = normalizeBody(req.body, req.bodyEncoding);\n\n const obj = { t: RPC.REQUEST, id: req.id, method: req.method, path: req.path };\n if (headers) obj.headers = headers;\n if (body !== undefined) {\n obj.body = body;\n if (bodyEncoding && bodyEncoding !== \"utf8\") obj.bodyEncoding = bodyEncoding;\n }\n return encodeJson(obj);\n}\n\n/** @param {RpcResponse} res @returns {Uint8Array} */\nexport function encodeResponse(res) {\n if (typeof res?.id !== \"string\") throw new TypeError(\"response.id required (string)\");\n if (!Number.isInteger(res.status) || res.status < 100 || res.status > 599) {\n throw new RangeError(\"response.status must be an integer in [100, 599]\");\n }\n assertIdLen(res.id);\n const headers = normalizeHeaders(res.headers);\n const { body, bodyEncoding } = normalizeBody(res.body, res.bodyEncoding);\n\n const obj = { t: RPC.RESPONSE, id: res.id, status: res.status };\n if (headers) obj.headers = headers;\n if (body !== undefined) {\n obj.body = body;\n if (bodyEncoding && bodyEncoding !== \"utf8\") obj.bodyEncoding = bodyEncoding;\n }\n return encodeJson(obj);\n}\n\n/** @param {string} id @returns {Uint8Array} */\nexport function encodeCancel(id) {\n if (typeof id !== \"string\") throw new TypeError(\"cancel.id required (string)\");\n assertIdLen(id);\n return encodeJson({ t: RPC.CANCEL, id });\n}\n\n/** @param {RpcEvent} ev @returns {Uint8Array} */\nexport function encodeEvent(ev) {\n if (typeof ev?.topic !== \"string\") throw new TypeError(\"event.topic required (string)\");\n if (ev.topic.length > MAX_TOPIC_LEN) {\n throw new RangeError(`event.topic exceeds ${MAX_TOPIC_LEN} chars`);\n }\n const obj = { t: RPC.EVENT, topic: ev.topic };\n if (ev.data !== undefined) obj.data = ev.data;\n return encodeJson(obj);\n}\n\n// ---------------------------------------------------------------------------\n// Decoder\n// ---------------------------------------------------------------------------\n\n/**\n * Decode a Noise plaintext frame into a typed RPC object. Throws on\n * malformed JSON, missing required fields, or out-of-bounds values.\n *\n * @param {Uint8Array} bytes\n * @returns {{type: \"req\"} & RpcRequest\n * | {type: \"res\"} & RpcResponse\n * | {type: \"cancel\"} & RpcCancel\n * | {type: \"evt\"} & RpcEvent}\n */\nexport function decode(bytes) {\n if (!(bytes instanceof Uint8Array)) {\n throw new TypeError(\"decode requires Uint8Array\");\n }\n if (bytes.length > MAX_BODY_BYTES + 64 * 1024) {\n // 64 KiB headroom for envelope JSON beyond the body itself.\n throw new RangeError(`rpc frame too large: ${bytes.length} bytes`);\n }\n let str;\n try {\n str = TEXT_DECODER.decode(bytes);\n } catch (err) {\n throw new Error(`rpc frame: invalid UTF-8 (${err.message})`);\n }\n let obj;\n try {\n obj = JSON.parse(str);\n } catch (err) {\n throw new Error(`rpc frame: invalid JSON (${err.message})`);\n }\n if (obj == null || typeof obj !== \"object\" || Array.isArray(obj)) {\n throw new Error(\"rpc frame: not a JSON object\");\n }\n const type = obj.t;\n if (typeof type !== \"string\" || !VALID_TYPES.has(type)) {\n throw new Error(`rpc frame: unknown type ${JSON.stringify(type)}`);\n }\n\n switch (type) {\n case RPC.REQUEST: return decodeRequest(obj);\n case RPC.RESPONSE: return decodeResponse(obj);\n case RPC.CANCEL: return decodeCancel(obj);\n case RPC.EVENT: return decodeEvent(obj);\n }\n // Unreachable \u2014 switch above is exhaustive over VALID_TYPES.\n throw new Error(\"unreachable\");\n}\n\nfunction decodeRequest(obj) {\n const id = requireStr(obj.id, \"id\");\n const method = requireStr(obj.method, \"method\");\n const path = requireStr(obj.path, \"path\");\n assertIdLen(id);\n assertMethod(method);\n assertPath(path);\n const headers = decodeHeaders(obj.headers);\n const { body, bodyEncoding } = decodeBody(obj);\n return { type: RPC.REQUEST, id, method, path, headers, body, bodyEncoding };\n}\n\nfunction decodeResponse(obj) {\n const id = requireStr(obj.id, \"id\");\n assertIdLen(id);\n const status = obj.status;\n if (!Number.isInteger(status) || status < 100 || status > 599) {\n throw new RangeError(\"response.status must be an integer in [100, 599]\");\n }\n const headers = decodeHeaders(obj.headers);\n const { body, bodyEncoding } = decodeBody(obj);\n return { type: RPC.RESPONSE, id, status, headers, body, bodyEncoding };\n}\n\nfunction decodeCancel(obj) {\n const id = requireStr(obj.id, \"id\");\n assertIdLen(id);\n return { type: RPC.CANCEL, id };\n}\n\nfunction decodeEvent(obj) {\n const topic = requireStr(obj.topic, \"topic\");\n if (topic.length > MAX_TOPIC_LEN) {\n throw new RangeError(`event.topic exceeds ${MAX_TOPIC_LEN} chars`);\n }\n return { type: RPC.EVENT, topic, data: obj.data };\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction requireStr(v, name) {\n if (typeof v !== \"string\") throw new TypeError(`${name} required (string)`);\n return v;\n}\n\nfunction assertIdLen(id) {\n if (id.length === 0) throw new RangeError(\"id must be non-empty\");\n if (id.length > MAX_RPC_ID_LEN) throw new RangeError(`id exceeds ${MAX_RPC_ID_LEN} chars`);\n}\n\nfunction assertMethod(m) {\n if (m.length === 0) throw new RangeError(\"method must be non-empty\");\n if (m.length > MAX_METHOD_LEN) throw new RangeError(`method exceeds ${MAX_METHOD_LEN} chars`);\n}\n\nfunction assertPath(p) {\n if (!p.startsWith(\"/\")) throw new RangeError(`path must start with \"/\" (got ${JSON.stringify(p.slice(0, 32))})`);\n if (p.length > MAX_PATH_LEN) throw new RangeError(`path exceeds ${MAX_PATH_LEN} chars`);\n}\n\n/**\n * Normalize headers for encoding. Returns a plain object or undefined.\n * Lowercases keys (matches Node's IncomingMessage convention) and rejects\n * non-string values.\n */\nfunction normalizeHeaders(headers) {\n if (headers == null) return undefined;\n if (typeof headers !== \"object\" || Array.isArray(headers)) {\n throw new TypeError(\"headers must be a plain object\");\n }\n const entries = Object.entries(headers);\n if (entries.length === 0) return undefined;\n if (entries.length > MAX_HEADERS) {\n throw new RangeError(`headers exceeds ${MAX_HEADERS} entries`);\n }\n const out = {};\n for (const [k, v] of entries) {\n if (typeof k !== \"string\" || typeof v !== \"string\") {\n throw new TypeError(`headers must be string\u2192string (got ${k}=${typeof v})`);\n }\n if (k.length > MAX_HEADER_LEN || v.length > MAX_HEADER_LEN) {\n throw new RangeError(`header ${JSON.stringify(k)} exceeds ${MAX_HEADER_LEN} chars`);\n }\n out[k.toLowerCase()] = v;\n }\n return out;\n}\n\nfunction decodeHeaders(raw) {\n if (raw == null) return {};\n if (typeof raw !== \"object\" || Array.isArray(raw)) {\n throw new Error(\"headers must be a JSON object\");\n }\n const entries = Object.entries(raw);\n if (entries.length > MAX_HEADERS) {\n throw new RangeError(`headers exceeds ${MAX_HEADERS} entries`);\n }\n const out = {};\n for (const [k, v] of entries) {\n if (typeof k !== \"string\" || typeof v !== \"string\") {\n throw new Error(`headers must be string\u2192string (got ${k}=${typeof v})`);\n }\n if (k.length > MAX_HEADER_LEN || v.length > MAX_HEADER_LEN) {\n throw new RangeError(`header ${JSON.stringify(k)} exceeds ${MAX_HEADER_LEN} chars`);\n }\n out[k.toLowerCase()] = v;\n }\n return out;\n}\n\nfunction normalizeBody(body, bodyEncoding) {\n if (body === undefined || body === null || body === \"\") return { body: undefined };\n if (typeof body !== \"string\") {\n throw new TypeError(\"body must be a string (binary callers: base64-encode and set bodyEncoding=\\\"base64\\\")\");\n }\n if (bodyEncoding != null && bodyEncoding !== \"utf8\" && bodyEncoding !== \"base64\") {\n throw new RangeError(`bodyEncoding must be \"utf8\" or \"base64\" (got ${JSON.stringify(bodyEncoding)})`);\n }\n // Approximate size check on the encoded JSON. We allow the body string\n // to be up to MAX_BODY_BYTES \u2014 JSON.stringify's escaping can add a few\n // bytes, but the outer bytes-length check in `decode` is the real cap.\n if (body.length > MAX_BODY_BYTES) {\n throw new RangeError(`body exceeds ${MAX_BODY_BYTES} chars`);\n }\n return { body, bodyEncoding: bodyEncoding ?? \"utf8\" };\n}\n\nfunction decodeBody(obj) {\n if (obj.body === undefined) return { body: undefined };\n if (typeof obj.body !== \"string\") throw new Error(\"body must be a string\");\n if (obj.body.length > MAX_BODY_BYTES) {\n throw new RangeError(`body exceeds ${MAX_BODY_BYTES} chars`);\n }\n let bodyEncoding = \"utf8\";\n if (obj.bodyEncoding !== undefined) {\n if (obj.bodyEncoding !== \"utf8\" && obj.bodyEncoding !== \"base64\") {\n throw new Error(`bodyEncoding must be \"utf8\" or \"base64\"`);\n }\n bodyEncoding = obj.bodyEncoding;\n }\n return { body: obj.body, bodyEncoding };\n}\n\nfunction encodeJson(obj) {\n // JSON.stringify rejects undefined values automatically; we explicitly\n // omit them above. Use TextEncoder so the wire is canonical UTF-8 (no\n // BOM, no surprise locale handling).\n return TEXT_ENCODER.encode(JSON.stringify(obj));\n}\n"],
5
+ "mappings": ";AAAA,SAASA,GAAOC,EAAS,CACvB,GAAI,CAAC,OAAO,cAAcA,CAAC,GAAKA,EAAI,EAAG,MAAM,IAAI,MAAM,2BAA2BA,CAAC,EAAE,CACvF,CAMA,SAASC,GAAMC,KAA8BC,EAAiB,CAC5D,GAAI,EAAED,aAAa,YAAa,MAAM,IAAI,MAAM,qBAAqB,EACrE,GAAIC,EAAQ,OAAS,GAAK,CAACA,EAAQ,SAASD,EAAE,MAAM,EAClD,MAAM,IAAI,MAAM,iCAAiCC,CAAO,mBAAmBD,EAAE,MAAM,EAAE,CACzF,CAQA,SAASE,GAAKA,EAAU,CACtB,GAAI,OAAOA,GAAS,YAAc,OAAOA,EAAK,QAAW,WACvD,MAAM,IAAI,MAAM,iDAAiD,E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iB,OAAW,CAClC,GAAIA,EAAI,eAAiB,QAAUA,EAAI,eAAiB,SACtD,MAAM,IAAI,MAAM,yCAAyC,EAE3DF,EAAeE,EAAI,YACrB,CACA,MAAO,CAAE,KAAMA,EAAI,KAAM,aAAAF,CAAa,CACxC,CAEA,SAASG,GAAWD,EAAK,CAIvB,OAAOrB,GAAa,OAAO,KAAK,UAAUqB,CAAG,CAAC,CAChD",
6
+ "names": ["number", "n", "bytes", "b", "lengths", "hash", "number", "exists", "instance", "checkFinished", "output", "out", "min", "crypto", "u8a", "a", "createView", "arr", "rotr", "word", "shift", "isLE", "utf8ToBytes", "str", "toBytes", "data", "u8a", "concatBytes", "arrays", "r", "sum", "a", "pad", "Hash", "toStr", "wrapConstructor", "hashCons", "hashC", "msg", "toBytes", "tmp", "randomBytes", "bytesLength", "crypto", "setBigUint64", "view", "byteOffset", "value", "isLE", "_32n", "_u32_max", "wh", "wl", "h", "l", "SHA2", "Hash", "blockLen", "outputLen", "padOffset", "createView", "data", "exists", "buffer", "toBytes", "len", "pos", "take", "dataView", "out", "output", "i", "oview", "outLen", "state", "res", "to", "length", "finished", "destroyed", "U32_MASK64", "_32n", "fromBig", "n", "le", "split", "lst", "Ah", "Al", "i", "h", "l", "toBig", "shrSH", "_l", "s", "shrSL", "rotrSH", "rotrSL", "rotrBH", "rotrBL", "rotr32H", "_h", "rotr32L", "rotlSH", "rotlSL", "rotlBH", "rotlBL", "add", "Bh", "Bl", "add3L", "Cl", "add3H", "low", "Ch", "add4L", "Dl", "add4H", "Dh", "add5L", "El", "add5H", "Eh", "u64", "fromBig", "split", "toBig", "shrSH", "shrSL", "rotrSH", "rotrSL", "rotrBH", "rotrBL", "rotr32H", "rotr32L", "rotlSH", "rotlSL", "rotlBH", "rotlBL", "add", "add3L", "add3H", "add4L", "add4H", "add5H", "add5L", "u64_default", "SHA512_Kh", "SHA512_Kl", "u64_default", "n", "SHA512_W_H", "SHA512_W_L", "SHA512", "SHA2", "Ah", "Al", "Bh", "Bl", "Ch", "Cl", "Dh", "Dl", "Eh", "El", "Fh", "Fl", "Gh", "Gl", "Hh", "Hl", "view", "offset", "i", "W15h", "W15l", "s0h", "s0l", "W2h", "W2l", "s1h", "s1l", "SUMl", "SUMh", "sigma1h", "sigma1l", "CHIh", "CHIl", "T1ll", "T1h", "T1l", "sigma0h", "sigma0l", "MAJh", "MAJl", "All", "sha512", "wrapConstructor", "SHA512", "_0n", "_1n", "_2n", "u8a", "a", "hexes", "_", "i", "bytesToHex", "bytes", "hex", "hexToNumber", "hex", "hexToBytes", "len", "array", "i", "j", "hexByte", "byte", "bytesToNumberBE", "bytes", "bytesToHex", "bytesToNumberLE", "u8a", "numberToBytesBE", "n", "numberToBytesLE", "ensureBytes", "title", "hex", "expectedLength", "res", "hexToBytes", "e", "u8a", "len", "concatBytes", "arrays", "r", "sum", "a", "pad", "bitMask", "n", "_2n", "_1n", "validatorFns", "val", "object", "validateObject", "validators", "optValidators", "checkField", "fieldName", "type", "isOptional", "checkVal", "_0n", "_1n", "_2n", "_3n", "_4n", "_5n", "_8n", "_9n", "_16n", "mod", "a", "b", "result", "pow", "num", "power", "modulo", "res", "pow2", "x", "invert", "number", "y", "u", "v", "q", "r", "m", "n", "tonelliShanks", "P", "legendreC", "Q", "S", "Z", "p1div4", "Fp", "root", "Q1div2", "g", "t2", "ge", "FpSqrt", "c1", "n2", "nv", "i", "isNegativeLE", "FIELD_FIELDS", "validateField", "field", "initial", "opts", "map", "val", "validateObject", "FpPow", "f", "p", "d", "FpInvertBatch", "nums", "tmp", "lastMultiplied", "acc", "inverted", "nLength", "n", "nBitLength", "_nBitLength", "nByteLength", "Field", "ORDER", "bitLen", "isLE", "redef", "_0n", "BITS", "BYTES", "sqrtP", "FpSqrt", "f", "bitMask", "_1n", "num", "mod", "lhs", "rhs", "power", "FpPow", "invert", "lst", "FpInvertBatch", "a", "b", "c", "numberToBytesLE", "numberToBytesBE", "bytes", "bytesToNumberLE", "bytesToNumberBE", "FpSqrtEven", "Fp", "elm", "root", "_0n", "_1n", "wNAF", "c", "bits", "constTimeNegate", "condition", "item", "neg", "opts", "W", "windows", "windowSize", "elm", "n", "p", "d", "points", "base", "window", "i", "precomputes", "f", "mask", "maxNumber", "shiftBy", "offset", "wbits", "offset1", "offset2", "cond1", "cond2", "P", "precomputesMap", "transform", "comp", "validateBasic", "curve", "validateField", "validateObject", "nLength", "_0n", "_1n", "_2n", "_8n", "VERIFY_DEFAULT", "validateOpts", "curve", "opts", "validateBasic", "validateObject", "twistedEdwards", "curveDef", "CURVE", "Fp", "CURVE_ORDER", "prehash", "cHash", "randomBytes", "nByteLength", "cofactor", "MASK", "modP", "uvRatio", "u", "v", "adjustScalarBytes", "bytes", "domain", "data", "ctx", "phflag", "inBig", "n", "inRange", "max", "in0MaskRange", "assertInRange", "assertGE0", "pointPrecomputes", "isPoint", "other", "Point", "ex", "ey", "ez", "et", "p", "x", "y", "points", "toInv", "i", "windowSize", "a", "d", "X", "Y", "Z", "T", "X2", "Y2", "Z2", "Z4", "aX2", "left", "right", "XY", "ZT", "X1", "Y1", "Z1", "X1Z2", "X2Z1", "Y1Z2", "Y2Z1", "A", "B", "C", "D", "x1y1", "E", "G", "F", "H", "X3", "Y3", "T3", "Z3", "T1", "T2", "wnaf", "scalar", "f", "I", "iz", "z", "is0", "ax", "ay", "zz", "hex", "zip215", "len", "ensureBytes", "normed", "lastByte", "bytesToNumberLE", "y2", "isValid", "isXOdd", "isLastByteOdd", "privKey", "getExtendedPublicKey", "numberToBytesLE", "bytesToHex", "wNAF", "modN", "mod", "modN_LE", "hash", "key", "hashed", "head", "prefix", "point", "pointBytes", "getPublicKey", "hashDomainToScalar", "context", "msgs", "msg", "concatBytes", "sign", "options", "r", "R", "k", "s", "res", "verifyOpts", "verify", "sig", "publicKey", "SB", "_0n", "_1n", "validateOpts", "curve", "validateObject", "montgomery", "curveDef", "CURVE", "P", "modP", "n", "mod", "montgomeryBits", "montgomeryBytes", "fieldLen", "adjustScalarBytes", "bytes", "powPminus2", "x", "pow", "cswap", "swap", "x_2", "x_3", "dummy", "assertFieldElement", "a24", "montgomeryLadder", "pointU", "scalar", "u", "k", "x_1", "z_2", "z_3", "sw", "t", "k_t", "A", "AA", "B", "BB", "E", "C", "D", "DA", "CB", "dacb", "da_cb", "z2", "encodeUCoordinate", "numberToBytesLE", "decodeUCoordinate", "uEnc", "ensureBytes", "bytesToNumberLE", "decodeScalar", "scalarMult", "_scalar", "pu", "GuBytes", "scalarMultBase", "privateKey", "publicKey", "ED25519_P", "ED25519_SQRT_M1", "_0n", "_1n", "_2n", "_5n", "_10n", "_20n", "_40n", "_80n", "ed25519_pow_2_252_3", "x", "P", "b2", "b4", "pow2", "b5", "b10", "b20", "b40", "b80", "b160", "b240", "b250", "adjustScalarBytes", "bytes", "uvRatio", "u", "v", "v3", "mod", "v7", "pow", "vx2", "root1", "root2", "useRoot1", "useRoot2", "noRoot", "isNegativeLE", "Fp", "Field", "ED25519_P", "ed25519Defaults", "sha512", "randomBytes", "adjustScalarBytes", "uvRatio", "ed25519_domain", "data", "ctx", "phflag", "concatBytes", "utf8ToBytes", "ed25519ctx", "twistedEdwards", "ed25519Defaults", "ed25519ph", "sha512", "x25519", "montgomery", "ED25519_P", "x", "P", "pow_p_5_8", "b2", "ed25519_pow_2_252_3", "mod", "pow2", "adjustScalarBytes", "randomBytes", "ELL2_C1", "Fp", "ELL2_C2", "_2n", "ELL2_C3", "ELL2_C4", "ELL2_J", "ELL2_C1_EDWARDS", "FpSqrtEven", "Fp", "SQRT_AD_MINUS_ONE", "INVSQRT_A_MINUS_D", "ONE_MINUS_D_SQ", "D_MINUS_ONE_SQ", "MAX_255B", "isBytes", "a", "abool", "b", "anumber", "n", "abytes", "lengths", "aexists", "instance", "checkFinished", "aoutput", "out", "abytes", "min", "u32", "arr", "clean", "arrays", "i", "createView", "isLE", "utf8ToBytes", "str", "toBytes", "data", "utf8ToBytes", "isBytes", "copyBytes", "checkOpts", "defaults", "opts", "equalBytes", "a", "b", "diff", "i", "wrapCipher", "params", "constructor", "wrappedCipher", "key", "args", "abytes", "isLE", "nonce", "tagl", "cipher", "checkOutput", "fnLength", "output", "called", "data", "getOutput", "expectedLength", "out", "onlyAligned", "isAligned32", "setBigUint64", "view", "byteOffset", "value", "_32n", "_u32_max", "wh", "wl", "h", "l", "u64Lengths", "dataLength", "aadLength", "abool", "num", "createView", "bytes", "copyBytes", "_utf8ToBytes", "str", "c", "sigma16", "sigma32", "sigma16_32", "u32", "sigma32_32", "rotl", "a", "b", "isAligned32", "BLOCK_LEN", "BLOCK_LEN32", "MAX_COUNTER", "U32_EMPTY", "runCipher", "core", "sigma", "key", "nonce", "data", "output", "counter", "rounds", "len", "block", "b32", "isAligned", "d32", "o32", "pos", "take", "pos32", "j", "posj", "createCipher", "opts", "allowShortKeys", "extendNonceFn", "counterLength", "counterRight", "checkOpts", "anumber", "abool", "abytes", "toClean", "l", "k", "copyBytes", "k32", "nonceNcLen", "nc", "n32", "clean", "u8to16", "a", "i", "Poly1305", "key", "toBytes", "abytes", "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "data", "offset", "isLast", "hibit", "h", "r", "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "h0", "h1", "h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9", "c", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "pad", "g", "mask", "f", "clean", "aexists", "buffer", "blockLen", "len", "pos", "take", "out", "aoutput", "opos", "outputLen", "res", "wrapConstructorWithKey", "hashCons", "hashC", "msg", "tmp", "poly1305", "chachaCore", "s", "k", "out", "cnt", "rounds", "y00", "y01", "y02", "y03", "y04", "y05", "y06", "y07", "y08", "y09", "y10", "y11", "y12", "y13", "y14", "y15", "x00", "x01", "x02", "x03", "x04", "x05", "x06", "x07", "x08", "x09", "x10", "x11", "x12", "x13", "x14", "x15", "r", "rotl", "oi", "hchacha", "i", "o32", "chacha20", "createCipher", "chachaCore", "xchacha20", "hchacha", "ZEROS16", "updatePadded", "h", "msg", "left", "ZEROS32", "computeTag", "fn", "key", "nonce", "data", "AAD", "authKey", "poly1305", "num", "u64Lengths", "res", "clean", "_poly1305_aead", "xorStream", "plaintext", "output", "plength", "getOutput", "oPlain", "tag", "ciphertext", "passedTag", "equalBytes", "chacha20poly1305", "wrapCipher", "chacha20", "xchacha20poly1305", "xchacha20", "Chi", "a", "b", "c", "Maj", "SHA256_K", "IV", "SHA256_W", "SHA256", "SHA2", "A", "B", "C", "D", "E", "F", "G", "H", "view", "offset", "i", "W15", "W2", "s0", "rotr", "s1", "sigma1", "T1", "T2", "sha256", "wrapConstructor", "SHA256", "HMAC", "Hash", "hash", "_key", "key", "toBytes", "blockLen", "pad", "buf", "exists", "out", "bytes", "to", "oHash", "iHash", "finished", "destroyed", "outputLen", "hmac", "message", "extract", "hash", "ikm", "salt", "hmac", "toBytes", "HKDF_COUNTER", "EMPTY_BUFFER", "expand", "prk", "info", "length", "number", "blocks", "okm", "HMAC", "HMACTmp", "T", "counter", "hkdf", "PROTOCOL_NAME", "HASHLEN", "KEYLEN", "DHLEN", "TAGLEN", "NONCE_MAX", "PROTOCOL_NAME_BYTES", "concat", "arrays", "total", "a", "out", "offset", "asBytes", "input", "noiseHash", "data", "sha256", "noiseHkdf", "ck", "ikm", "nOutputs", "length", "HASHLEN", "out", "hkdf", "slices", "generateKeypair", "priv", "x25519", "pub", "dh", "formatNonce", "counter", "v", "i", "aeadEncrypt", "key", "ad", "plaintext", "chacha20poly1305", "asBytes", "aeadDecrypt", "ciphertext", "CipherState", "NONCE_MAX", "ct", "pt", "SymmetricState", "protocolName", "nameBytes", "tempK", "KEYLEN", "concat", "k1", "k2", "HandshakeState", "initiator", "staticKeypair", "remoteStatic", "prologue", "PROTOCOL_NAME", "payload", "buf", "bytes", "offset", "re", "DHLEN", "sCiphertext", "TAGLEN", "cs1", "cs2", "NoiseSession", "sendCipher", "recvCipher", "handshakeHash", "createInitiator", "createResponder", "FRAME_DATA", "FRAME_ACK", "FRAME_PING", "FRAME_PONG", "FRAME_RESUME_REQ", "FRAME_RESUME_OK", "FRAME_RESUME_FAIL", "RESUME_FAIL_BUFFER_EXPIRED", "RESUME_FAIL_UNKNOWN_PAIRING", "RESUME_FAIL_HIBERNATED", "MID_BYTES", "asU8", "input", "readU32BE", "view", "offset", "writeU32BE", "value", "generateMid", "out", "i", "midToHex", "mid", "encodeData", "seq", "payload", "pl", "encodeAck", "encodePing", "encodePong", "encodeResumeReq", "lastSeenSeq", "encodeResumeOk", "currentSeq", "encodeResumeFail", "reason", "decode", "bytes", "u8", "type", "frameTypeName", "IDENTITY_KEY_BYTES", "HEX_RE", "bytesToHex", "bytes", "hex", "i", "hexToBytes", "out", "generateIdentityKeypair", "priv", "x25519", "pub", "publicFromPrivate", "fingerprintIdentity", "digest", "sha256", "alphabet", "acc", "idx", "TEXT_ENCODER", "TEXT_DECODER", "MAX_RPC_ID_LEN", "MAX_HEADERS", "MAX_HEADER_LEN", "MAX_METHOD_LEN", "MAX_PATH_LEN", "MAX_BODY_BYTES", "MAX_TOPIC_LEN", "RPC", "VALID_TYPES", "encodeRequest", "req", "assertIdLen", "assertMethod", "assertPath", "headers", "normalizeHeaders", "body", "bodyEncoding", "normalizeBody", "obj", "encodeJson", "encodeResponse", "res", "encodeCancel", "id", "encodeEvent", "ev", "decode", "bytes", "str", "err", "type", "decodeRequest", "decodeResponse", "decodeCancel", "decodeEvent", "requireStr", "method", "path", "decodeHeaders", "decodeBody", "status", "topic", "v", "name", "m", "p", "entries", "out", "k", "raw"]
7
+ }