{"version":3,"sources":["jsdelivr-header.js","/npm/nostr-tools@2.17.0/index.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/curves/node_modules/@noble/hashes/src/_assert.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/curves/node_modules/@noble/hashes/src/crypto.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/curves/node_modules/@noble/hashes/src/utils.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/curves/node_modules/@noble/hashes/src/_sha2.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/curves/node_modules/@noble/hashes/src/sha256.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/curves/src/abstract/utils.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/curves/src/abstract/modular.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/curves/src/abstract/curve.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/curves/src/abstract/weierstrass.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/curves/node_modules/@noble/hashes/src/hmac.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/curves/src/_shortw_utils.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/curves/src/secp256k1.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/hashes/src/crypto.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/hashes/src/utils.ts","/npm/nostr-tools@2.17.0/core.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/hashes/src/_assert.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/hashes/src/_sha2.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/hashes/src/sha256.ts","/npm/nostr-tools@2.17.0/utils.ts","/npm/nostr-tools@2.17.0/pure.ts","/npm/nostr-tools@2.17.0/kinds.ts","/npm/nostr-tools@2.17.0/filter.ts","/npm/nostr-tools@2.17.0/fakejson.ts","/npm/nostr-tools@2.17.0/nip42.ts","/npm/nostr-tools@2.17.0/helpers.ts","/npm/nostr-tools@2.17.0/relay.ts","/npm/nostr-tools@2.17.0/abstract-relay.ts","/npm/nostr-tools@2.17.0/pool.ts","/npm/nostr-tools@2.17.0/abstract-pool.ts","/npm/nostr-tools@2.17.0/nip19.ts","/npm/nostr-tools@2.17.0/node_modules/@scure/base/lib/esm/index.js","/npm/nostr-tools@2.17.0/references.ts","/npm/nostr-tools@2.17.0/nip04.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/ciphers/src/_assert.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/ciphers/src/utils.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/ciphers/src/_polyval.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/ciphers/src/aes.ts","/npm/nostr-tools@2.17.0/nip05.ts","/npm/nostr-tools@2.17.0/nip10.ts","/npm/nostr-tools@2.17.0/nip11.ts","/npm/nostr-tools@2.17.0/nip13.ts","/npm/nostr-tools@2.17.0/nip17.ts","/npm/nostr-tools@2.17.0/nip59.ts","/npm/nostr-tools@2.17.0/nip44.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/ciphers/src/_poly1305.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/ciphers/src/_arx.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/ciphers/src/chacha.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/hashes/src/hmac.ts","/npm/nostr-tools@2.17.0/node_modules/@noble/hashes/src/hkdf.ts","/npm/nostr-tools@2.17.0/nip18.ts","/npm/nostr-tools@2.17.0/nip21.ts","/npm/nostr-tools@2.17.0/nip25.ts","/npm/nostr-tools@2.17.0/nip27.ts","/npm/nostr-tools@2.17.0/nip28.ts","/npm/nostr-tools@2.17.0/nip30.ts","/npm/nostr-tools@2.17.0/nip39.ts","/npm/nostr-tools@2.17.0/nip47.ts","/npm/nostr-tools@2.17.0/nip54.ts","/npm/nostr-tools@2.17.0/nip57.ts","/npm/nostr-tools@2.17.0/nip98.ts"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA,yNCNA,EAAA,GCAA,SAAS,EAAO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,GAC7E,IAAK,GAAY,GACf,MAAM,IAAI,MAAM,0CAGlB,IAAK,GAAkB,GACrB,MAAM,IAAI,MAAM,qCAGlB,IAAK,GAAuB,GAC1B,MAAM,IAAI,MAAM,qDAGlB,IAAK,GAAoB,EAAO,GAC9B,MAAM,IAAI,MAAM,wCAGlB,IAAK,GAAuB,EAAO,GACjC,MAAM,IAAI,MAAM,2CAGlB,GAAI,QAAQ,IAAyB,iBAAT,GAAqB,OAAO,KAAK,GAAM,OAAS,IACrE,GAAwB,EAAO,GAClC,MAAM,IAAI,MAAM,qEAIpB,OAAO,CACT,C","file":"/npm/nostr-tools@2.17.0/lib/nostr.bundle.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/nostr-tools@2.17.0/lib/nostr.bundle.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","export * from './pure.ts'\nexport { Relay } from './relay.ts'\nexport * from './filter.ts'\nexport { SimplePool } from './pool.ts'\nexport * from './references.ts'\n\nexport * as nip04 from './nip04.ts'\nexport * as nip05 from './nip05.ts'\nexport * as nip10 from './nip10.ts'\nexport * as nip11 from './nip11.ts'\nexport * as nip13 from './nip13.ts'\nexport * as nip17 from './nip17.ts'\nexport * as nip18 from './nip18.ts'\nexport * as nip19 from './nip19.ts'\nexport * as nip21 from './nip21.ts'\nexport * as nip25 from './nip25.ts'\nexport * as nip27 from './nip27.ts'\nexport * as nip28 from './nip28.ts'\nexport * as nip30 from './nip30.ts'\nexport * as nip39 from './nip39.ts'\nexport * as nip42 from './nip42.ts'\nexport * as nip44 from './nip44.ts'\nexport * as nip47 from './nip47.ts'\nexport * as nip54 from './nip54.ts'\nexport * as nip57 from './nip57.ts'\nexport * as nip59 from './nip59.ts'\nexport * as nip98 from './nip98.ts'\n\nexport * as kinds from './kinds.ts'\nexport * as fj from './fakejson.ts'\nexport * as utils from './utils.ts'\n","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","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","/*! 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) ≡ 1    if a is a square (mod p)\n  // (a | p) ≡ -1   if a is not a square (mod p)\n  // (a | p) ≡ 0    if a ≡ 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) ≡ -1 and set c ≡ 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 ≡ -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 ≡ 3 (mod 4)\n  // √n = 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 ≡ 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 ≡ 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 / 𝑊) + 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^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n     * - 𝑊 is the window size\n     * - 𝑛 is the bitlength of the curve order.\n     * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n     * @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// Short Weierstrass curve. The formula is: y² = x³ + ax + b\nimport * as mod from './modular.js';\nimport * as ut from './utils.js';\nimport { CHash, Hex, PrivKey, ensureBytes } from './utils.js';\nimport { Group, GroupConstructor, wNAF, BasicCurve, validateBasic, AffinePoint } from './curve.js';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\ntype EndomorphismOpts = {\n  beta: bigint;\n  splitScalar: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\nexport type BasicWCurve<T> = BasicCurve<T> & {\n  // Params: a, b\n  a: T;\n  b: T;\n\n  // Optional params\n  allowedPrivateKeyLengths?: readonly number[]; // for P521\n  wrapPrivateKey?: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n  endo?: EndomorphismOpts; // Endomorphism options for Koblitz curves\n  // When a cofactor != 1, there can be an effective methods to:\n  // 1. Determine whether a point is torsion-free\n  isTorsionFree?: (c: ProjConstructor<T>, point: ProjPointType<T>) => boolean;\n  // 2. Clear torsion component\n  clearCofactor?: (c: ProjConstructor<T>, point: ProjPointType<T>) => ProjPointType<T>;\n};\n\ntype Entropy = Hex | true;\nexport type SignOpts = { lowS?: boolean; extraEntropy?: Entropy; prehash?: boolean };\nexport type VerOpts = { lowS?: boolean; prehash?: boolean };\n\n/**\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n *   `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n *   `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n *   it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance of nominative types in TypeScript and interfaces only check for shape, so it's hard to create unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n *     1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n *     which is hard to debug.\n *     2. Params can be generic and we can't enforce them to be constant value:\n *     if somebody creates curve from non-constant params,\n *     it would be allowed to interact with other curves with non-constant params\n *\n * TODO: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n */\n\n// Instance for 3d XYZ points\nexport interface ProjPointType<T> extends Group<ProjPointType<T>> {\n  readonly px: T;\n  readonly py: T;\n  readonly pz: T;\n  get x(): T;\n  get y(): T;\n  multiply(scalar: bigint): ProjPointType<T>;\n  toAffine(iz?: T): AffinePoint<T>;\n  isTorsionFree(): boolean;\n  clearCofactor(): ProjPointType<T>;\n  assertValidity(): void;\n  hasEvenY(): boolean;\n  toRawBytes(isCompressed?: boolean): Uint8Array;\n  toHex(isCompressed?: boolean): string;\n\n  multiplyUnsafe(scalar: bigint): ProjPointType<T>;\n  multiplyAndAddUnsafe(Q: ProjPointType<T>, a: bigint, b: bigint): ProjPointType<T> | undefined;\n  _setWindowSize(windowSize: number): void;\n}\n// Static methods for 3d XYZ points\nexport interface ProjConstructor<T> extends GroupConstructor<ProjPointType<T>> {\n  new (x: T, y: T, z: T): ProjPointType<T>;\n  fromAffine(p: AffinePoint<T>): ProjPointType<T>;\n  fromHex(hex: Hex): ProjPointType<T>;\n  fromPrivateKey(privateKey: PrivKey): ProjPointType<T>;\n  normalizeZ(points: ProjPointType<T>[]): ProjPointType<T>[];\n}\n\nexport type CurvePointsType<T> = BasicWCurve<T> & {\n  // Bytes\n  fromBytes?: (bytes: Uint8Array) => AffinePoint<T>;\n  toBytes?: (c: ProjConstructor<T>, point: ProjPointType<T>, isCompressed: boolean) => Uint8Array;\n};\n\nfunction validatePointOpts<T>(curve: CurvePointsType<T>) {\n  const opts = validateBasic(curve);\n  ut.validateObject(\n    opts,\n    {\n      a: 'field',\n      b: 'field',\n    },\n    {\n      allowedPrivateKeyLengths: 'array',\n      wrapPrivateKey: 'boolean',\n      isTorsionFree: 'function',\n      clearCofactor: 'function',\n      allowInfinityPoint: 'boolean',\n      fromBytes: 'function',\n      toBytes: 'function',\n    }\n  );\n  const { endo, Fp, a } = opts;\n  if (endo) {\n    if (!Fp.eql(a, Fp.ZERO)) {\n      throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');\n    }\n    if (\n      typeof endo !== 'object' ||\n      typeof endo.beta !== 'bigint' ||\n      typeof endo.splitScalar !== 'function'\n    ) {\n      throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');\n    }\n  }\n  return Object.freeze({ ...opts } as const);\n}\n\nexport type CurvePointsRes<T> = {\n  ProjectivePoint: ProjConstructor<T>;\n  normPrivateKeyToScalar: (key: PrivKey) => bigint;\n  weierstrassEquation: (x: T) => T;\n  isWithinCurveOrder: (num: bigint) => boolean;\n};\n\n// ASN.1 DER encoding utilities\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\nexport const DER = {\n  // asn.1 DER encoding utils\n  Err: class DERErr extends Error {\n    constructor(m = '') {\n      super(m);\n    }\n  },\n  _parseInt(data: Uint8Array): { d: bigint; l: Uint8Array } {\n    const { Err: E } = DER;\n    if (data.length < 2 || data[0] !== 0x02) throw new E('Invalid signature integer tag');\n    const len = data[1];\n    const res = data.subarray(2, len + 2);\n    if (!len || res.length !== len) throw new E('Invalid signature integer: wrong length');\n    // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n    // since we always use positive integers here. It must always be empty:\n    // - add zero byte if exists\n    // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n    if (res[0] & 0b10000000) throw new E('Invalid signature integer: negative');\n    if (res[0] === 0x00 && !(res[1] & 0b10000000))\n      throw new E('Invalid signature integer: unnecessary leading zero');\n    return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left\n  },\n  toSig(hex: string | Uint8Array): { r: bigint; s: bigint } {\n    // parse DER signature\n    const { Err: E } = DER;\n    const data = typeof hex === 'string' ? h2b(hex) : hex;\n    if (!(data instanceof Uint8Array)) throw new Error('ui8a expected');\n    let l = data.length;\n    if (l < 2 || data[0] != 0x30) throw new E('Invalid signature tag');\n    if (data[1] !== l - 2) throw new E('Invalid signature: incorrect length');\n    const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));\n    const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);\n    if (rBytesLeft.length) throw new E('Invalid signature: left bytes after parsing');\n    return { r, s };\n  },\n  hexFromSig(sig: { r: bigint; s: bigint }): string {\n    // Add leading zero if first byte has negative bit enabled. More details in '_parseInt'\n    const slice = (s: string): string => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s);\n    const h = (num: number | bigint) => {\n      const hex = num.toString(16);\n      return hex.length & 1 ? `0${hex}` : hex;\n    };\n    const s = slice(h(sig.s));\n    const r = slice(h(sig.r));\n    const shl = s.length / 2;\n    const rhl = r.length / 2;\n    const sl = h(shl);\n    const rl = h(rhl);\n    return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;\n  },\n};\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), _3n = BigInt(3), _4n = BigInt(4);\n\nexport function weierstrassPoints<T>(opts: CurvePointsType<T>) {\n  const CURVE = validatePointOpts(opts);\n  const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n\n  const toBytes =\n    CURVE.toBytes ||\n    ((_c: ProjConstructor<T>, point: ProjPointType<T>, _isCompressed: boolean) => {\n      const a = point.toAffine();\n      return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n    });\n  const fromBytes =\n    CURVE.fromBytes ||\n    ((bytes: Uint8Array) => {\n      // const head = bytes[0];\n      const tail = bytes.subarray(1);\n      // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n      const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n      const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n      return { x, y };\n    });\n\n  /**\n   * y² = x³ + ax + b: Short weierstrass curve formula\n   * @returns y²\n   */\n  function weierstrassEquation(x: T): T {\n    const { a, b } = CURVE;\n    const x2 = Fp.sqr(x); // x * x\n    const x3 = Fp.mul(x2, x); // x2 * x\n    return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n  }\n  // Validate whether the passed curve params are valid.\n  // We check if curve equation works for generator point.\n  // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n  // ProjectivePoint class has not been initialized yet.\n  if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n    throw new Error('bad generator point: equation left != right');\n\n  // Valid group elements reside in range 1..n-1\n  function isWithinCurveOrder(num: bigint): boolean {\n    return typeof num === 'bigint' && _0n < num && num < CURVE.n;\n  }\n  function assertGE(num: bigint) {\n    if (!isWithinCurveOrder(num)) throw new Error('Expected valid bigint: 0 < bigint < curve.n');\n  }\n  // Validates if priv key is valid and converts it to bigint.\n  // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n  function normPrivateKeyToScalar(key: PrivKey): bigint {\n    const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;\n    if (lengths && typeof key !== 'bigint') {\n      if (key instanceof Uint8Array) key = ut.bytesToHex(key);\n      // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n      if (typeof key !== 'string' || !lengths.includes(key.length)) throw new Error('Invalid key');\n      key = key.padStart(nByteLength * 2, '0');\n    }\n    let num: bigint;\n    try {\n      num =\n        typeof key === 'bigint'\n          ? key\n          : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n    } catch (error) {\n      throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);\n    }\n    if (wrapPrivateKey) num = mod.mod(num, n); // disabled by default, enabled for BLS\n    assertGE(num); // num in range [1..N-1]\n    return num;\n  }\n\n  const pointPrecomputes = new Map<Point, Point[]>();\n  function assertPrjPoint(other: unknown) {\n    if (!(other instanceof Point)) throw new Error('ProjectivePoint expected');\n  }\n  /**\n   * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n   * Default Point works in 2d / affine coordinates: (x, y)\n   * We're doing calculations in projective, because its operations don't require costly inversion.\n   */\n  class Point implements ProjPointType<T> {\n    static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n    static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n\n    constructor(readonly px: T, readonly py: T, readonly pz: T) {\n      if (px == null || !Fp.isValid(px)) throw new Error('x required');\n      if (py == null || !Fp.isValid(py)) throw new Error('y required');\n      if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n    }\n\n    // Does not validate if the point is on-curve.\n    // Use fromHex instead, or call assertValidity() later.\n    static fromAffine(p: AffinePoint<T>): Point {\n      const { x, y } = p || {};\n      if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point');\n      if (p instanceof Point) throw new Error('projective point not allowed');\n      const is0 = (i: T) => Fp.eql(i, Fp.ZERO);\n      // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n      if (is0(x) && is0(y)) return Point.ZERO;\n      return new Point(x, y, Fp.ONE);\n    }\n\n    get x(): T {\n      return this.toAffine().x;\n    }\n    get y(): T {\n      return this.toAffine().y;\n    }\n\n    /**\n     * Takes a bunch of Projective Points but executes only one\n     * inversion on all of them. Inversion is very slow operation,\n     * so this improves performance massively.\n     * Optimization: converts a list of projective points to a list of identical points with Z=1.\n     */\n    static normalizeZ(points: Point[]): Point[] {\n      const toInv = Fp.invertBatch(points.map((p) => p.pz));\n      return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n    }\n\n    /**\n     * Converts hash string or Uint8Array to Point.\n     * @param hex short/long ECDSA hex\n     */\n    static fromHex(hex: Hex): Point {\n      const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n      P.assertValidity();\n      return P;\n    }\n\n    // Multiplies generator point by privateKey.\n    static fromPrivateKey(privateKey: PrivKey) {\n      return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\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\n    // A point on curve is valid if it conforms to equation.\n    assertValidity(): void {\n      if (this.is0()) {\n        // (0, 1, 0) aka ZERO is invalid in most contexts.\n        // In BLS, ZERO can be serialized, so we allow it.\n        // (0, 0, 0) is wrong representation of ZERO and is always invalid.\n        if (CURVE.allowInfinityPoint && !Fp.is0(this.py)) return;\n        throw new Error('bad point: ZERO');\n      }\n      // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n      const { x, y } = this.toAffine();\n      // Check if x, y are valid field elements\n      if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not FE');\n      const left = Fp.sqr(y); // y²\n      const right = weierstrassEquation(x); // x³ + ax + b\n      if (!Fp.eql(left, right)) throw new Error('bad point: equation left != right');\n      if (!this.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n    }\n    hasEvenY(): boolean {\n      const { y } = this.toAffine();\n      if (Fp.isOdd) return !Fp.isOdd(y);\n      throw new Error(\"Field doesn't support isOdd\");\n    }\n\n    /**\n     * Compare one point to another.\n     */\n    equals(other: Point): boolean {\n      assertPrjPoint(other);\n      const { px: X1, py: Y1, pz: Z1 } = this;\n      const { px: X2, py: Y2, pz: Z2 } = other;\n      const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n      const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n      return U1 && U2;\n    }\n\n    /**\n     * Flips point to one corresponding to (x, -y) in Affine coordinates.\n     */\n    negate(): Point {\n      return new Point(this.px, Fp.neg(this.py), this.pz);\n    }\n\n    // Renes-Costello-Batina exception-free doubling formula.\n    // There is 30% faster Jacobian formula, but it is not complete.\n    // https://eprint.iacr.org/2015/1060, algorithm 3\n    // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n    double() {\n      const { a, b } = CURVE;\n      const b3 = Fp.mul(b, _3n);\n      const { px: X1, py: Y1, pz: Z1 } = this;\n      let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n      let t0 = Fp.mul(X1, X1); // step 1\n      let t1 = Fp.mul(Y1, Y1);\n      let t2 = Fp.mul(Z1, Z1);\n      let t3 = Fp.mul(X1, Y1);\n      t3 = Fp.add(t3, t3); // step 5\n      Z3 = Fp.mul(X1, Z1);\n      Z3 = Fp.add(Z3, Z3);\n      X3 = Fp.mul(a, Z3);\n      Y3 = Fp.mul(b3, t2);\n      Y3 = Fp.add(X3, Y3); // step 10\n      X3 = Fp.sub(t1, Y3);\n      Y3 = Fp.add(t1, Y3);\n      Y3 = Fp.mul(X3, Y3);\n      X3 = Fp.mul(t3, X3);\n      Z3 = Fp.mul(b3, Z3); // step 15\n      t2 = Fp.mul(a, t2);\n      t3 = Fp.sub(t0, t2);\n      t3 = Fp.mul(a, t3);\n      t3 = Fp.add(t3, Z3);\n      Z3 = Fp.add(t0, t0); // step 20\n      t0 = Fp.add(Z3, t0);\n      t0 = Fp.add(t0, t2);\n      t0 = Fp.mul(t0, t3);\n      Y3 = Fp.add(Y3, t0);\n      t2 = Fp.mul(Y1, Z1); // step 25\n      t2 = Fp.add(t2, t2);\n      t0 = Fp.mul(t2, t3);\n      X3 = Fp.sub(X3, t0);\n      Z3 = Fp.mul(t2, t1);\n      Z3 = Fp.add(Z3, Z3); // step 30\n      Z3 = Fp.add(Z3, Z3);\n      return new Point(X3, Y3, Z3);\n    }\n\n    // Renes-Costello-Batina exception-free addition formula.\n    // There is 30% faster Jacobian formula, but it is not complete.\n    // https://eprint.iacr.org/2015/1060, algorithm 1\n    // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n    add(other: Point): Point {\n      assertPrjPoint(other);\n      const { px: X1, py: Y1, pz: Z1 } = this;\n      const { px: X2, py: Y2, pz: Z2 } = other;\n      let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n      const a = CURVE.a;\n      const b3 = Fp.mul(CURVE.b, _3n);\n      let t0 = Fp.mul(X1, X2); // step 1\n      let t1 = Fp.mul(Y1, Y2);\n      let t2 = Fp.mul(Z1, Z2);\n      let t3 = Fp.add(X1, Y1);\n      let t4 = Fp.add(X2, Y2); // step 5\n      t3 = Fp.mul(t3, t4);\n      t4 = Fp.add(t0, t1);\n      t3 = Fp.sub(t3, t4);\n      t4 = Fp.add(X1, Z1);\n      let t5 = Fp.add(X2, Z2); // step 10\n      t4 = Fp.mul(t4, t5);\n      t5 = Fp.add(t0, t2);\n      t4 = Fp.sub(t4, t5);\n      t5 = Fp.add(Y1, Z1);\n      X3 = Fp.add(Y2, Z2); // step 15\n      t5 = Fp.mul(t5, X3);\n      X3 = Fp.add(t1, t2);\n      t5 = Fp.sub(t5, X3);\n      Z3 = Fp.mul(a, t4);\n      X3 = Fp.mul(b3, t2); // step 20\n      Z3 = Fp.add(X3, Z3);\n      X3 = Fp.sub(t1, Z3);\n      Z3 = Fp.add(t1, Z3);\n      Y3 = Fp.mul(X3, Z3);\n      t1 = Fp.add(t0, t0); // step 25\n      t1 = Fp.add(t1, t0);\n      t2 = Fp.mul(a, t2);\n      t4 = Fp.mul(b3, t4);\n      t1 = Fp.add(t1, t2);\n      t2 = Fp.sub(t0, t2); // step 30\n      t2 = Fp.mul(a, t2);\n      t4 = Fp.add(t4, t2);\n      t0 = Fp.mul(t1, t4);\n      Y3 = Fp.add(Y3, t0);\n      t0 = Fp.mul(t5, t4); // step 35\n      X3 = Fp.mul(t3, X3);\n      X3 = Fp.sub(X3, t0);\n      t0 = Fp.mul(t3, t1);\n      Z3 = Fp.mul(t5, Z3);\n      Z3 = Fp.add(Z3, t0); // step 40\n      return new Point(X3, Y3, Z3);\n    }\n\n    subtract(other: Point) {\n      return this.add(other.negate());\n    }\n\n    private is0() {\n      return this.equals(Point.ZERO);\n    }\n    private wNAF(n: bigint): { p: Point; f: Point } {\n      return wnaf.wNAFCached(this, pointPrecomputes, n, (comp: Point[]) => {\n        const toInv = Fp.invertBatch(comp.map((p) => p.pz));\n        return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n      });\n    }\n\n    /**\n     * Non-constant-time multiplication. Uses double-and-add algorithm.\n     * It's faster, but should only be used when you don't care about\n     * an exposed private key e.g. sig verification, which works over *public* keys.\n     */\n    multiplyUnsafe(n: bigint): Point {\n      const I = Point.ZERO;\n      if (n === _0n) return I;\n      assertGE(n); // Will throw on 0\n      if (n === _1n) return this;\n      const { endo } = CURVE;\n      if (!endo) return wnaf.unsafeLadder(this, n);\n\n      // Apply endomorphism\n      let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n      let k1p = I;\n      let k2p = I;\n      let d: Point = this;\n      while (k1 > _0n || k2 > _0n) {\n        if (k1 & _1n) k1p = k1p.add(d);\n        if (k2 & _1n) k2p = k2p.add(d);\n        d = d.double();\n        k1 >>= _1n;\n        k2 >>= _1n;\n      }\n      if (k1neg) k1p = k1p.negate();\n      if (k2neg) k2p = k2p.negate();\n      k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n      return k1p.add(k2p);\n    }\n\n    /**\n     * Constant time multiplication.\n     * Uses wNAF method. Windowed method may be 10% faster,\n     * but takes 2x longer to generate and consumes 2x memory.\n     * Uses precomputes when available.\n     * Uses endomorphism for Koblitz curves.\n     * @param scalar by which the point would be multiplied\n     * @returns New point\n     */\n    multiply(scalar: bigint): Point {\n      assertGE(scalar);\n      let n = scalar;\n      let point: Point, fake: Point; // Fake point is used to const-time mult\n      const { endo } = CURVE;\n      if (endo) {\n        const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n        let { p: k1p, f: f1p } = this.wNAF(k1);\n        let { p: k2p, f: f2p } = this.wNAF(k2);\n        k1p = wnaf.constTimeNegate(k1neg, k1p);\n        k2p = wnaf.constTimeNegate(k2neg, k2p);\n        k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n        point = k1p.add(k2p);\n        fake = f1p.add(f2p);\n      } else {\n        const { p, f } = this.wNAF(n);\n        point = p;\n        fake = f;\n      }\n      // Normalize `z` for both points, but return only real one\n      return Point.normalizeZ([point, fake])[0];\n    }\n\n    /**\n     * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n     * Not using Strauss-Shamir trick: precomputation tables are faster.\n     * The trick could be useful if both P and Q are not G (not in our case).\n     * @returns non-zero affine point\n     */\n    multiplyAndAddUnsafe(Q: Point, a: bigint, b: bigint): Point | undefined {\n      const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n      const mul = (\n        P: Point,\n        a: bigint // Select faster multiply() method\n      ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n      const sum = mul(this, a).add(mul(Q, b));\n      return sum.is0() ? undefined : sum;\n    }\n\n    // Converts Projective point to affine (x, y) coordinates.\n    // Can accept precomputed Z^-1 - for example, from invertBatch.\n    // (x, y, z) ∋ (x=x/z, y=y/z)\n    toAffine(iz?: T): AffinePoint<T> {\n      const { px: x, py: y, pz: z } = this;\n      const is0 = this.is0();\n      // If invZ was 0, we return zero point. However we still want to execute\n      // all operations, so we replace invZ with a random number, 1.\n      if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(z);\n      const ax = Fp.mul(x, iz);\n      const ay = Fp.mul(y, iz);\n      const zz = Fp.mul(z, iz);\n      if (is0) return { x: Fp.ZERO, y: Fp.ZERO };\n      if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid');\n      return { x: ax, y: ay };\n    }\n    isTorsionFree(): boolean {\n      const { h: cofactor, isTorsionFree } = CURVE;\n      if (cofactor === _1n) return true; // No subgroups, always torsion-free\n      if (isTorsionFree) return isTorsionFree(Point, this);\n      throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n    }\n    clearCofactor(): Point {\n      const { h: cofactor, clearCofactor } = CURVE;\n      if (cofactor === _1n) return this; // Fast-path\n      if (clearCofactor) return clearCofactor(Point, this) as Point;\n      return this.multiplyUnsafe(CURVE.h);\n    }\n\n    toRawBytes(isCompressed = true): Uint8Array {\n      this.assertValidity();\n      return toBytes(Point, this, isCompressed);\n    }\n\n    toHex(isCompressed = true): string {\n      return ut.bytesToHex(this.toRawBytes(isCompressed));\n    }\n  }\n  const _bits = CURVE.nBitLength;\n  const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n  // Validate if generator point is on curve\n  return {\n    CURVE,\n    ProjectivePoint: Point as ProjConstructor<T>,\n    normPrivateKeyToScalar,\n    weierstrassEquation,\n    isWithinCurveOrder,\n  };\n}\n\n// Instance\nexport interface SignatureType {\n  readonly r: bigint;\n  readonly s: bigint;\n  readonly recovery?: number;\n  assertValidity(): void;\n  addRecoveryBit(recovery: number): RecoveredSignatureType;\n  hasHighS(): boolean;\n  normalizeS(): SignatureType;\n  recoverPublicKey(msgHash: Hex): ProjPointType<bigint>;\n  toCompactRawBytes(): Uint8Array;\n  toCompactHex(): string;\n  // DER-encoded\n  toDERRawBytes(isCompressed?: boolean): Uint8Array;\n  toDERHex(isCompressed?: boolean): string;\n}\nexport type RecoveredSignatureType = SignatureType & {\n  readonly recovery: number;\n};\n// Static methods\nexport type SignatureConstructor = {\n  new (r: bigint, s: bigint): SignatureType;\n  fromCompact(hex: Hex): SignatureType;\n  fromDER(hex: Hex): SignatureType;\n};\ntype SignatureLike = { r: bigint; s: bigint };\n\nexport type PubKey = Hex | ProjPointType<bigint>;\n\nexport type CurveType = BasicWCurve<bigint> & {\n  hash: CHash; // CHash not FHash because we need outputLen for DRBG\n  hmac: HmacFnSync;\n  randomBytes: (bytesLength?: number) => Uint8Array;\n  lowS?: boolean;\n  bits2int?: (bytes: Uint8Array) => bigint;\n  bits2int_modN?: (bytes: Uint8Array) => bigint;\n};\n\nfunction validateOpts(curve: CurveType) {\n  const opts = validateBasic(curve);\n  ut.validateObject(\n    opts,\n    {\n      hash: 'hash',\n      hmac: 'function',\n      randomBytes: 'function',\n    },\n    {\n      bits2int: 'function',\n      bits2int_modN: 'function',\n      lowS: 'boolean',\n    }\n  );\n  return Object.freeze({ lowS: true, ...opts } as const);\n}\n\nexport type CurveFn = {\n  CURVE: ReturnType<typeof validateOpts>;\n  getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array;\n  getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array;\n  sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType;\n  verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean;\n  ProjectivePoint: ProjConstructor<bigint>;\n  Signature: SignatureConstructor;\n  utils: {\n    normPrivateKeyToScalar: (key: PrivKey) => bigint;\n    isValidPrivateKey(privateKey: PrivKey): boolean;\n    randomPrivateKey: () => Uint8Array;\n    precompute: (windowSize?: number, point?: ProjPointType<bigint>) => ProjPointType<bigint>;\n  };\n};\n\nexport function weierstrass(curveDef: CurveType): CurveFn {\n  const CURVE = validateOpts(curveDef) as ReturnType<typeof validateOpts>;\n  const { Fp, n: CURVE_ORDER } = CURVE;\n  const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n  const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n\n  function isValidFieldElement(num: bigint): boolean {\n    return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE\n  }\n  function modN(a: bigint) {\n    return mod.mod(a, CURVE_ORDER);\n  }\n  function invN(a: bigint) {\n    return mod.invert(a, CURVE_ORDER);\n  }\n\n  const {\n    ProjectivePoint: Point,\n    normPrivateKeyToScalar,\n    weierstrassEquation,\n    isWithinCurveOrder,\n  } = weierstrassPoints({\n    ...CURVE,\n    toBytes(_c, point, isCompressed: boolean): Uint8Array {\n      const a = point.toAffine();\n      const x = Fp.toBytes(a.x);\n      const cat = ut.concatBytes;\n      if (isCompressed) {\n        return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n      } else {\n        return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n      }\n    },\n    fromBytes(bytes: Uint8Array) {\n      const len = bytes.length;\n      const head = bytes[0];\n      const tail = bytes.subarray(1);\n      // this.assertValidity() is done inside of fromHex\n      if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n        const x = ut.bytesToNumberBE(tail);\n        if (!isValidFieldElement(x)) throw new Error('Point is not on curve');\n        const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n        let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n        const isYOdd = (y & _1n) === _1n;\n        // ECDSA\n        const isHeadOdd = (head & 1) === 1;\n        if (isHeadOdd !== isYOdd) y = Fp.neg(y);\n        return { x, y };\n      } else if (len === uncompressedLen && head === 0x04) {\n        const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n        const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n        return { x, y };\n      } else {\n        throw new Error(\n          `Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`\n        );\n      }\n    },\n  });\n  const numToNByteStr = (num: bigint): string =>\n    ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n\n  function isBiggerThanHalfOrder(number: bigint) {\n    const HALF = CURVE_ORDER >> _1n;\n    return number > HALF;\n  }\n\n  function normalizeS(s: bigint) {\n    return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n  }\n  // slice bytes num\n  const slcNum = (b: Uint8Array, from: number, to: number) => ut.bytesToNumberBE(b.slice(from, to));\n\n  /**\n   * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n   */\n  class Signature implements SignatureType {\n    constructor(readonly r: bigint, readonly s: bigint, readonly recovery?: number) {\n      this.assertValidity();\n    }\n\n    // pair (bytes of r, bytes of s)\n    static fromCompact(hex: Hex) {\n      const l = CURVE.nByteLength;\n      hex = ensureBytes('compactSignature', hex, l * 2);\n      return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n    }\n\n    // DER encoded ECDSA signature\n    // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n    static fromDER(hex: Hex) {\n      const { r, s } = DER.toSig(ensureBytes('DER', hex));\n      return new Signature(r, s);\n    }\n\n    assertValidity(): void {\n      // can use assertGE here\n      if (!isWithinCurveOrder(this.r)) throw new Error('r must be 0 < r < CURVE.n');\n      if (!isWithinCurveOrder(this.s)) throw new Error('s must be 0 < s < CURVE.n');\n    }\n\n    addRecoveryBit(recovery: number): RecoveredSignature {\n      return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n    }\n\n    recoverPublicKey(msgHash: Hex): typeof Point.BASE {\n      const { r, s, recovery: rec } = this;\n      const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n      if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error('recovery id invalid');\n      const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n      if (radj >= Fp.ORDER) throw new Error('recovery id 2 or 3 invalid');\n      const prefix = (rec & 1) === 0 ? '02' : '03';\n      const R = Point.fromHex(prefix + numToNByteStr(radj));\n      const ir = invN(radj); // r^-1\n      const u1 = modN(-h * ir); // -hr^-1\n      const u2 = modN(s * ir); // sr^-1\n      const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n      if (!Q) throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n      Q.assertValidity();\n      return Q;\n    }\n\n    // Signatures should be low-s, to prevent malleability.\n    hasHighS(): boolean {\n      return isBiggerThanHalfOrder(this.s);\n    }\n\n    normalizeS() {\n      return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n    }\n\n    // DER-encoded\n    toDERRawBytes() {\n      return ut.hexToBytes(this.toDERHex());\n    }\n    toDERHex() {\n      return DER.hexFromSig({ r: this.r, s: this.s });\n    }\n\n    // padded bytes of r, then padded bytes of s\n    toCompactRawBytes() {\n      return ut.hexToBytes(this.toCompactHex());\n    }\n    toCompactHex() {\n      return numToNByteStr(this.r) + numToNByteStr(this.s);\n    }\n  }\n  type RecoveredSignature = Signature & { recovery: number };\n\n  const utils = {\n    isValidPrivateKey(privateKey: PrivKey) {\n      try {\n        normPrivateKeyToScalar(privateKey);\n        return true;\n      } catch (error) {\n        return false;\n      }\n    },\n    normPrivateKeyToScalar: normPrivateKeyToScalar,\n\n    /**\n     * Produces cryptographically secure private key from random of size\n     * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n     */\n    randomPrivateKey: (): Uint8Array => {\n      const length = mod.getMinHashLength(CURVE.n);\n      return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n    },\n\n    /**\n     * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n     * Allows to massively speed-up `point.multiply(scalar)`.\n     * @returns cached point\n     * @example\n     * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n     * fast.multiply(privKey); // much faster ECDH now\n     */\n    precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n      point._setWindowSize(windowSize);\n      point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n      return point;\n    },\n  };\n\n  /**\n   * Computes public key for a private key. Checks for validity of the private key.\n   * @param privateKey private key\n   * @param isCompressed whether to return compact (default), or full key\n   * @returns Public key, full when isCompressed=false; short when isCompressed=true\n   */\n  function getPublicKey(privateKey: PrivKey, isCompressed = true): Uint8Array {\n    return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n  }\n\n  /**\n   * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n   */\n  function isProbPub(item: PrivKey | PubKey): boolean {\n    const arr = item instanceof Uint8Array;\n    const str = typeof item === 'string';\n    const len = (arr || str) && (item as Hex).length;\n    if (arr) return len === compressedLen || len === uncompressedLen;\n    if (str) return len === 2 * compressedLen || len === 2 * uncompressedLen;\n    if (item instanceof Point) return true;\n    return false;\n  }\n\n  /**\n   * ECDH (Elliptic Curve Diffie Hellman).\n   * Computes shared public key from private key and public key.\n   * Checks: 1) private key validity 2) shared key is on-curve.\n   * Does NOT hash the result.\n   * @param privateA private key\n   * @param publicB different public key\n   * @param isCompressed whether to return compact (default), or full key\n   * @returns shared public key\n   */\n  function getSharedSecret(privateA: PrivKey, publicB: Hex, isCompressed = true): Uint8Array {\n    if (isProbPub(privateA)) throw new Error('first arg must be private key');\n    if (!isProbPub(publicB)) throw new Error('second arg must be public key');\n    const b = Point.fromHex(publicB); // check for being on-curve\n    return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n  }\n\n  // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n  // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n  // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n  // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n  const bits2int =\n    CURVE.bits2int ||\n    function (bytes: Uint8Array): bigint {\n      // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n      // for some cases, since bytes.length * 8 is not actual bitLength.\n      const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n      const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n      return delta > 0 ? num >> BigInt(delta) : num;\n    };\n  const bits2int_modN =\n    CURVE.bits2int_modN ||\n    function (bytes: Uint8Array): bigint {\n      return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n    };\n  // NOTE: pads output with zero as per spec\n  const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n  /**\n   * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n   */\n  function int2octets(num: bigint): Uint8Array {\n    if (typeof num !== 'bigint') throw new Error('bigint expected');\n    if (!(_0n <= num && num < ORDER_MASK))\n      throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);\n    // works with order, can have different size than numToField!\n    return ut.numberToBytesBE(num, CURVE.nByteLength);\n  }\n\n  // Steps A, D of RFC6979 3.2\n  // Creates RFC6979 seed; converts msg/privKey to numbers.\n  // Used only in sign, not in verify.\n  // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.\n  // Also it can be bigger for P224 + SHA256\n  function prepSig(msgHash: Hex, privateKey: PrivKey, opts = defaultSigOpts) {\n    if (['recovered', 'canonical'].some((k) => k in opts))\n      throw new Error('sign() legacy options not supported');\n    const { hash, randomBytes } = CURVE;\n    let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n    if (lowS == null) lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n    msgHash = ensureBytes('msgHash', msgHash);\n    if (prehash) msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n\n    // We can't later call bits2octets, since nested bits2int is broken for curves\n    // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n    // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n    const h1int = bits2int_modN(msgHash);\n    const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n    const seedArgs = [int2octets(d), int2octets(h1int)];\n    // extraEntropy. RFC6979 3.6: additional k' (optional).\n    if (ent != null) {\n      // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n      const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n      seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n    }\n    const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n    const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n    // Converts signature params into point w r/s, checks result for validity.\n    function k2sig(kBytes: Uint8Array): RecoveredSignature | undefined {\n      // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n      const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n      if (!isWithinCurveOrder(k)) return; // Important: all mod() calls here must be done over N\n      const ik = invN(k); // k^-1 mod n\n      const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n      const r = modN(q.x); // r = q.x mod n\n      if (r === _0n) return;\n      // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n      // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n      // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n      const s = modN(ik * modN(m + r * d)); // Not using blinding here\n      if (s === _0n) return;\n      let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n      let normS = s;\n      if (lowS && isBiggerThanHalfOrder(s)) {\n        normS = normalizeS(s); // if lowS was passed, ensure s is always\n        recovery ^= 1; // // in the bottom half of N\n      }\n      return new Signature(r, normS, recovery) as RecoveredSignature; // use normS, not s\n    }\n    return { seed, k2sig };\n  }\n  const defaultSigOpts: SignOpts = { lowS: CURVE.lowS, prehash: false };\n  const defaultVerOpts: VerOpts = { lowS: CURVE.lowS, prehash: false };\n\n  /**\n   * Signs message hash with a private key.\n   * ```\n   * sign(m, d, k) where\n   *   (x, y) = G × k\n   *   r = x mod n\n   *   s = (m + dr)/k mod n\n   * ```\n   * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n   * @param privKey private key\n   * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n   * @returns signature with recovery param\n   */\n  function sign(msgHash: Hex, privKey: PrivKey, opts = defaultSigOpts): RecoveredSignature {\n    const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n    const C = CURVE;\n    const drbg = ut.createHmacDrbg<RecoveredSignature>(C.hash.outputLen, C.nByteLength, C.hmac);\n    return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n  }\n\n  // Enable precomputes. Slows down first publicKey computation by 20ms.\n  Point.BASE._setWindowSize(8);\n  // utils.precompute(8, ProjectivePoint.BASE)\n\n  /**\n   * Verifies a signature against message hash and public key.\n   * Rejects lowS signatures by default: to override,\n   * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n   *\n   * ```\n   * verify(r, s, h, P) where\n   *   U1 = hs^-1 mod n\n   *   U2 = rs^-1 mod n\n   *   R = U1⋅G - U2⋅P\n   *   mod(R.x, n) == r\n   * ```\n   */\n  function verify(\n    signature: Hex | SignatureLike,\n    msgHash: Hex,\n    publicKey: Hex,\n    opts = defaultVerOpts\n  ): boolean {\n    const sg = signature;\n    msgHash = ensureBytes('msgHash', msgHash);\n    publicKey = ensureBytes('publicKey', publicKey);\n    if ('strict' in opts) throw new Error('options.strict was renamed to lowS');\n    const { lowS, prehash } = opts;\n\n    let _sig: Signature | undefined = undefined;\n    let P: ProjPointType<bigint>;\n    try {\n      if (typeof sg === 'string' || sg instanceof Uint8Array) {\n        // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n        // Since DER can also be 2*nByteLength bytes, we check for it first.\n        try {\n          _sig = Signature.fromDER(sg);\n        } catch (derError) {\n          if (!(derError instanceof DER.Err)) throw derError;\n          _sig = Signature.fromCompact(sg);\n        }\n      } else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {\n        const { r, s } = sg;\n        _sig = new Signature(r, s);\n      } else {\n        throw new Error('PARSE');\n      }\n      P = Point.fromHex(publicKey);\n    } catch (error) {\n      if ((error as Error).message === 'PARSE')\n        throw new Error(`signature must be Signature instance, Uint8Array or hex string`);\n      return false;\n    }\n    if (lowS && _sig.hasHighS()) return false;\n    if (prehash) msgHash = CURVE.hash(msgHash);\n    const { r, s } = _sig;\n    const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n    const is = invN(s); // s^-1\n    const u1 = modN(h * is); // u1 = hs^-1 mod n\n    const u2 = modN(r * is); // u2 = rs^-1 mod n\n    const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n    if (!R) return false;\n    const v = modN(R.x);\n    return v === r;\n  }\n  return {\n    CURVE,\n    getPublicKey,\n    getSharedSecret,\n    sign,\n    verify,\n    ProjectivePoint: Point,\n    Signature,\n    utils,\n  };\n}\n\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio<T>(Fp: mod.IField<T>, Z: T) {\n  // Generic implementation\n  const q = Fp.ORDER;\n  let l = _0n;\n  for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n;\n  const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n  // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n  // 2n ** c1 == 2n << (c1-1)\n  const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n  const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n  const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1)  # Integer arithmetic\n  const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2            # Integer arithmetic\n  const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1                # Integer arithmetic\n  const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1)                  # Integer arithmetic\n  const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n  const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n  let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => {\n    let tv1 = c6; // 1. tv1 = c6\n    let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n    let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n    tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n    let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n    tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n    tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n    tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n    tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n    let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n    tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n    let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n    tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n    tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n    tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n    tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n    // 17. for i in (c1, c1 - 1, ..., 2):\n    for (let i = c1; i > _1n; i--) {\n      let tv5 = i - _2n; // 18.    tv5 = i - 2\n      tv5 = _2n << (tv5 - _1n); // 19.    tv5 = 2^tv5\n      let tvv5 = Fp.pow(tv4, tv5); // 20.    tv5 = tv4^tv5\n      const e1 = Fp.eql(tvv5, Fp.ONE); // 21.    e1 = tv5 == 1\n      tv2 = Fp.mul(tv3, tv1); // 22.    tv2 = tv3 * tv1\n      tv1 = Fp.mul(tv1, tv1); // 23.    tv1 = tv1 * tv1\n      tvv5 = Fp.mul(tv4, tv1); // 24.    tv5 = tv4 * tv1\n      tv3 = Fp.cmov(tv2, tv3, e1); // 25.    tv3 = CMOV(tv2, tv3, e1)\n      tv4 = Fp.cmov(tvv5, tv4, e1); // 26.    tv4 = CMOV(tv5, tv4, e1)\n    }\n    return { isValid: isQR, value: tv3 };\n  };\n  if (Fp.ORDER % _4n === _3n) {\n    // sqrt_ratio_3mod4(u, v)\n    const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4     # Integer arithmetic\n    const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n    sqrtRatio = (u: T, v: T) => {\n      let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n      const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n      tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n      let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n      y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n      const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n      const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n      const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n      let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n      return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n    };\n  }\n  // No curves uses that\n  // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n  return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU<T>(\n  Fp: mod.IField<T>,\n  opts: {\n    A: T;\n    B: T;\n    Z: T;\n  }\n) {\n  mod.validateField(Fp);\n  if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n    throw new Error('mapToCurveSimpleSWU: invalid opts');\n  const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n  if (!Fp.isOdd) throw new Error('Fp.isOdd is not implemented!');\n  // Input: u, an element of F.\n  // Output: (x, y), a point on E.\n  return (u: T): { x: T; y: T } => {\n    // prettier-ignore\n    let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n    tv1 = Fp.sqr(u); // 1.  tv1 = u^2\n    tv1 = Fp.mul(tv1, opts.Z); // 2.  tv1 = Z * tv1\n    tv2 = Fp.sqr(tv1); // 3.  tv2 = tv1^2\n    tv2 = Fp.add(tv2, tv1); // 4.  tv2 = tv2 + tv1\n    tv3 = Fp.add(tv2, Fp.ONE); // 5.  tv3 = tv2 + 1\n    tv3 = Fp.mul(tv3, opts.B); // 6.  tv3 = B * tv3\n    tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7.  tv4 = CMOV(Z, -tv2, tv2 != 0)\n    tv4 = Fp.mul(tv4, opts.A); // 8.  tv4 = A * tv4\n    tv2 = Fp.sqr(tv3); // 9.  tv2 = tv3^2\n    tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n    tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n    tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n    tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n    tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n    tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n    tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n    x = Fp.mul(tv1, tv3); // 17.   x = tv1 * tv3\n    const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n    y = Fp.mul(tv1, u); // 19.   y = tv1 * u  -> Z * u^3 * y1\n    y = Fp.mul(y, value); // 20.   y = y * y1\n    x = Fp.cmov(x, tv3, isValid); // 21.   x = CMOV(x, tv3, is_gx1_square)\n    y = Fp.cmov(y, value, isValid); // 22.   y = CMOV(y, y1, is_gx1_square)\n    const e1 = Fp.isOdd!(u) === Fp.isOdd!(y); // 23.  e1 = sgn0(u) == sgn0(y)\n    y = Fp.cmov(Fp.neg(y), y, e1); // 24.   y = CMOV(-y, y, e1)\n    x = Fp.div(x, tv4); // 25.   x = x / tv4\n    return { x, y };\n  };\n}\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","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { weierstrass, CurveType } from './abstract/weierstrass.js';\nimport { CHash } from './abstract/utils.js';\n\n// connects noble-curves to noble-hashes\nexport function getHash(hash: CHash) {\n  return {\n    hash,\n    hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(hash, key, concatBytes(...msgs)),\n    randomBytes,\n  };\n}\n// Same API as @noble/hashes, with ability to create curve with custom hash\ntype CurveDef = Readonly<Omit<CurveType, 'hash' | 'hmac' | 'randomBytes'>>;\nexport function createCurve(curveDef: CurveDef, defHash: CHash) {\n  const create = (hash: CHash) => weierstrass({ ...curveDef, ...getHash(hash) });\n  return Object.freeze({ ...create(defHash), create });\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport { ProjPointType as PointType, mapToCurveSimpleSWU } from './abstract/weierstrass.js';\nimport type { Hex, PrivKey } from './abstract/utils.js';\nimport { bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE } from './abstract/utils.js';\nimport { createHasher, isogenyMap } from './abstract/hash-to-curve.js';\nimport { createCurve } from './_shortw_utils.js';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a: bigint, b: bigint) => (a + b / _2n) / b;\n\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y: bigint): bigint {\n  const P = secp256k1P;\n  // prettier-ignore\n  const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n  // prettier-ignore\n  const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n  const b2 = (y * y * y) % P; // x^3, 11\n  const b3 = (b2 * b2 * y) % P; // x^7\n  const b6 = (pow2(b3, _3n, P) * b3) % P;\n  const b9 = (pow2(b6, _3n, P) * b3) % P;\n  const b11 = (pow2(b9, _2n, P) * b2) % P;\n  const b22 = (pow2(b11, _11n, P) * b11) % P;\n  const b44 = (pow2(b22, _22n, P) * b22) % P;\n  const b88 = (pow2(b44, _44n, P) * b44) % P;\n  const b176 = (pow2(b88, _88n, P) * b88) % P;\n  const b220 = (pow2(b176, _44n, P) * b44) % P;\n  const b223 = (pow2(b220, _3n, P) * b3) % P;\n  const t1 = (pow2(b223, _23n, P) * b22) % P;\n  const t2 = (pow2(t1, _6n, P) * b2) % P;\n  const root = pow2(t2, _2n, P);\n  if (!Fp.eql(Fp.sqr(root), y)) throw new Error('Cannot find square root');\n  return root;\n}\n\nconst Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n\nexport const secp256k1 = createCurve(\n  {\n    a: BigInt(0), // equation params: a, b\n    b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975\n    Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n\n    n: secp256k1N, // Curve order, total count of valid points in the field\n    // Base point (x, y) aka generator point\n    Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n    Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n    h: BigInt(1), // Cofactor\n    lowS: true, // Allow only low-S signatures by default in sign() and verify()\n    /**\n     * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n     * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n     * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n     * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066\n     */\n    endo: {\n      beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n      splitScalar: (k: bigint) => {\n        const n = secp256k1N;\n        const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n        const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n        const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n        const b2 = a1;\n        const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n\n        const c1 = divNearest(b2 * k, n);\n        const c2 = divNearest(-b1 * k, n);\n        let k1 = mod(k - c1 * a1 - c2 * a2, n);\n        let k2 = mod(-c1 * b1 - c2 * b2, n);\n        const k1neg = k1 > POW_2_128;\n        const k2neg = k2 > POW_2_128;\n        if (k1neg) k1 = n - k1;\n        if (k2neg) k2 = n - k2;\n        if (k1 > POW_2_128 || k2 > POW_2_128) {\n          throw new Error('splitScalar: Endomorphism failed, k=' + k);\n        }\n        return { k1neg, k1, k2neg, k2 };\n      },\n    },\n  },\n  sha256\n);\n\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\nconst fe = (x: bigint) => typeof x === 'bigint' && _0n < x && x < secp256k1P;\nconst ge = (x: bigint) => typeof x === 'bigint' && _0n < x && x < secp256k1N;\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {};\nfunction taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array {\n  let tagP = TAGGED_HASH_PREFIXES[tag];\n  if (tagP === undefined) {\n    const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n    tagP = concatBytes(tagH, tagH);\n    TAGGED_HASH_PREFIXES[tag] = tagP;\n  }\n  return sha256(concatBytes(tagP, ...messages));\n}\n\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point: PointType<bigint>) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n: bigint) => numberToBytesBE(n, 32);\nconst modP = (x: bigint) => mod(x, secp256k1P);\nconst modN = (x: bigint) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q: PointType<bigint>, a: bigint, b: bigint) =>\n  Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: PrivKey) {\n  let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n  let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside\n  const scalar = p.hasEvenY() ? d_ : modN(-d_);\n  return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x: bigint): PointType<bigint> {\n  if (!fe(x)) throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p.\n  const xx = modP(x * x);\n  const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n  let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n  if (y % _2n !== _0n) y = modP(-y); // Return the unique point P such that x(P) = x and\n  const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n  p.assertValidity();\n  return p;\n}\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args: Uint8Array[]): bigint {\n  return modN(bytesToNumberBE(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey: Hex): Uint8Array {\n  return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(\n  message: Hex,\n  privateKey: PrivKey,\n  auxRand: Hex = randomBytes(32)\n): Uint8Array {\n  const m = ensureBytes('message', message);\n  const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n  const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n  const t = numTo32b(d ^ bytesToNumberBE(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n  const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n  const k_ = modN(bytesToNumberBE(rand)); // Let k' = int(rand) mod n\n  if (k_ === _0n) throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n  const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.\n  const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n  const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n  sig.set(rx, 0);\n  sig.set(numTo32b(modN(k + e * d)), 32);\n  // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n  if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced');\n  return sig;\n}\n\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean {\n  const sig = ensureBytes('signature', signature, 64);\n  const m = ensureBytes('message', message);\n  const pub = ensureBytes('publicKey', publicKey, 32);\n  try {\n    const P = lift_x(bytesToNumberBE(pub)); // P = lift_x(int(pk)); fail if that fails\n    const r = bytesToNumberBE(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n    if (!fe(r)) return false;\n    const s = bytesToNumberBE(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n    if (!ge(s)) return false;\n    const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n    const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P\n    if (!R || !R.hasEvenY() || R.toAffine().x !== r) return false; // -eP == (n-e)P\n    return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n  } catch (error) {\n    return false;\n  }\n}\n\nexport const schnorr = /* @__PURE__ */ (() => ({\n  getPublicKey: schnorrGetPublicKey,\n  sign: schnorrSign,\n  verify: schnorrVerify,\n  utils: {\n    randomPrivateKey: secp256k1.utils.randomPrivateKey,\n    lift_x,\n    pointToBytes,\n    numberToBytesBE,\n    bytesToNumberBE,\n    taggedHash,\n    mod,\n  },\n}))();\n\nconst isoMap = /* @__PURE__ */ (() =>\n  isogenyMap(\n    Fp,\n    [\n      // xNum\n      [\n        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n        '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n        '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n      ],\n      // xDen\n      [\n        '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n        '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n      ],\n      // yNum\n      [\n        '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n        '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n        '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n        '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n      ],\n      // yDen\n      [\n        '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n        '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n        '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n      ],\n    ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]]\n  ))();\nconst mapSWU = /* @__PURE__ */ (() =>\n  mapToCurveSimpleSWU(Fp, {\n    A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n    B: BigInt('1771'),\n    Z: Fp.create(BigInt('-11')),\n  }))();\nconst htf = /* @__PURE__ */ (() =>\n  createHasher(\n    secp256k1.ProjectivePoint,\n    (scalars: bigint[]) => {\n      const { x, y } = mapSWU(Fp.create(scalars[0]));\n      return isoMap(x, y);\n    },\n    {\n      DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n      encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n      p: Fp.ORDER,\n      m: 1,\n      k: 128,\n      expand: 'xmd',\n      hash: sha256,\n    }\n  ))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\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 = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));\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\n// Check if object doens't have custom constructor (like Uint8Array/Array)\nconst isPlainObject = (obj: any) =>\n  Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object;\n\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n  defaults: T1,\n  opts?: T2\n): T1 & T2 {\n  if (opts !== undefined && (typeof opts !== 'object' || !isPlainObject(opts)))\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","export interface Nostr {\n  generateSecretKey(): Uint8Array\n  getPublicKey(secretKey: Uint8Array): string\n  finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n  verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport interface Event {\n  kind: number\n  tags: string[][]\n  content: string\n  created_at: number\n  pubkey: string\n  id: string\n  sig: string\n  [verifiedSymbol]?: boolean\n}\n\nexport type NostrEvent = Event\nexport type EventTemplate = Pick<Event, 'kind' | 'tags' | 'content' | 'created_at'>\nexport type UnsignedEvent = Pick<Event, 'kind' | 'tags' | 'content' | 'created_at' | 'pubkey'>\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n  [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record<string, unknown> => obj instanceof Object\n\nexport function validateEvent<T>(event: T): event is T & UnsignedEvent {\n  if (!isRecord(event)) return false\n  if (typeof event.kind !== 'number') return false\n  if (typeof event.content !== 'string') return false\n  if (typeof event.created_at !== 'number') return false\n  if (typeof event.pubkey !== 'string') return false\n  if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n  if (!Array.isArray(event.tags)) return false\n  for (let i = 0; i < event.tags.length; i++) {\n    let tag = event.tags[i]\n    if (!Array.isArray(tag)) return false\n    for (let j = 0; j < tag.length; j++) {\n      if (typeof tag[j] !== 'string') return false\n    }\n  }\n\n  return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n  return events.sort((a: NostrEvent, b: NostrEvent): number => {\n    if (a.created_at !== b.created_at) {\n      return b.created_at - a.created_at\n    }\n    return a.id.localeCompare(b.id)\n  })\n}\n","export function number(n: number) {\n  if (!Number.isSafeInteger(n) || n < 0) throw new Error(`Wrong positive integer: ${n}`);\n}\n\nexport function bool(b: boolean) {\n  if (typeof b !== 'boolean') throw new Error(`Expected boolean, not ${b}`);\n}\n\nexport function 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};\nexport function 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\nexport function 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}\nexport function 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\nconst assert = {\n  number,\n  bool,\n  bytes,\n  hash,\n  exists,\n  output,\n};\n\nexport default assert;\n","import assert 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    assert.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    assert.exists(this);\n    assert.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","import { SHA2 } from './_sha2.js';\nimport { rotr, wrapConstructor } from './utils.js';\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 = 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 = 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 = 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 = wrapConstructor(() => new SHA256());\nexport const sha224 = wrapConstructor(() => new SHA224());\n","import type { Event } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils'\n\nexport function normalizeURL(url: string): string {\n  try {\n    if (url.indexOf('://') === -1) url = 'wss://' + url\n    let p = new URL(url)\n    p.pathname = p.pathname.replace(/\\/+/g, '/')\n    if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n    if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n    p.searchParams.sort()\n    p.hash = ''\n    return p.toString()\n  } catch (e) {\n    throw new Error(`Invalid URL: ${url}`)\n  }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {\n  const [idx, found] = binarySearch(sortedArray, b => {\n    if (event.id === b.id) return 0\n    if (event.created_at === b.created_at) return -1\n    return b.created_at - event.created_at\n  })\n  if (!found) {\n    sortedArray.splice(idx, 0, event)\n  }\n  return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {\n  const [idx, found] = binarySearch(sortedArray, b => {\n    if (event.id === b.id) return 0\n    if (event.created_at === b.created_at) return -1\n    return event.created_at - b.created_at\n  })\n  if (!found) {\n    sortedArray.splice(idx, 0, event)\n  }\n  return sortedArray\n}\n\nexport function binarySearch<T>(arr: T[], compare: (b: T) => number): [number, boolean] {\n  let start = 0\n  let end = arr.length - 1\n\n  while (start <= end) {\n    const mid = Math.floor((start + end) / 2)\n    const cmp = compare(arr[mid])\n\n    if (cmp === 0) {\n      return [mid, true]\n    }\n\n    if (cmp < 0) {\n      end = mid - 1\n    } else {\n      start = mid + 1\n    }\n  }\n\n  return [start, false]\n}\n\nexport class QueueNode<V> {\n  public value: V\n  public next: QueueNode<V> | null = null\n  public prev: QueueNode<V> | null = null\n\n  constructor(message: V) {\n    this.value = message\n  }\n}\n\nexport class Queue<V> {\n  public first: QueueNode<V> | null\n  public last: QueueNode<V> | null\n\n  constructor() {\n    this.first = null\n    this.last = null\n  }\n\n  enqueue(value: V): boolean {\n    const newNode = new QueueNode(value)\n    if (!this.last) {\n      // list is empty\n      this.first = newNode\n      this.last = newNode\n    } else if (this.last === this.first) {\n      // list has a single element\n      this.last = newNode\n      this.last.prev = this.first\n      this.first.next = newNode\n    } else {\n      // list has elements, add as last\n      newNode.prev = this.last\n      this.last.next = newNode\n      this.last = newNode\n    }\n    return true\n  }\n\n  dequeue(): V | null {\n    if (!this.first) return null\n\n    if (this.first === this.last) {\n      const target = this.first\n      this.first = null\n      this.last = null\n      return target.value\n    }\n\n    const target = this.first\n    this.first = target.next\n    if (this.first) {\n      this.first.prev = null // fix: clean up prev pointer\n    }\n\n    return target.value\n  }\n}\n","import { schnorr } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\nclass JS implements Nostr {\n  generateSecretKey(): Uint8Array {\n    return schnorr.utils.randomPrivateKey()\n  }\n  getPublicKey(secretKey: Uint8Array): string {\n    return bytesToHex(schnorr.getPublicKey(secretKey))\n  }\n  finalizeEvent(t: EventTemplate, secretKey: Uint8Array): VerifiedEvent {\n    const event = t as VerifiedEvent\n    event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))\n    event.id = getEventHash(event)\n    event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey))\n    event[verifiedSymbol] = true\n    return event\n  }\n  verifyEvent(event: Event): event is VerifiedEvent {\n    if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]\n\n    const hash = getEventHash(event)\n    if (hash !== event.id) {\n      event[verifiedSymbol] = false\n      return false\n    }\n\n    try {\n      const valid = schnorr.verify(event.sig, hash, event.pubkey)\n      event[verifiedSymbol] = valid\n      return valid\n    } catch (err) {\n      event[verifiedSymbol] = false\n      return false\n    }\n  }\n}\n\nexport function serializeEvent(evt: UnsignedEvent): string {\n  if (!validateEvent(evt)) throw new Error(\"can't serialize event with wrong or missing properties\")\n  return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])\n}\n\nexport function getEventHash(event: UnsignedEvent): string {\n  let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))\n  return bytesToHex(eventHash)\n}\n\nconst i: JS = new JS()\n\nexport const generateSecretKey = i.generateSecretKey\nexport const getPublicKey = i.getPublicKey\nexport const finalizeEvent = i.finalizeEvent\nexport const verifyEvent = i.verifyEvent\nexport * from './core.ts'\n","import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n  return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n  return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n  return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n  return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n  if (isRegularKind(kind)) return 'regular'\n  if (isReplaceableKind(kind)) return 'replaceable'\n  if (isEphemeralKind(kind)) return 'ephemeral'\n  if (isAddressableKind(kind)) return 'parameterized'\n  return 'unknown'\n}\n\nexport function isKind<T extends number>(event: unknown, kind: T | Array<T>): event is NostrEvent & { kind: T } {\n  const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n  return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\n","import { Event } from './core.ts'\nimport { isAddressableKind, isReplaceableKind } from './kinds.ts'\n\nexport type Filter = {\n  ids?: string[]\n  kinds?: number[]\n  authors?: string[]\n  since?: number\n  until?: number\n  limit?: number\n  search?: string\n  [key: `#${string}`]: string[] | undefined\n}\n\nexport function matchFilter(filter: Filter, event: Event): boolean {\n  if (filter.ids && filter.ids.indexOf(event.id) === -1) {\n    return false\n  }\n  if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) {\n    return false\n  }\n  if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {\n    return false\n  }\n\n  for (let f in filter) {\n    if (f[0] === '#') {\n      let tagName = f.slice(1)\n      let values = filter[`#${tagName}`]\n      if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values!.indexOf(v) !== -1)) return false\n    }\n  }\n\n  if (filter.since && event.created_at < filter.since) return false\n  if (filter.until && event.created_at > filter.until) return false\n\n  return true\n}\n\nexport function matchFilters(filters: Filter[], event: Event): boolean {\n  for (let i = 0; i < filters.length; i++) {\n    if (matchFilter(filters[i], event)) {\n      return true\n    }\n  }\n  return false\n}\n\nexport function mergeFilters(...filters: Filter[]): Filter {\n  let result: Filter = {}\n  for (let i = 0; i < filters.length; i++) {\n    let filter = filters[i]\n    Object.entries(filter).forEach(([property, values]) => {\n      if (property === 'kinds' || property === 'ids' || property === 'authors' || property[0] === '#') {\n        // @ts-ignore\n        result[property] = result[property] || []\n        // @ts-ignore\n        for (let v = 0; v < values.length; v++) {\n          // @ts-ignore\n          let value = values[v]\n          // @ts-ignore\n          if (!result[property].includes(value)) result[property].push(value)\n        }\n      }\n    })\n\n    if (filter.limit && (!result.limit || filter.limit > result.limit)) result.limit = filter.limit\n    if (filter.until && (!result.until || filter.until > result.until)) result.until = filter.until\n    if (filter.since && (!result.since || filter.since < result.since)) result.since = filter.since\n  }\n\n  return result\n}\n\n/**\n * Calculate the intrinsic limit of a filter.\n * This function returns a positive integer, or `Infinity` if there is no intrinsic limit.\n */\nexport function getFilterLimit(filter: Filter): number {\n  if (filter.ids && !filter.ids.length) return 0\n  if (filter.kinds && !filter.kinds.length) return 0\n  if (filter.authors && !filter.authors.length) return 0\n\n  for (const [key, value] of Object.entries(filter)) {\n    if (key[0] === '#' && Array.isArray(value) && !value.length) return 0\n  }\n\n  return Math.min(\n    // The `limit` property creates an artificial limit.\n    Math.max(0, filter.limit ?? Infinity),\n\n    // There can only be one event per `id`.\n    filter.ids?.length ?? Infinity,\n\n    // Replaceable events are limited by the number of authors and kinds.\n    filter.authors?.length && filter.kinds?.every(kind => isReplaceableKind(kind))\n      ? filter.authors.length * filter.kinds.length\n      : Infinity,\n\n    // Parameterized replaceable events are limited by the number of authors, kinds, and \"d\" tags.\n    filter.authors?.length && filter.kinds?.every(kind => isAddressableKind(kind)) && filter['#d']?.length\n      ? filter.authors.length * filter.kinds.length * filter['#d'].length\n      : Infinity,\n  )\n}\n","export function getHex64(json: string, field: string): string {\n  let len = field.length + 3\n  let idx = json.indexOf(`\"${field}\":`) + len\n  let s = json.slice(idx).indexOf(`\"`) + idx + 1\n  return json.slice(s, s + 64)\n}\n\nexport function getInt(json: string, field: string): number {\n  let len = field.length\n  let idx = json.indexOf(`\"${field}\":`) + len + 3\n  let sliced = json.slice(idx)\n  let end = Math.min(sliced.indexOf(','), sliced.indexOf('}'))\n  return parseInt(sliced.slice(0, end), 10)\n}\n\nexport function getSubscriptionId(json: string): string | null {\n  let idx = json.slice(0, 22).indexOf(`\"EVENT\"`)\n  if (idx === -1) return null\n\n  let pstart = json.slice(idx + 7 + 1).indexOf(`\"`)\n  if (pstart === -1) return null\n  let start = idx + 7 + 1 + pstart\n\n  let pend = json.slice(start + 1, 80).indexOf(`\"`)\n  if (pend === -1) return null\n  let end = start + 1 + pend\n\n  return json.slice(start + 1, end)\n}\n\nexport function matchEventId(json: string, id: string): boolean {\n  return id === getHex64(json, 'id')\n}\n\nexport function matchEventPubkey(json: string, pubkey: string): boolean {\n  return pubkey === getHex64(json, 'pubkey')\n}\n\nexport function matchEventKind(json: string, kind: number): boolean {\n  return kind === getInt(json, 'kind')\n}\n","import { EventTemplate } from './core.ts'\nimport { ClientAuth } from './kinds.ts'\n\n/**\n * creates an EventTemplate for an AUTH event to be signed.\n */\nexport function makeAuthEvent(relayURL: string, challenge: string): EventTemplate {\n  return {\n    kind: ClientAuth,\n    created_at: Math.floor(Date.now() / 1000),\n    tags: [\n      ['relay', relayURL],\n      ['challenge', challenge],\n    ],\n    content: '',\n  }\n}\n","import { verifiedSymbol, type Event, type Nostr, VerifiedEvent } from './core.ts'\n\nexport async function yieldThread() {\n  return new Promise<void>(resolve => {\n    const ch = new MessageChannel()\n    const handler = () => {\n      // @ts-ignore (typescript thinks this property should be called `removeListener`, but in fact it's `removeEventListener`)\n      ch.port1.removeEventListener('message', handler)\n      resolve()\n    }\n    // @ts-ignore (typescript thinks this property should be called `addListener`, but in fact it's `addEventListener`)\n    ch.port1.addEventListener('message', handler)\n    ch.port2.postMessage(0)\n    ch.port1.start()\n  })\n}\n\nexport const alwaysTrue: Nostr['verifyEvent'] = (t: Event): t is VerifiedEvent => {\n  t[verifiedSymbol] = true\n  return true\n}\n","/* global WebSocket */\n\nimport { verifyEvent } from './pure.ts'\nimport { AbstractRelay } from './abstract-relay.ts'\n\nvar _WebSocket: typeof WebSocket\n\ntry {\n  _WebSocket = WebSocket\n} catch {}\n\nexport function useWebSocketImplementation(websocketImplementation: any) {\n  _WebSocket = websocketImplementation\n}\n\nexport class Relay extends AbstractRelay {\n  constructor(url: string) {\n    super(url, { verifyEvent, websocketImplementation: _WebSocket })\n  }\n\n  static async connect(url: string): Promise<Relay> {\n    const relay = new Relay(url)\n    await relay.connect()\n    return relay\n  }\n}\n\nexport type RelayRecord = Record<string, { read: boolean; write: boolean }>\n\nexport * from './abstract-relay.ts'\n","/* global WebSocket */\n\nimport type { Event, EventTemplate, VerifiedEvent, Nostr, NostrEvent } from './core.ts'\nimport { matchFilters, type Filter } from './filter.ts'\nimport { getHex64, getSubscriptionId } from './fakejson.ts'\nimport { Queue, normalizeURL } from './utils.ts'\nimport { makeAuthEvent } from './nip42.ts'\nimport { yieldThread } from './helpers.ts'\n\ntype RelayWebSocket = WebSocket & {\n  ping?(): void\n  on?(event: 'pong', listener: () => void): any\n}\n\nexport type AbstractRelayConstructorOptions = {\n  verifyEvent: Nostr['verifyEvent']\n  websocketImplementation?: typeof WebSocket\n  enablePing?: boolean\n}\n\nexport class SendingOnClosedConnection extends Error {\n  constructor(message: string, relay: string) {\n    super(`Tried to send message '${message} on a closed connection to ${relay}.`)\n    this.name = 'SendingOnClosedConnection'\n  }\n}\n\nexport class AbstractRelay {\n  public readonly url: string\n  private _connected: boolean = false\n\n  public onclose: (() => void) | null = null\n  public onnotice: (msg: string) => void = msg => console.debug(`NOTICE from ${this.url}: ${msg}`)\n\n  public baseEoseTimeout: number = 4400\n  public connectionTimeout: number = 4400\n  public publishTimeout: number = 4400\n  public pingFrequency: number = 20000\n  public pingTimeout: number = 20000\n  public openSubs: Map<string, Subscription> = new Map()\n  public enablePing: boolean | undefined\n  private connectionTimeoutHandle: ReturnType<typeof setTimeout> | undefined\n\n  private connectionPromise: Promise<void> | undefined\n  private openCountRequests = new Map<string, CountResolver>()\n  private openEventPublishes = new Map<string, EventPublishResolver>()\n  private ws: RelayWebSocket | undefined\n  private incomingMessageQueue = new Queue<string>()\n  private queueRunning = false\n  private challenge: string | undefined\n  private authPromise: Promise<string> | undefined\n  private serial: number = 0\n  private verifyEvent: Nostr['verifyEvent']\n\n  private _WebSocket: typeof WebSocket\n\n  constructor(url: string, opts: AbstractRelayConstructorOptions) {\n    this.url = normalizeURL(url)\n    this.verifyEvent = opts.verifyEvent\n    this._WebSocket = opts.websocketImplementation || WebSocket\n    this.enablePing = opts.enablePing\n  }\n\n  static async connect(url: string, opts: AbstractRelayConstructorOptions): Promise<AbstractRelay> {\n    const relay = new AbstractRelay(url, opts)\n    await relay.connect()\n    return relay\n  }\n\n  private closeAllSubscriptions(reason: string) {\n    for (let [_, sub] of this.openSubs) {\n      sub.close(reason)\n    }\n    this.openSubs.clear()\n\n    for (let [_, ep] of this.openEventPublishes) {\n      ep.reject(new Error(reason))\n    }\n    this.openEventPublishes.clear()\n\n    for (let [_, cr] of this.openCountRequests) {\n      cr.reject(new Error(reason))\n    }\n    this.openCountRequests.clear()\n  }\n\n  public get connected(): boolean {\n    return this._connected\n  }\n\n  public async connect(): Promise<void> {\n    if (this.connectionPromise) return this.connectionPromise\n\n    this.challenge = undefined\n    this.authPromise = undefined\n    this.connectionPromise = new Promise((resolve, reject) => {\n      this.connectionTimeoutHandle = setTimeout(() => {\n        reject('connection timed out')\n        this.connectionPromise = undefined\n        this.onclose?.()\n        this.closeAllSubscriptions('relay connection timed out')\n      }, this.connectionTimeout)\n\n      try {\n        this.ws = new this._WebSocket(this.url)\n      } catch (err) {\n        clearTimeout(this.connectionTimeoutHandle)\n        reject(err)\n        return\n      }\n\n      this.ws.onopen = () => {\n        clearTimeout(this.connectionTimeoutHandle)\n        this._connected = true\n        if (this.enablePing) {\n          this.pingpong()\n        }\n        resolve()\n      }\n\n      this.ws.onerror = ev => {\n        clearTimeout(this.connectionTimeoutHandle)\n        reject((ev as any).message || 'websocket error')\n        this._connected = false\n        this.connectionPromise = undefined\n        this.onclose?.()\n        this.closeAllSubscriptions('relay connection errored')\n      }\n\n      this.ws.onclose = ev => {\n        clearTimeout(this.connectionTimeoutHandle)\n        reject((ev as any).message || 'websocket closed')\n        this._connected = false\n        this.connectionPromise = undefined\n        this.onclose?.()\n        this.closeAllSubscriptions('relay connection closed')\n      }\n\n      this.ws.onmessage = this._onmessage.bind(this)\n    })\n\n    return this.connectionPromise\n  }\n\n  private async waitForPingPong() {\n    return new Promise((res, err) => {\n      // listen for pong\n      ;(this.ws && this.ws.on && this.ws.on('pong', () => res(true))) || err(\"ws can't listen for pong\")\n      // send a ping\n      this.ws && this.ws.ping && this.ws.ping()\n    })\n  }\n\n  private async waitForDummyReq() {\n    return new Promise((resolve, _) => {\n      // make a dummy request with expected empty eose reply\n      // [\"REQ\", \"_\", {\"ids\":[\"aaaa...aaaa\"]}]\n      const sub = this.subscribe([{ ids: ['a'.repeat(64)] }], {\n        oneose: () => {\n          sub.close()\n          resolve(true)\n        },\n        eoseTimeout: this.pingTimeout + 1000,\n      })\n    })\n  }\n\n  // nodejs requires this magic here to ensure connections are closed when internet goes off and stuff\n  // in browsers it's done automatically. see https://github.com/nbd-wtf/nostr-tools/issues/491\n  private async pingpong() {\n    // if the websocket is connected\n    if (this.ws?.readyState === 1) {\n      // wait for either a ping-pong reply or a timeout\n      const result = await Promise.any([\n        // browsers don't have ping so use a dummy req\n        this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(),\n        new Promise(res => setTimeout(() => res(false), this.pingTimeout)),\n      ])\n      if (result) {\n        // schedule another pingpong\n        setTimeout(() => this.pingpong(), this.pingFrequency)\n      } else {\n        // pingpong closing socket\n        this.closeAllSubscriptions('pingpong timed out')\n        this._connected = false\n        this.onclose?.()\n        this.ws?.close()\n      }\n    }\n  }\n\n  private async runQueue() {\n    this.queueRunning = true\n    while (true) {\n      if (false === this.handleNext()) {\n        break\n      }\n      await yieldThread()\n    }\n    this.queueRunning = false\n  }\n\n  private handleNext(): undefined | false {\n    const json = this.incomingMessageQueue.dequeue()\n    if (!json) {\n      return false\n    }\n\n    const subid = getSubscriptionId(json)\n    if (subid) {\n      const so = this.openSubs.get(subid as string)\n      if (!so) {\n        // this is an EVENT message, but for a subscription we don't have, so just stop here\n        return\n      }\n\n      // this will be called only when this message is a EVENT message for a subscription we have\n      // we do this before parsing the JSON to not have to do that for duplicate events\n      //   since JSON parsing is slow\n      const id = getHex64(json, 'id')\n      const alreadyHave = so.alreadyHaveEvent?.(id)\n\n      // notify any interested client that the relay has this event\n      // (do this after alreadyHaveEvent() because the client may rely on this to answer that)\n      so.receivedEvent?.(this, id)\n\n      if (alreadyHave) {\n        // if we had already seen this event we can just stop here\n        return\n      }\n    }\n\n    try {\n      let data = JSON.parse(json)\n      // we won't do any checks against the data since all failures (i.e. invalid messages from relays)\n      // will naturally be caught by the encompassing try..catch block\n\n      switch (data[0]) {\n        case 'EVENT': {\n          const so = this.openSubs.get(data[1] as string) as Subscription\n          const event = data[2] as NostrEvent\n          if (this.verifyEvent(event) && matchFilters(so.filters, event)) {\n            so.onevent(event)\n          }\n          return\n        }\n        case 'COUNT': {\n          const id: string = data[1]\n          const payload = data[2] as { count: number }\n          const cr = this.openCountRequests.get(id) as CountResolver\n          if (cr) {\n            cr.resolve(payload.count)\n            this.openCountRequests.delete(id)\n          }\n          return\n        }\n        case 'EOSE': {\n          const so = this.openSubs.get(data[1] as string)\n          if (!so) return\n          so.receivedEose()\n          return\n        }\n        case 'OK': {\n          const id: string = data[1]\n          const ok: boolean = data[2]\n          const reason: string = data[3]\n          const ep = this.openEventPublishes.get(id) as EventPublishResolver\n          if (ep) {\n            clearTimeout(ep.timeout)\n            if (ok) ep.resolve(reason)\n            else ep.reject(new Error(reason))\n            this.openEventPublishes.delete(id)\n          }\n          return\n        }\n        case 'CLOSED': {\n          const id: string = data[1]\n          const so = this.openSubs.get(id)\n          if (!so) return\n          so.closed = true\n          so.close(data[2] as string)\n          return\n        }\n        case 'NOTICE':\n          this.onnotice(data[1] as string)\n          return\n        case 'AUTH': {\n          this.challenge = data[1] as string\n          return\n        }\n      }\n    } catch (err) {\n      return\n    }\n  }\n\n  public async send(message: string) {\n    if (!this.connectionPromise) throw new SendingOnClosedConnection(message, this.url)\n\n    this.connectionPromise.then(() => {\n      this.ws?.send(message)\n    })\n  }\n\n  public async auth(signAuthEvent: (evt: EventTemplate) => Promise<VerifiedEvent>): Promise<string> {\n    const challenge = this.challenge\n    if (!challenge) throw new Error(\"can't perform auth, no challenge was received\")\n    if (this.authPromise) return this.authPromise\n\n    this.authPromise = new Promise<string>(async (resolve, reject) => {\n      try {\n        let evt = await signAuthEvent(makeAuthEvent(this.url, challenge))\n        let timeout = setTimeout(() => {\n          let ep = this.openEventPublishes.get(evt.id) as EventPublishResolver\n          if (ep) {\n            ep.reject(new Error('auth timed out'))\n            this.openEventPublishes.delete(evt.id)\n          }\n        }, this.publishTimeout)\n        this.openEventPublishes.set(evt.id, { resolve, reject, timeout })\n        this.send('[\"AUTH\",' + JSON.stringify(evt) + ']')\n      } catch (err) {\n        console.warn('subscribe auth function failed:', err)\n      }\n    })\n    return this.authPromise\n  }\n\n  public async publish(event: Event): Promise<string> {\n    const ret = new Promise<string>((resolve, reject) => {\n      const timeout = setTimeout(() => {\n        const ep = this.openEventPublishes.get(event.id) as EventPublishResolver\n        if (ep) {\n          ep.reject(new Error('publish timed out'))\n          this.openEventPublishes.delete(event.id)\n        }\n      }, this.publishTimeout)\n      this.openEventPublishes.set(event.id, { resolve, reject, timeout })\n    })\n    this.send('[\"EVENT\",' + JSON.stringify(event) + ']')\n    return ret\n  }\n\n  public async count(filters: Filter[], params: { id?: string | null }): Promise<number> {\n    this.serial++\n    const id = params?.id || 'count:' + this.serial\n    const ret = new Promise<number>((resolve, reject) => {\n      this.openCountRequests.set(id, { resolve, reject })\n    })\n    this.send('[\"COUNT\",\"' + id + '\",' + JSON.stringify(filters).substring(1))\n    return ret\n  }\n\n  public subscribe(\n    filters: Filter[],\n    params: Partial<SubscriptionParams> & { label?: string; id?: string },\n  ): Subscription {\n    const subscription = this.prepareSubscription(filters, params)\n    subscription.fire()\n    return subscription\n  }\n\n  public prepareSubscription(\n    filters: Filter[],\n    params: Partial<SubscriptionParams> & { label?: string; id?: string },\n  ): Subscription {\n    this.serial++\n    const id = params.id || (params.label ? params.label + ':' : 'sub:') + this.serial\n    const subscription = new Subscription(this, id, filters, params)\n    this.openSubs.set(id, subscription)\n    return subscription\n  }\n\n  public close() {\n    this.closeAllSubscriptions('relay connection closed by us')\n    this._connected = false\n    this.onclose?.()\n    this.ws?.close()\n  }\n\n  // this is the function assigned to this.ws.onmessage\n  // it's exposed for testing and debugging purposes\n  public _onmessage(ev: MessageEvent<any>) {\n    this.incomingMessageQueue.enqueue(ev.data as string)\n    if (!this.queueRunning) {\n      this.runQueue()\n    }\n  }\n}\n\nexport class Subscription {\n  public readonly relay: AbstractRelay\n  public readonly id: string\n\n  public closed: boolean = false\n  public eosed: boolean = false\n  public filters: Filter[]\n  public alreadyHaveEvent: ((id: string) => boolean) | undefined\n  public receivedEvent: ((relay: AbstractRelay, id: string) => void) | undefined\n\n  public onevent: (evt: Event) => void\n  public oneose: (() => void) | undefined\n  public onclose: ((reason: string) => void) | undefined\n\n  public eoseTimeout: number\n  private eoseTimeoutHandle: ReturnType<typeof setTimeout> | undefined\n\n  constructor(relay: AbstractRelay, id: string, filters: Filter[], params: SubscriptionParams) {\n    this.relay = relay\n    this.filters = filters\n    this.id = id\n    this.alreadyHaveEvent = params.alreadyHaveEvent\n    this.receivedEvent = params.receivedEvent\n    this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout\n\n    this.oneose = params.oneose\n    this.onclose = params.onclose\n    this.onevent =\n      params.onevent ||\n      (event => {\n        console.warn(\n          `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,\n          event,\n        )\n      })\n  }\n\n  public fire() {\n    this.relay.send('[\"REQ\",\"' + this.id + '\",' + JSON.stringify(this.filters).substring(1))\n\n    // only now we start counting the eoseTimeout\n    this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout)\n  }\n\n  public receivedEose() {\n    if (this.eosed) return\n    clearTimeout(this.eoseTimeoutHandle)\n    this.eosed = true\n    this.oneose?.()\n  }\n\n  public close(reason: string = 'closed by caller') {\n    if (!this.closed && this.relay.connected) {\n      // if the connection was closed by the user calling .close() we will send a CLOSE message\n      // otherwise this._open will be already set to false so we will skip this\n      try {\n        this.relay.send('[\"CLOSE\",' + JSON.stringify(this.id) + ']')\n      } catch (err) {\n        if (err instanceof SendingOnClosedConnection) {\n          /* doesn't matter, it's ok */\n        } else {\n          throw err\n        }\n      }\n      this.closed = true\n    }\n    this.relay.openSubs.delete(this.id)\n    this.onclose?.(reason)\n  }\n}\n\nexport type SubscriptionParams = {\n  onevent?: (evt: Event) => void\n  oneose?: () => void\n  onclose?: (reason: string) => void\n  alreadyHaveEvent?: (id: string) => boolean\n  receivedEvent?: (relay: AbstractRelay, id: string) => void\n  eoseTimeout?: number\n}\n\nexport type CountResolver = {\n  resolve: (count: number) => void\n  reject: (err: Error) => void\n}\n\nexport type EventPublishResolver = {\n  resolve: (reason: string) => void\n  reject: (err: Error) => void\n  timeout: ReturnType<typeof setTimeout>\n}\n","/* global WebSocket */\n\nimport { verifyEvent } from './pure.ts'\nimport { AbstractSimplePool } from './abstract-pool.ts'\n\nvar _WebSocket: typeof WebSocket\n\ntry {\n  _WebSocket = WebSocket\n} catch {}\n\nexport function useWebSocketImplementation(websocketImplementation: any) {\n  _WebSocket = websocketImplementation\n}\n\nexport class SimplePool extends AbstractSimplePool {\n  constructor(options?: { enablePing?: boolean }) {\n    super({ verifyEvent, websocketImplementation: _WebSocket, ...options })\n  }\n}\n\nexport * from './abstract-pool.ts'\n","/* global WebSocket */\n\nimport {\n  AbstractRelay as AbstractRelay,\n  SubscriptionParams,\n  Subscription,\n  type AbstractRelayConstructorOptions,\n} from './abstract-relay.ts'\nimport { normalizeURL } from './utils.ts'\n\nimport type { Event, EventTemplate, Nostr, VerifiedEvent } from './core.ts'\nimport { type Filter } from './filter.ts'\nimport { alwaysTrue } from './helpers.ts'\n\nexport type SubCloser = { close: (reason?: string) => void }\n\nexport type AbstractPoolConstructorOptions = AbstractRelayConstructorOptions & {}\n\nexport type SubscribeManyParams = Omit<SubscriptionParams, 'onclose'> & {\n  maxWait?: number\n  onclose?: (reasons: string[]) => void\n  onauth?: (event: EventTemplate) => Promise<VerifiedEvent>\n  // Deprecated: use onauth instead\n  doauth?: (event: EventTemplate) => Promise<VerifiedEvent>\n  id?: string\n  label?: string\n}\n\nexport class AbstractSimplePool {\n  protected relays: Map<string, AbstractRelay> = new Map()\n  public seenOn: Map<string, Set<AbstractRelay>> = new Map()\n  public trackRelays: boolean = false\n\n  public verifyEvent: Nostr['verifyEvent']\n  public enablePing: boolean | undefined\n  public trustedRelayURLs: Set<string> = new Set()\n\n  private _WebSocket?: typeof WebSocket\n\n  constructor(opts: AbstractPoolConstructorOptions) {\n    this.verifyEvent = opts.verifyEvent\n    this._WebSocket = opts.websocketImplementation\n    this.enablePing = opts.enablePing\n  }\n\n  async ensureRelay(url: string, params?: { connectionTimeout?: number }): Promise<AbstractRelay> {\n    url = normalizeURL(url)\n\n    let relay = this.relays.get(url)\n    if (!relay) {\n      relay = new AbstractRelay(url, {\n        verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent,\n        websocketImplementation: this._WebSocket,\n        enablePing: this.enablePing,\n      })\n      relay.onclose = () => {\n        this.relays.delete(url)\n      }\n      if (params?.connectionTimeout) relay.connectionTimeout = params.connectionTimeout\n      this.relays.set(url, relay)\n    }\n    await relay.connect()\n\n    return relay\n  }\n\n  close(relays: string[]) {\n    relays.map(normalizeURL).forEach(url => {\n      this.relays.get(url)?.close()\n      this.relays.delete(url)\n    })\n  }\n\n  subscribe(relays: string[], filter: Filter, params: SubscribeManyParams): SubCloser {\n    params.onauth = params.onauth || params.doauth\n\n    const request: { url: string; filter: Filter }[] = []\n    for (let i = 0; i < relays.length; i++) {\n      const url = normalizeURL(relays[i])\n      if (!request.find(r => r.url === url)) {\n        request.push({ url, filter: filter })\n      }\n    }\n\n    return this.subscribeMap(request, params)\n  }\n\n  subscribeMany(relays: string[], filter: Filter, params: SubscribeManyParams): SubCloser {\n    params.onauth = params.onauth || params.doauth\n\n    const request: { url: string; filter: Filter }[] = []\n    const uniqUrls: string[] = []\n    for (let i = 0; i < relays.length; i++) {\n      const url = normalizeURL(relays[i])\n      if (uniqUrls.indexOf(url) === -1) {\n        uniqUrls.push(url)\n        request.push({ url, filter: filter })\n      }\n    }\n\n    return this.subscribeMap(request, params)\n  }\n\n  subscribeMap(requests: { url: string; filter: Filter }[], params: SubscribeManyParams): SubCloser {\n    params.onauth = params.onauth || params.doauth\n\n    const grouped = new Map<string, Filter[]>()\n    for (const req of requests) {\n      const { url, filter } = req\n      if (!grouped.has(url)) grouped.set(url, [])\n      grouped.get(url)!.push(filter)\n    }\n    const groupedRequests = Array.from(grouped.entries()).map(([url, filters]) => ({ url, filters }))\n\n    if (this.trackRelays) {\n      params.receivedEvent = (relay: AbstractRelay, id: string) => {\n        let set = this.seenOn.get(id)\n        if (!set) {\n          set = new Set()\n          this.seenOn.set(id, set)\n        }\n        set.add(relay)\n      }\n    }\n\n    const _knownIds = new Set<string>()\n    const subs: Subscription[] = []\n\n    // batch all EOSEs into a single\n    const eosesReceived: boolean[] = []\n    let handleEose = (i: number) => {\n      if (eosesReceived[i]) return // do not act twice for the same relay\n      eosesReceived[i] = true\n      if (eosesReceived.filter(a => a).length === requests.length) {\n        params.oneose?.()\n        handleEose = () => {}\n      }\n    }\n    // batch all closes into a single\n    const closesReceived: string[] = []\n    let handleClose = (i: number, reason: string) => {\n      if (closesReceived[i]) return // do not act twice for the same relay\n      handleEose(i)\n      closesReceived[i] = reason\n      if (closesReceived.filter(a => a).length === requests.length) {\n        params.onclose?.(closesReceived)\n        handleClose = () => {}\n      }\n    }\n\n    const localAlreadyHaveEventHandler = (id: string) => {\n      if (params.alreadyHaveEvent?.(id)) {\n        return true\n      }\n      const have = _knownIds.has(id)\n      _knownIds.add(id)\n      return have\n    }\n\n    // open a subscription in all given relays\n    const allOpened = Promise.all(\n      groupedRequests.map(async ({ url, filters }, i) => {\n        let relay: AbstractRelay\n        try {\n          relay = await this.ensureRelay(url, {\n            connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1000) : undefined,\n          })\n        } catch (err) {\n          handleClose(i, (err as any)?.message || String(err))\n          return\n        }\n\n        let subscription = relay.subscribe(filters, {\n          ...params,\n          oneose: () => handleEose(i),\n          onclose: reason => {\n            if (reason.startsWith('auth-required: ') && params.onauth) {\n              relay\n                .auth(params.onauth)\n                .then(() => {\n                  relay.subscribe(filters, {\n                    ...params,\n                    oneose: () => handleEose(i),\n                    onclose: reason => {\n                      handleClose(i, reason) // the second time we won't try to auth anymore\n                    },\n                    alreadyHaveEvent: localAlreadyHaveEventHandler,\n                    eoseTimeout: params.maxWait,\n                  })\n                })\n                .catch(err => {\n                  handleClose(i, `auth was required and attempted, but failed with: ${err}`)\n                })\n            } else {\n              handleClose(i, reason)\n            }\n          },\n          alreadyHaveEvent: localAlreadyHaveEventHandler,\n          eoseTimeout: params.maxWait,\n        })\n\n        subs.push(subscription)\n      }),\n    )\n\n    return {\n      async close(reason?: string) {\n        await allOpened\n        subs.forEach(sub => {\n          sub.close(reason)\n        })\n      },\n    }\n  }\n\n  subscribeEose(\n    relays: string[],\n    filter: Filter,\n    params: Pick<SubscribeManyParams, 'label' | 'id' | 'onevent' | 'onclose' | 'maxWait' | 'onauth' | 'doauth'>,\n  ): SubCloser {\n    params.onauth = params.onauth || params.doauth\n\n    const subcloser = this.subscribe(relays, filter, {\n      ...params,\n      oneose() {\n        subcloser.close('closed automatically on eose')\n      },\n    })\n    return subcloser\n  }\n\n  subscribeManyEose(\n    relays: string[],\n    filter: Filter,\n    params: Pick<SubscribeManyParams, 'label' | 'id' | 'onevent' | 'onclose' | 'maxWait' | 'onauth' | 'doauth'>,\n  ): SubCloser {\n    params.onauth = params.onauth || params.doauth\n\n    const subcloser = this.subscribeMany(relays, filter, {\n      ...params,\n      oneose() {\n        subcloser.close('closed automatically on eose')\n      },\n    })\n    return subcloser\n  }\n\n  async querySync(\n    relays: string[],\n    filter: Filter,\n    params?: Pick<SubscribeManyParams, 'label' | 'id' | 'maxWait'>,\n  ): Promise<Event[]> {\n    return new Promise(async resolve => {\n      const events: Event[] = []\n      this.subscribeEose(relays, filter, {\n        ...params,\n        onevent(event: Event) {\n          events.push(event)\n        },\n        onclose(_: string[]) {\n          resolve(events)\n        },\n      })\n    })\n  }\n\n  async get(\n    relays: string[],\n    filter: Filter,\n    params?: Pick<SubscribeManyParams, 'label' | 'id' | 'maxWait'>,\n  ): Promise<Event | null> {\n    filter.limit = 1\n    const events = await this.querySync(relays, filter, params)\n    events.sort((a, b) => b.created_at - a.created_at)\n    return events[0] || null\n  }\n\n  publish(\n    relays: string[],\n    event: Event,\n    options?: { onauth?: (evt: EventTemplate) => Promise<VerifiedEvent> },\n  ): Promise<string>[] {\n    return relays.map(normalizeURL).map(async (url, i, arr) => {\n      if (arr.indexOf(url) !== i) {\n        // duplicate\n        return Promise.reject('duplicate url')\n      }\n\n      let r = await this.ensureRelay(url)\n      return r\n        .publish(event)\n        .catch(async err => {\n          if (err instanceof Error && err.message.startsWith('auth-required: ') && options?.onauth) {\n            await r.auth(options.onauth)\n            return r.publish(event) // retry\n          }\n          throw err\n        })\n        .then(reason => {\n          if (this.trackRelays) {\n            let set = this.seenOn.get(event.id)\n            if (!set) {\n              set = new Set()\n              this.seenOn.set(event.id, set)\n            }\n            set.add(r)\n          }\n          return reason\n        })\n    })\n  }\n\n  listConnectionStatus(): Map<string, boolean> {\n    const map = new Map<string, boolean>()\n    this.relays.forEach((relay, url) => map.set(url, relay.connected))\n\n    return map\n  }\n\n  destroy(): void {\n    this.relays.forEach(conn => conn.close())\n    this.relays = new Map()\n  }\n}\n","import { bytesToHex, concatBytes, hexToBytes } from '@noble/hashes/utils'\nimport { bech32 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport type NProfile = `nprofile1${string}`\nexport type NEvent = `nevent1${string}`\nexport type NAddr = `naddr1${string}`\nexport type NSec = `nsec1${string}`\nexport type NPub = `npub1${string}`\nexport type Note = `note1${string}`\nexport type Ncryptsec = `ncryptsec1${string}`\n\nexport const NostrTypeGuard = {\n  isNProfile: (value?: string | null): value is NProfile => /^nprofile1[a-z\\d]+$/.test(value || ''),\n  isNEvent: (value?: string | null): value is NEvent => /^nevent1[a-z\\d]+$/.test(value || ''),\n  isNAddr: (value?: string | null): value is NAddr => /^naddr1[a-z\\d]+$/.test(value || ''),\n  isNSec: (value?: string | null): value is NSec => /^nsec1[a-z\\d]{58}$/.test(value || ''),\n  isNPub: (value?: string | null): value is NPub => /^npub1[a-z\\d]{58}$/.test(value || ''),\n  isNote: (value?: string | null): value is Note => /^note1[a-z\\d]+$/.test(value || ''),\n  isNcryptsec: (value?: string | null): value is Ncryptsec => /^ncryptsec1[a-z\\d]+$/.test(value || ''),\n}\n\nexport const Bech32MaxSize = 5000\n\n/**\n * Bech32 regex.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32\n */\nexport const BECH32_REGEX = /[\\x21-\\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/\n\nfunction integerToUint8Array(number: number) {\n  // Create a Uint8Array with enough space to hold a 32-bit integer (4 bytes).\n  const uint8Array = new Uint8Array(4)\n\n  // Use bitwise operations to extract the bytes.\n  uint8Array[0] = (number >> 24) & 0xff // Most significant byte (MSB)\n  uint8Array[1] = (number >> 16) & 0xff\n  uint8Array[2] = (number >> 8) & 0xff\n  uint8Array[3] = number & 0xff // Least significant byte (LSB)\n\n  return uint8Array\n}\n\nexport type ProfilePointer = {\n  pubkey: string // hex\n  relays?: string[]\n}\n\nexport type EventPointer = {\n  id: string // hex\n  relays?: string[]\n  author?: string\n  kind?: number\n}\n\nexport type AddressPointer = {\n  identifier: string\n  pubkey: string\n  kind: number\n  relays?: string[]\n}\n\nexport function decodeNostrURI(nip19code: string): ReturnType<typeof decode> | { type: 'invalid'; data: null } {\n  try {\n    if (nip19code.startsWith('nostr:')) nip19code = nip19code.substring(6)\n    return decode(nip19code)\n  } catch (_err) {\n    return { type: 'invalid', data: null }\n  }\n}\n\nexport type DecodedNevent = {\n  type: 'nevent'\n  data: EventPointer\n}\n\nexport type DecodedNprofile = {\n  type: 'nprofile'\n  data: ProfilePointer\n}\n\nexport type DecodedNaddr = {\n  type: 'naddr'\n  data: AddressPointer\n}\n\nexport type DecodedNsec = {\n  type: 'nsec'\n  data: Uint8Array\n}\n\nexport type DecodedNpub = {\n  type: 'npub'\n  data: string\n}\n\nexport type DecodedNote = {\n  type: 'note'\n  data: string\n}\n\nexport type DecodedResult = DecodedNevent | DecodedNprofile | DecodedNaddr | DecodedNpub | DecodedNsec | DecodedNote\n\nexport function decode(nip19: NEvent): DecodedNevent\nexport function decode(nip19: NProfile): DecodedNprofile\nexport function decode(nip19: NAddr): DecodedNaddr\nexport function decode(nip19: NSec): DecodedNsec\nexport function decode(nip19: NPub): DecodedNpub\nexport function decode(nip19: Note): DecodedNote\nexport function decode(code: string): DecodedResult\nexport function decode(code: string): DecodedResult {\n  let { prefix, words } = bech32.decode(code, Bech32MaxSize)\n  let data = new Uint8Array(bech32.fromWords(words))\n\n  switch (prefix) {\n    case 'nprofile': {\n      let tlv = parseTLV(data)\n      if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nprofile')\n      if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n\n      return {\n        type: 'nprofile',\n        data: {\n          pubkey: bytesToHex(tlv[0][0]),\n          relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n        },\n      }\n    }\n    case 'nevent': {\n      let tlv = parseTLV(data)\n      if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nevent')\n      if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')\n      if (tlv[2] && tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n      if (tlv[3] && tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n      return {\n        type: 'nevent',\n        data: {\n          id: bytesToHex(tlv[0][0]),\n          relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n          author: tlv[2]?.[0] ? bytesToHex(tlv[2][0]) : undefined,\n          kind: tlv[3]?.[0] ? parseInt(bytesToHex(tlv[3][0]), 16) : undefined,\n        },\n      }\n    }\n\n    case 'naddr': {\n      let tlv = parseTLV(data)\n      if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for naddr')\n      if (!tlv[2]?.[0]) throw new Error('missing TLV 2 for naddr')\n      if (tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')\n      if (!tlv[3]?.[0]) throw new Error('missing TLV 3 for naddr')\n      if (tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')\n\n      return {\n        type: 'naddr',\n        data: {\n          identifier: utf8Decoder.decode(tlv[0][0]),\n          pubkey: bytesToHex(tlv[2][0]),\n          kind: parseInt(bytesToHex(tlv[3][0]), 16),\n          relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],\n        },\n      }\n    }\n\n    case 'nsec':\n      return { type: prefix, data }\n\n    case 'npub':\n    case 'note':\n      return { type: prefix, data: bytesToHex(data) }\n\n    default:\n      throw new Error(`unknown prefix ${prefix}`)\n  }\n}\n\ntype TLV = { [t: number]: Uint8Array[] }\n\nfunction parseTLV(data: Uint8Array): TLV {\n  let result: TLV = {}\n  let rest = data\n  while (rest.length > 0) {\n    let t = rest[0]\n    let l = rest[1]\n    let v = rest.slice(2, 2 + l)\n    rest = rest.slice(2 + l)\n    if (v.length < l) throw new Error(`not enough data to read on TLV ${t}`)\n    result[t] = result[t] || []\n    result[t].push(v)\n  }\n  return result\n}\n\nexport function nsecEncode(key: Uint8Array): NSec {\n  return encodeBytes('nsec', key)\n}\n\nexport function npubEncode(hex: string): NPub {\n  return encodeBytes('npub', hexToBytes(hex))\n}\n\nexport function noteEncode(hex: string): Note {\n  return encodeBytes('note', hexToBytes(hex))\n}\n\nfunction encodeBech32<Prefix extends string>(prefix: Prefix, data: Uint8Array): `${Prefix}1${string}` {\n  let words = bech32.toWords(data)\n  return bech32.encode(prefix, words, Bech32MaxSize) as `${Prefix}1${string}`\n}\n\nexport function encodeBytes<Prefix extends string>(prefix: Prefix, bytes: Uint8Array): `${Prefix}1${string}` {\n  return encodeBech32(prefix, bytes)\n}\n\nexport function nprofileEncode(profile: ProfilePointer): NProfile {\n  let data = encodeTLV({\n    0: [hexToBytes(profile.pubkey)],\n    1: (profile.relays || []).map(url => utf8Encoder.encode(url)),\n  })\n  return encodeBech32('nprofile', data)\n}\n\nexport function neventEncode(event: EventPointer): NEvent {\n  let kindArray\n  if (event.kind !== undefined) {\n    kindArray = integerToUint8Array(event.kind)\n  }\n\n  let data = encodeTLV({\n    0: [hexToBytes(event.id)],\n    1: (event.relays || []).map(url => utf8Encoder.encode(url)),\n    2: event.author ? [hexToBytes(event.author)] : [],\n    3: kindArray ? [new Uint8Array(kindArray)] : [],\n  })\n\n  return encodeBech32('nevent', data)\n}\n\nexport function naddrEncode(addr: AddressPointer): NAddr {\n  let kind = new ArrayBuffer(4)\n  new DataView(kind).setUint32(0, addr.kind, false)\n\n  let data = encodeTLV({\n    0: [utf8Encoder.encode(addr.identifier)],\n    1: (addr.relays || []).map(url => utf8Encoder.encode(url)),\n    2: [hexToBytes(addr.pubkey)],\n    3: [new Uint8Array(kind)],\n  })\n  return encodeBech32('naddr', data)\n}\n\nfunction encodeTLV(tlv: TLV): Uint8Array {\n  let entries: Uint8Array[] = []\n\n  Object.entries(tlv)\n    .reverse()\n    .forEach(([t, vs]) => {\n      vs.forEach(v => {\n        let entry = new Uint8Array(v.length + 2)\n        entry.set([parseInt(t)], 0)\n        entry.set([v.length], 1)\n        entry.set(v, 2)\n        entries.push(entry)\n      })\n    })\n\n  return concatBytes(...entries)\n}\n","/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nexport function assertNumber(n) {\n    if (!Number.isSafeInteger(n))\n        throw new Error(`Wrong integer: ${n}`);\n}\nfunction chain(...args) {\n    const wrap = (a, b) => (c) => a(b(c));\n    const encode = Array.from(args)\n        .reverse()\n        .reduce((acc, i) => (acc ? wrap(acc, i.encode) : i.encode), undefined);\n    const decode = args.reduce((acc, i) => (acc ? wrap(acc, i.decode) : i.decode), undefined);\n    return { encode, decode };\n}\nfunction alphabet(alphabet) {\n    return {\n        encode: (digits) => {\n            if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))\n                throw new Error('alphabet.encode input should be an array of numbers');\n            return digits.map((i) => {\n                assertNumber(i);\n                if (i < 0 || i >= alphabet.length)\n                    throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet.length})`);\n                return alphabet[i];\n            });\n        },\n        decode: (input) => {\n            if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string'))\n                throw new Error('alphabet.decode input should be array of strings');\n            return input.map((letter) => {\n                if (typeof letter !== 'string')\n                    throw new Error(`alphabet.decode: not string element=${letter}`);\n                const index = alphabet.indexOf(letter);\n                if (index === -1)\n                    throw new Error(`Unknown letter: \"${letter}\". Allowed: ${alphabet}`);\n                return index;\n            });\n        },\n    };\n}\nfunction join(separator = '') {\n    if (typeof separator !== 'string')\n        throw new Error('join separator should be string');\n    return {\n        encode: (from) => {\n            if (!Array.isArray(from) || (from.length && typeof from[0] !== 'string'))\n                throw new Error('join.encode input should be array of strings');\n            for (let i of from)\n                if (typeof i !== 'string')\n                    throw new Error(`join.encode: non-string input=${i}`);\n            return from.join(separator);\n        },\n        decode: (to) => {\n            if (typeof to !== 'string')\n                throw new Error('join.decode input should be string');\n            return to.split(separator);\n        },\n    };\n}\nfunction padding(bits, chr = '=') {\n    assertNumber(bits);\n    if (typeof chr !== 'string')\n        throw new Error('padding chr should be string');\n    return {\n        encode(data) {\n            if (!Array.isArray(data) || (data.length && typeof data[0] !== 'string'))\n                throw new Error('padding.encode input should be array of strings');\n            for (let i of data)\n                if (typeof i !== 'string')\n                    throw new Error(`padding.encode: non-string input=${i}`);\n            while ((data.length * bits) % 8)\n                data.push(chr);\n            return data;\n        },\n        decode(input) {\n            if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string'))\n                throw new Error('padding.encode input should be array of strings');\n            for (let i of input)\n                if (typeof i !== 'string')\n                    throw new Error(`padding.decode: non-string input=${i}`);\n            let end = input.length;\n            if ((end * bits) % 8)\n                throw new Error('Invalid padding: string should have whole number of bytes');\n            for (; end > 0 && input[end - 1] === chr; end--) {\n                if (!(((end - 1) * bits) % 8))\n                    throw new Error('Invalid padding: string has too much padding');\n            }\n            return input.slice(0, end);\n        },\n    };\n}\nfunction normalize(fn) {\n    if (typeof fn !== 'function')\n        throw new Error('normalize fn should be function');\n    return { encode: (from) => from, decode: (to) => fn(to) };\n}\nfunction convertRadix(data, from, to) {\n    if (from < 2)\n        throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`);\n    if (to < 2)\n        throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`);\n    if (!Array.isArray(data))\n        throw new Error('convertRadix: data should be array');\n    if (!data.length)\n        return [];\n    let pos = 0;\n    const res = [];\n    const digits = Array.from(data);\n    digits.forEach((d) => {\n        assertNumber(d);\n        if (d < 0 || d >= from)\n            throw new Error(`Wrong integer: ${d}`);\n    });\n    while (true) {\n        let carry = 0;\n        let done = true;\n        for (let i = pos; i < digits.length; i++) {\n            const digit = digits[i];\n            const digitBase = from * carry + digit;\n            if (!Number.isSafeInteger(digitBase) ||\n                (from * carry) / from !== carry ||\n                digitBase - digit !== from * carry) {\n                throw new Error('convertRadix: carry overflow');\n            }\n            carry = digitBase % to;\n            digits[i] = Math.floor(digitBase / to);\n            if (!Number.isSafeInteger(digits[i]) || digits[i] * to + carry !== digitBase)\n                throw new Error('convertRadix: carry overflow');\n            if (!done)\n                continue;\n            else if (!digits[i])\n                pos = i;\n            else\n                done = false;\n        }\n        res.push(carry);\n        if (done)\n            break;\n    }\n    for (let i = 0; i < data.length - 1 && data[i] === 0; i++)\n        res.push(0);\n    return res.reverse();\n}\nconst gcd = (a, b) => (!b ? a : gcd(b, a % b));\nconst radix2carry = (from, to) => from + (to - gcd(from, to));\nfunction convertRadix2(data, from, to, padding) {\n    if (!Array.isArray(data))\n        throw new Error('convertRadix2: data should be array');\n    if (from <= 0 || from > 32)\n        throw new Error(`convertRadix2: wrong from=${from}`);\n    if (to <= 0 || to > 32)\n        throw new Error(`convertRadix2: wrong to=${to}`);\n    if (radix2carry(from, to) > 32) {\n        throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`);\n    }\n    let carry = 0;\n    let pos = 0;\n    const mask = 2 ** to - 1;\n    const res = [];\n    for (const n of data) {\n        assertNumber(n);\n        if (n >= 2 ** from)\n            throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);\n        carry = (carry << from) | n;\n        if (pos + from > 32)\n            throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);\n        pos += from;\n        for (; pos >= to; pos -= to)\n            res.push(((carry >> (pos - to)) & mask) >>> 0);\n        carry &= 2 ** pos - 1;\n    }\n    carry = (carry << (to - pos)) & mask;\n    if (!padding && pos >= from)\n        throw new Error('Excess padding');\n    if (!padding && carry)\n        throw new Error(`Non-zero padding: ${carry}`);\n    if (padding && pos > 0)\n        res.push(carry >>> 0);\n    return res;\n}\nfunction radix(num) {\n    assertNumber(num);\n    return {\n        encode: (bytes) => {\n            if (!(bytes instanceof Uint8Array))\n                throw new Error('radix.encode input should be Uint8Array');\n            return convertRadix(Array.from(bytes), 2 ** 8, num);\n        },\n        decode: (digits) => {\n            if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))\n                throw new Error('radix.decode input should be array of strings');\n            return Uint8Array.from(convertRadix(digits, num, 2 ** 8));\n        },\n    };\n}\nfunction radix2(bits, revPadding = false) {\n    assertNumber(bits);\n    if (bits <= 0 || bits > 32)\n        throw new Error('radix2: bits should be in (0..32]');\n    if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)\n        throw new Error('radix2: carry overflow');\n    return {\n        encode: (bytes) => {\n            if (!(bytes instanceof Uint8Array))\n                throw new Error('radix2.encode input should be Uint8Array');\n            return convertRadix2(Array.from(bytes), 8, bits, !revPadding);\n        },\n        decode: (digits) => {\n            if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))\n                throw new Error('radix2.decode input should be array of strings');\n            return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));\n        },\n    };\n}\nfunction unsafeWrapper(fn) {\n    if (typeof fn !== 'function')\n        throw new Error('unsafeWrapper fn should be function');\n    return function (...args) {\n        try {\n            return fn.apply(null, args);\n        }\n        catch (e) { }\n    };\n}\nfunction checksum(len, fn) {\n    assertNumber(len);\n    if (typeof fn !== 'function')\n        throw new Error('checksum fn should be function');\n    return {\n        encode(data) {\n            if (!(data instanceof Uint8Array))\n                throw new Error('checksum.encode: input should be Uint8Array');\n            const checksum = fn(data).slice(0, len);\n            const res = new Uint8Array(data.length + len);\n            res.set(data);\n            res.set(checksum, data.length);\n            return res;\n        },\n        decode(data) {\n            if (!(data instanceof Uint8Array))\n                throw new Error('checksum.decode: input should be Uint8Array');\n            const payload = data.slice(0, -len);\n            const newChecksum = fn(payload).slice(0, len);\n            const oldChecksum = data.slice(-len);\n            for (let i = 0; i < len; i++)\n                if (newChecksum[i] !== oldChecksum[i])\n                    throw new Error('Invalid checksum');\n            return payload;\n        },\n    };\n}\nexport const utils = { alphabet, chain, checksum, radix, radix2, join, padding };\nexport const base16 = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));\nexport const base32 = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join(''));\nexport const base32hex = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join(''));\nexport const base32crockford = chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')));\nexport const base64 = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join(''));\nexport const base64url = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join(''));\nconst genBase58 = (abc) => chain(radix(58), alphabet(abc), join(''));\nexport const base58 = genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');\nexport const base58flickr = genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ');\nexport const base58xrp = genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz');\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\nexport const base58xmr = {\n    encode(data) {\n        let res = '';\n        for (let i = 0; i < data.length; i += 8) {\n            const block = data.subarray(i, i + 8);\n            res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1');\n        }\n        return res;\n    },\n    decode(str) {\n        let res = [];\n        for (let i = 0; i < str.length; i += 11) {\n            const slice = str.slice(i, i + 11);\n            const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);\n            const block = base58.decode(slice);\n            for (let j = 0; j < block.length - blockLen; j++) {\n                if (block[j] !== 0)\n                    throw new Error('base58xmr: wrong padding');\n            }\n            res = res.concat(Array.from(block.slice(block.length - blockLen)));\n        }\n        return Uint8Array.from(res);\n    },\n};\nexport const base58check = (sha256) => chain(checksum(4, (data) => sha256(sha256(data))), base58);\nconst BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join(''));\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\nfunction bech32Polymod(pre) {\n    const b = pre >> 25;\n    let chk = (pre & 0x1ffffff) << 5;\n    for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n        if (((b >> i) & 1) === 1)\n            chk ^= POLYMOD_GENERATORS[i];\n    }\n    return chk;\n}\nfunction bechChecksum(prefix, words, encodingConst = 1) {\n    const len = prefix.length;\n    let chk = 1;\n    for (let i = 0; i < len; i++) {\n        const c = prefix.charCodeAt(i);\n        if (c < 33 || c > 126)\n            throw new Error(`Invalid prefix (${prefix})`);\n        chk = bech32Polymod(chk) ^ (c >> 5);\n    }\n    chk = bech32Polymod(chk);\n    for (let i = 0; i < len; i++)\n        chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n    for (let v of words)\n        chk = bech32Polymod(chk) ^ v;\n    for (let i = 0; i < 6; i++)\n        chk = bech32Polymod(chk);\n    chk ^= encodingConst;\n    return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false));\n}\nfunction genBech32(encoding) {\n    const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n    const _words = radix2(5);\n    const fromWords = _words.decode;\n    const toWords = _words.encode;\n    const fromWordsUnsafe = unsafeWrapper(fromWords);\n    function encode(prefix, words, limit = 90) {\n        if (typeof prefix !== 'string')\n            throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`);\n        if (!Array.isArray(words) || (words.length && typeof words[0] !== 'number'))\n            throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`);\n        const actualLength = prefix.length + 7 + words.length;\n        if (limit !== false && actualLength > limit)\n            throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n        prefix = prefix.toLowerCase();\n        return `${prefix}1${BECH_ALPHABET.encode(words)}${bechChecksum(prefix, words, ENCODING_CONST)}`;\n    }\n    function decode(str, limit = 90) {\n        if (typeof str !== 'string')\n            throw new Error(`bech32.decode input should be string, not ${typeof str}`);\n        if (str.length < 8 || (limit !== false && str.length > limit))\n            throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`);\n        const lowered = str.toLowerCase();\n        if (str !== lowered && str !== str.toUpperCase())\n            throw new Error(`String must be lowercase or uppercase`);\n        str = lowered;\n        const sepIndex = str.lastIndexOf('1');\n        if (sepIndex === 0 || sepIndex === -1)\n            throw new Error(`Letter \"1\" must be present between prefix and data only`);\n        const prefix = str.slice(0, sepIndex);\n        const _words = str.slice(sepIndex + 1);\n        if (_words.length < 6)\n            throw new Error('Data must be at least 6 characters long');\n        const words = BECH_ALPHABET.decode(_words).slice(0, -6);\n        const sum = bechChecksum(prefix, words, ENCODING_CONST);\n        if (!_words.endsWith(sum))\n            throw new Error(`Invalid checksum in ${str}: expected \"${sum}\"`);\n        return { prefix, words };\n    }\n    const decodeUnsafe = unsafeWrapper(decode);\n    function decodeToBytes(str) {\n        const { prefix, words } = decode(str, false);\n        return { prefix, words, bytes: fromWords(words) };\n    }\n    return { encode, decode, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords };\n}\nexport const bech32 = genBech32('bech32');\nexport const bech32m = genBech32('bech32m');\nexport const utf8 = {\n    encode: (data) => new TextDecoder().decode(data),\n    decode: (str) => new TextEncoder().encode(str),\n};\nexport const hex = chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => {\n    if (typeof s !== 'string' || s.length % 2)\n        throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);\n    return s.toLowerCase();\n}));\nconst CODERS = {\n    utf8, hex, base16, base32, base64, base64url, base58, base58xmr\n};\nconst coderTypeError = `Invalid encoding type. Available types: ${Object.keys(CODERS).join(', ')}`;\nexport const bytesToString = (type, bytes) => {\n    if (typeof type !== 'string' || !CODERS.hasOwnProperty(type))\n        throw new TypeError(coderTypeError);\n    if (!(bytes instanceof Uint8Array))\n        throw new TypeError('bytesToString() expects Uint8Array');\n    return CODERS[type].encode(bytes);\n};\nexport const str = bytesToString;\nexport const stringToBytes = (type, str) => {\n    if (!CODERS.hasOwnProperty(type))\n        throw new TypeError(coderTypeError);\n    if (typeof str !== 'string')\n        throw new TypeError('stringToBytes() expects string');\n    return CODERS[type].decode(str);\n};\nexport const bytes = stringToBytes;\n","import { decode, type AddressPointer, type ProfilePointer, type EventPointer } from './nip19.ts'\n\nimport type { Event } from './core.ts'\n\ntype Reference = {\n  text: string\n  profile?: ProfilePointer\n  event?: EventPointer\n  address?: AddressPointer\n}\n\nconst mentionRegex = /\\bnostr:((note|npub|naddr|nevent|nprofile)1\\w+)\\b|#\\[(\\d+)\\]/g\n\nexport function parseReferences(evt: Event): Reference[] {\n  let references: Reference[] = []\n  for (let ref of evt.content.matchAll(mentionRegex)) {\n    if (ref[2]) {\n      // it's a NIP-27 mention\n      try {\n        let { type, data } = decode(ref[1])\n        switch (type) {\n          case 'npub': {\n            references.push({\n              text: ref[0],\n              profile: { pubkey: data as string, relays: [] },\n            })\n            break\n          }\n          case 'nprofile': {\n            references.push({\n              text: ref[0],\n              profile: data as ProfilePointer,\n            })\n            break\n          }\n          case 'note': {\n            references.push({\n              text: ref[0],\n              event: { id: data as string, relays: [] },\n            })\n            break\n          }\n          case 'nevent': {\n            references.push({\n              text: ref[0],\n              event: data as EventPointer,\n            })\n            break\n          }\n          case 'naddr': {\n            references.push({\n              text: ref[0],\n              address: data as AddressPointer,\n            })\n            break\n          }\n        }\n      } catch (err) {\n        /***/\n      }\n    } else if (ref[3]) {\n      // it's a NIP-10 mention\n      let idx = parseInt(ref[3], 10)\n      let tag = evt.tags[idx]\n      if (!tag) continue\n\n      switch (tag[0]) {\n        case 'p': {\n          references.push({\n            text: ref[0],\n            profile: { pubkey: tag[1], relays: tag[2] ? [tag[2]] : [] },\n          })\n          break\n        }\n        case 'e': {\n          references.push({\n            text: ref[0],\n            event: { id: tag[1], relays: tag[2] ? [tag[2]] : [] },\n          })\n          break\n        }\n        case 'a': {\n          try {\n            let [kind, pubkey, identifier] = tag[1].split(':')\n            references.push({\n              text: ref[0],\n              address: {\n                identifier,\n                pubkey,\n                kind: parseInt(kind, 10),\n                relays: tag[2] ? [tag[2]] : [],\n              },\n            })\n          } catch (err) {\n            /***/\n          }\n          break\n        }\n      }\n    }\n  }\n\n  return references\n}\n","import { bytesToHex, randomBytes } from '@noble/hashes/utils'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { cbc } from '@noble/ciphers/aes'\nimport { base64 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nexport function encrypt(secretKey: string | Uint8Array, pubkey: string, text: string): string {\n  const privkey: string = secretKey instanceof Uint8Array ? bytesToHex(secretKey) : secretKey\n  const key = secp256k1.getSharedSecret(privkey, '02' + pubkey)\n  const normalizedKey = getNormalizedX(key)\n\n  let iv = Uint8Array.from(randomBytes(16))\n  let plaintext = utf8Encoder.encode(text)\n\n  let ciphertext = cbc(normalizedKey, iv).encrypt(plaintext)\n\n  let ctb64 = base64.encode(new Uint8Array(ciphertext))\n  let ivb64 = base64.encode(new Uint8Array(iv.buffer))\n\n  return `${ctb64}?iv=${ivb64}`\n}\n\nexport function decrypt(secretKey: string | Uint8Array, pubkey: string, data: string): string {\n  const privkey: string = secretKey instanceof Uint8Array ? bytesToHex(secretKey) : secretKey\n  let [ctb64, ivb64] = data.split('?iv=')\n  let key = secp256k1.getSharedSecret(privkey, '02' + pubkey)\n  let normalizedKey = getNormalizedX(key)\n\n  let iv = base64.decode(ivb64)\n  let ciphertext = base64.decode(ctb64)\n\n  let plaintext = cbc(normalizedKey, iv).decrypt(ciphertext)\n\n  return utf8Decoder.decode(plaintext)\n}\n\nfunction getNormalizedX(key: Uint8Array): Uint8Array {\n  return key.slice(1, 33)\n}\n","function number(n: number) {\n  if (!Number.isSafeInteger(n) || n < 0) throw new Error(`positive integer expected, not ${n}`);\n}\n\nfunction bool(b: boolean) {\n  if (typeof b !== 'boolean') throw new Error(`boolean expected, not ${b}`);\n}\n\nexport function isBytes(a: unknown): a is Uint8Array {\n  return (\n    a instanceof Uint8Array ||\n    (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n  );\n}\n\nfunction bytes(b: Uint8Array | undefined, ...lengths: number[]) {\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}, not of length=${b.length}`);\n}\n\nexport type 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 must 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}\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 };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n","/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\nimport { bytes as abytes, isBytes } from './_assert.js';\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n  Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n// Cast array to different type\nexport const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u16 = (arr: TypedArray) =>\n  new Uint16Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 2));\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// big-endian hardware is rare. Just in case someone still decides to run ciphers:\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\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 * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n  abytes(bytes);\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(char: number): number | undefined {\n  if (char >= asciis._0 && char <= asciis._9) return char - asciis._0;\n  if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10);\n  if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10);\n  return;\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 hl = hex.length;\n  const al = hl / 2;\n  if (hl % 2) throw new Error('padded 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;\n  }\n  return array;\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// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n  return hexToNumber(bytesToHex(bytes));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n  return hexToBytes(n.toString(16).padStart(len * 2, '0'));\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;\ndeclare const TextDecoder: 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(`string expected, got ${typeof str}`);\n  return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n  return new TextDecoder().decode(bytes);\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  else if (isBytes(data)) data = data.slice();\n  else throw new Error(`Uint8Array expected, got ${typeof data}`);\n  return data;\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\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 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array) {\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// 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\n// This will allow to re-use with composable things like packed & base encoders\n// Also, we probably can make tags composable\nexport type Cipher = {\n  encrypt(plaintext: Uint8Array): Uint8Array;\n  decrypt(ciphertext: Uint8Array): Uint8Array;\n};\n\nexport type AsyncCipher = {\n  encrypt(plaintext: Uint8Array): Promise<Uint8Array>;\n  decrypt(ciphertext: Uint8Array): Promise<Uint8Array>;\n};\n\nexport type CipherWithOutput = Cipher & {\n  encrypt(plaintext: Uint8Array, output?: Uint8Array): Uint8Array;\n  decrypt(ciphertext: Uint8Array, output?: Uint8Array): Uint8Array;\n};\n\n// Params is outside return type, so it is accessible before calling constructor\n// If function support multiple nonceLength's, we return best one\nexport type CipherParams = { blockSize: number; nonceLength?: number; tagLength?: number };\nexport type CipherCons<T extends any[]> = (key: Uint8Array, ...args: T) => Cipher;\n/**\n * @__NO_SIDE_EFFECTS__\n */\nexport const wrapCipher = <C extends CipherCons<any>, P extends CipherParams>(\n  params: P,\n  c: C\n): C & P => {\n  Object.assign(c, params);\n  return c as C & P;\n};\n\nexport type XorStream = (\n  key: Uint8Array,\n  nonce: Uint8Array,\n  data: Uint8Array,\n  output?: Uint8Array,\n  counter?: number\n) => Uint8Array;\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(ciphertext: Uint8Array, AAD?: Uint8Array) {\n  const num = new Uint8Array(16);\n  const view = createView(num);\n  setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n  setBigUint64(view, 8, BigInt(ciphertext.length), true);\n  return num;\n}\n","import { createView, toBytes, Input, Hash, u32 } from './utils.js';\nimport { bytes as abytes, exists as aexists, output as aoutput } from './_assert.js';\n\n// GHash from AES-GCM and its little-endian \"mirror image\" Polyval from AES-SIV.\n// Implemented in terms of GHash with conversion function for keys\n// GCM GHASH from NIST SP800-38d, SIV from RFC 8452.\n// https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf\n\n// GHASH   modulo: x^128 + x^7   + x^2   + x     + 1\n// POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1\n\nconst BLOCK_SIZE = 16;\n// TODO: rewrite\n// temporary padding buffer\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\nconst ZEROS32 = u32(ZEROS16);\nconst POLY = 0xe1; // v = 2*v % POLY\n\n// v = 2*v % POLY\n// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x\n// We can multiply any number using montgomery ladder and this function (works as double, add is simple xor)\nconst mul2 = (s0: number, s1: number, s2: number, s3: number) => {\n  const hiBit = s3 & 1;\n  return {\n    s3: (s2 << 31) | (s3 >>> 1),\n    s2: (s1 << 31) | (s2 >>> 1),\n    s1: (s0 << 31) | (s1 >>> 1),\n    s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly\n  };\n};\n\nconst swapLE = (n: number) =>\n  (((n >>> 0) & 0xff) << 24) |\n  (((n >>> 8) & 0xff) << 16) |\n  (((n >>> 16) & 0xff) << 8) |\n  ((n >>> 24) & 0xff) |\n  0;\n\n/**\n * `mulX_POLYVAL(ByteReverse(H))` from spec\n * @param k mutated in place\n */\nexport function _toGHASHKey(k: Uint8Array): Uint8Array {\n  k.reverse();\n  const hiBit = k[15] & 1;\n  // k >>= 1\n  let carry = 0;\n  for (let i = 0; i < k.length; i++) {\n    const t = k[i];\n    k[i] = (t >>> 1) | carry;\n    carry = (t & 1) << 7;\n  }\n  k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000;\n  return k;\n}\n\ntype Value = { s0: number; s1: number; s2: number; s3: number };\n\nconst estimateWindow = (bytes: number) => {\n  if (bytes > 64 * 1024) return 8;\n  if (bytes > 1024) return 4;\n  return 2;\n};\n\nclass GHASH implements Hash<GHASH> {\n  readonly blockLen = BLOCK_SIZE;\n  readonly outputLen = BLOCK_SIZE;\n  protected s0 = 0;\n  protected s1 = 0;\n  protected s2 = 0;\n  protected s3 = 0;\n  protected finished = false;\n  protected t: Value[];\n  private W: number;\n  private windowSize: number;\n  // We select bits per window adaptively based on expectedLength\n  constructor(key: Input, expectedLength?: number) {\n    key = toBytes(key);\n    abytes(key, 16);\n    const kView = createView(key);\n    let k0 = kView.getUint32(0, false);\n    let k1 = kView.getUint32(4, false);\n    let k2 = kView.getUint32(8, false);\n    let k3 = kView.getUint32(12, false);\n    // generate table of doubled keys (half of montgomery ladder)\n    const doubles: Value[] = [];\n    for (let i = 0; i < 128; i++) {\n      doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });\n      ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));\n    }\n    const W = estimateWindow(expectedLength || 1024);\n    if (![1, 2, 4, 8].includes(W))\n      throw new Error(`ghash: wrong window size=${W}, should be 2, 4 or 8`);\n    this.W = W;\n    const bits = 128; // always 128 bits;\n    const windows = bits / W;\n    const windowSize = (this.windowSize = 2 ** W);\n    const items: Value[] = [];\n    // Create precompute table for window of W bits\n    for (let w = 0; w < windows; w++) {\n      // truth table: 00, 01, 10, 11\n      for (let byte = 0; byte < windowSize; byte++) {\n        // prettier-ignore\n        let s0 = 0, s1 = 0, s2 = 0, s3 = 0;\n        for (let j = 0; j < W; j++) {\n          const bit = (byte >>> (W - j - 1)) & 1;\n          if (!bit) continue;\n          const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];\n          (s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3);\n        }\n        items.push({ s0, s1, s2, s3 });\n      }\n    }\n    this.t = items;\n  }\n  protected _updateBlock(s0: number, s1: number, s2: number, s3: number) {\n    (s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3);\n    const { W, t, windowSize } = this;\n    // prettier-ignore\n    let o0 = 0, o1 = 0, o2 = 0, o3 = 0;\n    const mask = (1 << W) - 1; // 2**W will kill performance.\n    let w = 0;\n    for (const num of [s0, s1, s2, s3]) {\n      for (let bytePos = 0; bytePos < 4; bytePos++) {\n        const byte = (num >>> (8 * bytePos)) & 0xff;\n        for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {\n          const bit = (byte >>> (W * bitPos)) & mask;\n          const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];\n          (o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3);\n          w += 1;\n        }\n      }\n    }\n    this.s0 = o0;\n    this.s1 = o1;\n    this.s2 = o2;\n    this.s3 = o3;\n  }\n  update(data: Input): this {\n    data = toBytes(data);\n    aexists(this);\n    const b32 = u32(data);\n    const blocks = Math.floor(data.length / BLOCK_SIZE);\n    const left = data.length % BLOCK_SIZE;\n    for (let i = 0; i < blocks; i++) {\n      this._updateBlock(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]);\n    }\n    if (left) {\n      ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n      this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]);\n      ZEROS32.fill(0); // clean tmp buffer\n    }\n    return this;\n  }\n  destroy() {\n    const { t } = this;\n    // clean precompute table\n    for (const elm of t) {\n      (elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0);\n    }\n  }\n  digestInto(out: Uint8Array) {\n    aexists(this);\n    aoutput(out, this);\n    this.finished = true;\n    const { s0, s1, s2, s3 } = this;\n    const o32 = u32(out);\n    o32[0] = s0;\n    o32[1] = s1;\n    o32[2] = s2;\n    o32[3] = s3;\n    return out;\n  }\n  digest(): Uint8Array {\n    const res = new Uint8Array(BLOCK_SIZE);\n    this.digestInto(res);\n    this.destroy();\n    return res;\n  }\n}\n\nclass Polyval extends GHASH {\n  constructor(key: Input, expectedLength?: number) {\n    key = toBytes(key);\n    const ghKey = _toGHASHKey(key.slice());\n    super(ghKey, expectedLength);\n    ghKey.fill(0);\n  }\n  update(data: Input): this {\n    data = toBytes(data);\n    aexists(this);\n    const b32 = u32(data);\n    const left = data.length % BLOCK_SIZE;\n    const blocks = Math.floor(data.length / BLOCK_SIZE);\n    for (let i = 0; i < blocks; i++) {\n      this._updateBlock(\n        swapLE(b32[i * 4 + 3]),\n        swapLE(b32[i * 4 + 2]),\n        swapLE(b32[i * 4 + 1]),\n        swapLE(b32[i * 4 + 0])\n      );\n    }\n    if (left) {\n      ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n      this._updateBlock(\n        swapLE(ZEROS32[3]),\n        swapLE(ZEROS32[2]),\n        swapLE(ZEROS32[1]),\n        swapLE(ZEROS32[0])\n      );\n      ZEROS32.fill(0); // clean tmp buffer\n    }\n    return this;\n  }\n  digestInto(out: Uint8Array) {\n    aexists(this);\n    aoutput(out, this);\n    this.finished = true;\n    // tmp ugly hack\n    const { s0, s1, s2, s3 } = this;\n    const o32 = u32(out);\n    o32[0] = s0;\n    o32[1] = s1;\n    o32[2] = s2;\n    o32[3] = s3;\n    return out.reverse();\n  }\n}\n\nexport type CHash = ReturnType<typeof wrapConstructorWithKey>;\nfunction wrapConstructorWithKey<H extends Hash<H>>(\n  hashCons: (key: Input, expectedLength?: number) => Hash<H>\n) {\n  const hashC = (msg: Input, key: Input): Uint8Array =>\n    hashCons(key, msg.length).update(toBytes(msg)).digest();\n  const tmp = hashCons(new Uint8Array(16), 0);\n  hashC.outputLen = tmp.outputLen;\n  hashC.blockLen = tmp.blockLen;\n  hashC.create = (key: Input, expectedLength?: number) => hashCons(key, expectedLength);\n  return hashC;\n}\n\nexport const ghash = wrapConstructorWithKey(\n  (key, expectedLength) => new GHASH(key, expectedLength)\n);\nexport const polyval = wrapConstructorWithKey(\n  (key, expectedLength) => new Polyval(key, expectedLength)\n);\n","// prettier-ignore\nimport {\n  wrapCipher, Cipher, CipherWithOutput,\n  createView, setBigUint64, equalBytes, u32, u8,\n} from './utils.js';\nimport { ghash, polyval } from './_polyval.js';\nimport { bytes as abytes } from './_assert.js';\n\n/*\nAES (Advanced Encryption Standard) aka Rijndael block cipher.\n\nData is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:\n1. **S-box**, table substitution\n2. **Shift rows**, cyclic shift left of all rows of data array\n3. **Mix columns**, multiplying every column by fixed polynomial\n4. **Add round key**, round_key xor i-th column of array\n\nResources:\n- FIPS-197 https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf\n- Original proposal: https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf\n*/\n\nconst BLOCK_SIZE = 16;\nconst BLOCK_SIZE32 = 4;\nconst EMPTY_BLOCK = new Uint8Array(BLOCK_SIZE);\nconst POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8\n\n// TODO: remove multiplication, binary ops only\nfunction mul2(n: number) {\n  return (n << 1) ^ (POLY & -(n >> 7));\n}\n\nfunction mul(a: number, b: number) {\n  let res = 0;\n  for (; b > 0; b >>= 1) {\n    // Montgomery ladder\n    res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).\n    a = mul2(a); // a = 2*a\n  }\n  return res;\n}\n\n// AES S-box is generated using finite field inversion,\n// an affine transform, and xor of a constant 0x63.\nconst sbox = /* @__PURE__ */ (() => {\n  let t = new Uint8Array(256);\n  for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x)) t[i] = x;\n  const box = new Uint8Array(256);\n  box[0] = 0x63; // first elm\n  for (let i = 0; i < 255; i++) {\n    let x = t[255 - i];\n    x |= x << 8;\n    box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;\n  }\n  return box;\n})();\n\n// Inverted S-box\nconst invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));\n\n// Rotate u32 by 8\nconst rotr32_8 = (n: number) => (n << 24) | (n >>> 8);\nconst rotl32_8 = (n: number) => (n << 8) | (n >>> 24);\n\n// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:\n// - LE instead of BE\n// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;\n//   so index is u16, instead of u8. This speeds up things, unexpectedly\nfunction genTtable(sbox: Uint8Array, fn: (n: number) => number) {\n  if (sbox.length !== 256) throw new Error('Wrong sbox length');\n  const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));\n  const T1 = T0.map(rotl32_8);\n  const T2 = T1.map(rotl32_8);\n  const T3 = T2.map(rotl32_8);\n  const T01 = new Uint32Array(256 * 256);\n  const T23 = new Uint32Array(256 * 256);\n  const sbox2 = new Uint16Array(256 * 256);\n  for (let i = 0; i < 256; i++) {\n    for (let j = 0; j < 256; j++) {\n      const idx = i * 256 + j;\n      T01[idx] = T0[i] ^ T1[j];\n      T23[idx] = T2[i] ^ T3[j];\n      sbox2[idx] = (sbox[i] << 8) | sbox[j];\n    }\n  }\n  return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };\n}\n\nconst tableEncoding = /* @__PURE__ */ genTtable(\n  sbox,\n  (s: number) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2)\n);\nconst tableDecoding = /* @__PURE__ */ genTtable(\n  invSbox,\n  (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14)\n);\n\nconst xPowers = /* @__PURE__ */ (() => {\n  const p = new Uint8Array(16);\n  for (let i = 0, x = 1; i < 16; i++, x = mul2(x)) p[i] = x;\n  return p;\n})();\n\nexport function expandKeyLE(key: Uint8Array): Uint32Array {\n  abytes(key);\n  const len = key.length;\n  if (![16, 24, 32].includes(len))\n    throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`);\n  const { sbox2 } = tableEncoding;\n  const k32 = u32(key);\n  const Nk = k32.length;\n  const subByte = (n: number) => applySbox(sbox2, n, n, n, n);\n  const xk = new Uint32Array(len + 28); // expanded key\n  xk.set(k32);\n  // 4.3.1 Key expansion\n  for (let i = Nk; i < xk.length; i++) {\n    let t = xk[i - 1];\n    if (i % Nk === 0) t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];\n    else if (Nk > 6 && i % Nk === 4) t = subByte(t);\n    xk[i] = xk[i - Nk] ^ t;\n  }\n  return xk;\n}\n\nexport function expandKeyDecLE(key: Uint8Array): Uint32Array {\n  const encKey = expandKeyLE(key);\n  const xk = encKey.slice();\n  const Nk = encKey.length;\n  const { sbox2 } = tableEncoding;\n  const { T0, T1, T2, T3 } = tableDecoding;\n  // Inverse key by chunks of 4 (rounds)\n  for (let i = 0; i < Nk; i += 4) {\n    for (let j = 0; j < 4; j++) xk[i + j] = encKey[Nk - i - 4 + j];\n  }\n  encKey.fill(0);\n  // apply InvMixColumn except first & last round\n  for (let i = 4; i < Nk - 4; i++) {\n    const x = xk[i];\n    const w = applySbox(sbox2, x, x, x, x);\n    xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];\n  }\n  return xk;\n}\n\n// Apply tables\nfunction apply0123(\n  T01: Uint32Array,\n  T23: Uint32Array,\n  s0: number,\n  s1: number,\n  s2: number,\n  s3: number\n) {\n  return (\n    T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^\n    T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]\n  );\n}\n\nfunction applySbox(sbox2: Uint16Array, s0: number, s1: number, s2: number, s3: number) {\n  return (\n    sbox2[(s0 & 0xff) | (s1 & 0xff00)] |\n    (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16)\n  );\n}\n\nfunction encrypt(xk: Uint32Array, s0: number, s1: number, s2: number, s3: number) {\n  const { sbox2, T01, T23 } = tableEncoding;\n  let k = 0;\n  (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n  const rounds = xk.length / 4 - 2;\n  for (let i = 0; i < rounds; i++) {\n    const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);\n    const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);\n    const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);\n    const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);\n    (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n  }\n  // last round (without mixcolumns, so using SBOX2 table)\n  const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);\n  const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);\n  const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);\n  const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);\n  return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n\nfunction decrypt(xk: Uint32Array, s0: number, s1: number, s2: number, s3: number) {\n  const { sbox2, T01, T23 } = tableDecoding;\n  let k = 0;\n  (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n  const rounds = xk.length / 4 - 2;\n  for (let i = 0; i < rounds; i++) {\n    const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);\n    const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);\n    const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);\n    const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);\n    (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n  }\n  // Last round\n  const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);\n  const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);\n  const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);\n  const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);\n  return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n\nfunction getDst(len: number, dst?: Uint8Array) {\n  if (!dst) return new Uint8Array(len);\n  abytes(dst);\n  if (dst.length < len)\n    throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`);\n  return dst;\n}\n\n// TODO: investigate merging with ctr32\nfunction ctrCounter(xk: Uint32Array, nonce: Uint8Array, src: Uint8Array, dst?: Uint8Array) {\n  abytes(nonce, BLOCK_SIZE);\n  abytes(src);\n  const srcLen = src.length;\n  dst = getDst(srcLen, dst);\n  const ctr = nonce;\n  const c32 = u32(ctr);\n  // Fill block (empty, ctr=0)\n  let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n  const src32 = u32(src);\n  const dst32 = u32(dst);\n  // process blocks\n  for (let i = 0; i + 4 <= src32.length; i += 4) {\n    dst32[i + 0] = src32[i + 0] ^ s0;\n    dst32[i + 1] = src32[i + 1] ^ s1;\n    dst32[i + 2] = src32[i + 2] ^ s2;\n    dst32[i + 3] = src32[i + 3] ^ s3;\n    // Full 128 bit counter with wrap around\n    let carry = 1;\n    for (let i = ctr.length - 1; i >= 0; i--) {\n      carry = (carry + (ctr[i] & 0xff)) | 0;\n      ctr[i] = carry & 0xff;\n      carry >>>= 8;\n    }\n    ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n  }\n  // leftovers (less than block)\n  // It's possible to handle > u32 fast, but is it worth it?\n  const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n  if (start < srcLen) {\n    const b32 = new Uint32Array([s0, s1, s2, s3]);\n    const buf = u8(b32);\n    for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];\n  }\n  return dst;\n}\n\n// AES CTR with overflowing 32 bit counter\n// It's possible to do 32le significantly simpler (and probably faster) by using u32.\n// But, we need both, and perf bottleneck is in ghash anyway.\nfunction ctr32(\n  xk: Uint32Array,\n  isLE: boolean,\n  nonce: Uint8Array,\n  src: Uint8Array,\n  dst?: Uint8Array\n) {\n  abytes(nonce, BLOCK_SIZE);\n  abytes(src);\n  dst = getDst(src.length, dst);\n  const ctr = nonce; // write new value to nonce, so it can be re-used\n  const c32 = u32(ctr);\n  const view = createView(ctr);\n  const src32 = u32(src);\n  const dst32 = u32(dst);\n  const ctrPos = isLE ? 0 : 12;\n  const srcLen = src.length;\n  // Fill block (empty, ctr=0)\n  let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value\n  let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n  // process blocks\n  for (let i = 0; i + 4 <= src32.length; i += 4) {\n    dst32[i + 0] = src32[i + 0] ^ s0;\n    dst32[i + 1] = src32[i + 1] ^ s1;\n    dst32[i + 2] = src32[i + 2] ^ s2;\n    dst32[i + 3] = src32[i + 3] ^ s3;\n    ctrNum = (ctrNum + 1) >>> 0; // u32 wrap\n    view.setUint32(ctrPos, ctrNum, isLE);\n    ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n  }\n  // leftovers (less than a block)\n  const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n  if (start < srcLen) {\n    const b32 = new Uint32Array([s0, s1, s2, s3]);\n    const buf = u8(b32);\n    for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];\n  }\n  return dst;\n}\n\n/**\n * CTR: counter mode. Creates stream cipher.\n * Requires good IV. Parallelizable. OK, but no MAC.\n */\nexport const ctr = wrapCipher(\n  { blockSize: 16, nonceLength: 16 },\n  function ctr(key: Uint8Array, nonce: Uint8Array): CipherWithOutput {\n    abytes(key);\n    abytes(nonce, BLOCK_SIZE);\n    function processCtr(buf: Uint8Array, dst?: Uint8Array) {\n      const xk = expandKeyLE(key);\n      const n = nonce.slice();\n      const out = ctrCounter(xk, n, buf, dst);\n      xk.fill(0);\n      n.fill(0);\n      return out;\n    }\n    return {\n      encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => processCtr(plaintext, dst),\n      decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => processCtr(ciphertext, dst),\n    };\n  }\n);\n\nfunction validateBlockDecrypt(data: Uint8Array) {\n  abytes(data);\n  if (data.length % BLOCK_SIZE !== 0) {\n    throw new Error(\n      `aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`\n    );\n  }\n}\n\nfunction validateBlockEncrypt(plaintext: Uint8Array, pcks5: boolean, dst?: Uint8Array) {\n  let outLen = plaintext.length;\n  const remaining = outLen % BLOCK_SIZE;\n  if (!pcks5 && remaining !== 0)\n    throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');\n  const b = u32(plaintext);\n  if (pcks5) {\n    let left = BLOCK_SIZE - remaining;\n    if (!left) left = BLOCK_SIZE; // if no bytes left, create empty padding block\n    outLen = outLen + left;\n  }\n  const out = getDst(outLen, dst);\n  const o = u32(out);\n  return { b, o, out };\n}\n\nfunction validatePCKS(data: Uint8Array, pcks5: boolean) {\n  if (!pcks5) return data;\n  const len = data.length;\n  if (!len) throw new Error(`aes/pcks5: empty ciphertext not allowed`);\n  const lastByte = data[len - 1];\n  if (lastByte <= 0 || lastByte > 16) throw new Error(`aes/pcks5: wrong padding byte: ${lastByte}`);\n  const out = data.subarray(0, -lastByte);\n  for (let i = 0; i < lastByte; i++)\n    if (data[len - i - 1] !== lastByte) throw new Error(`aes/pcks5: wrong padding`);\n  return out;\n}\n\nfunction padPCKS(left: Uint8Array) {\n  const tmp = new Uint8Array(16);\n  const tmp32 = u32(tmp);\n  tmp.set(left);\n  const paddingByte = BLOCK_SIZE - left.length;\n  for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++) tmp[i] = paddingByte;\n  return tmp32;\n}\n\nexport type BlockOpts = { disablePadding?: boolean };\n\n/**\n * ECB: Electronic CodeBook. Simple deterministic replacement.\n * Dangerous: always map x to y. See [AES Penguin](https://words.filippo.io/the-ecb-penguin/).\n */\nexport const ecb = wrapCipher(\n  { blockSize: 16 },\n  function ecb(key: Uint8Array, opts: BlockOpts = {}): CipherWithOutput {\n    abytes(key);\n    const pcks5 = !opts.disablePadding;\n    return {\n      encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => {\n        abytes(plaintext);\n        const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n        const xk = expandKeyLE(key);\n        let i = 0;\n        for (; i + 4 <= b.length; ) {\n          const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n          (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n        }\n        if (pcks5) {\n          const tmp32 = padPCKS(plaintext.subarray(i * 4));\n          const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);\n          (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n        }\n        xk.fill(0);\n        return _out;\n      },\n      decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => {\n        validateBlockDecrypt(ciphertext);\n        const xk = expandKeyDecLE(key);\n        const out = getDst(ciphertext.length, dst);\n        const b = u32(ciphertext);\n        const o = u32(out);\n        for (let i = 0; i + 4 <= b.length; ) {\n          const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n          (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n        }\n        xk.fill(0);\n        return validatePCKS(out, pcks5);\n      },\n    };\n  }\n);\n\n/**\n * CBC: Cipher-Block-Chaining. Key is previous round’s block.\n * Fragile: needs proper padding. Unauthenticated: needs MAC.\n */\nexport const cbc = wrapCipher(\n  { blockSize: 16, nonceLength: 16 },\n  function cbc(key: Uint8Array, iv: Uint8Array, opts: BlockOpts = {}): CipherWithOutput {\n    abytes(key);\n    abytes(iv, 16);\n    const pcks5 = !opts.disablePadding;\n    return {\n      encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => {\n        const xk = expandKeyLE(key);\n        const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n        const n32 = u32(iv);\n        // prettier-ignore\n        let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n        let i = 0;\n        for (; i + 4 <= b.length; ) {\n          (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]);\n          ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n          (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n        }\n        if (pcks5) {\n          const tmp32 = padPCKS(plaintext.subarray(i * 4));\n          (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]);\n          ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n          (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n        }\n        xk.fill(0);\n        return _out;\n      },\n      decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => {\n        validateBlockDecrypt(ciphertext);\n        const xk = expandKeyDecLE(key);\n        const n32 = u32(iv);\n        const out = getDst(ciphertext.length, dst);\n        const b = u32(ciphertext);\n        const o = u32(out);\n        // prettier-ignore\n        let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n        for (let i = 0; i + 4 <= b.length; ) {\n          // prettier-ignore\n          const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;\n          (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]);\n          const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);\n          (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);\n        }\n        xk.fill(0);\n        return validatePCKS(out, pcks5);\n      },\n    };\n  }\n);\n\n// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen\nfunction computeTag(\n  fn: typeof ghash,\n  isLE: boolean,\n  key: Uint8Array,\n  data: Uint8Array,\n  AAD?: Uint8Array\n) {\n  const h = fn.create(key, data.length + (AAD?.length || 0));\n  if (AAD) h.update(AAD);\n  h.update(data);\n  const num = new Uint8Array(16);\n  const view = createView(num);\n  if (AAD) setBigUint64(view, 0, BigInt(AAD.length * 8), isLE);\n  setBigUint64(view, 8, BigInt(data.length * 8), isLE);\n  h.update(num);\n  return h.digest();\n}\n\n/**\n * GCM: Galois/Counter Mode.\n * Good, modern version of CTR, parallel, with MAC.\n * Be careful: MACs can be forged.\n */\nexport const gcm = wrapCipher(\n  { blockSize: 16, nonceLength: 12, tagLength: 16 },\n  function gcm(key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): Cipher {\n    abytes(nonce);\n    // Nonce can be pretty much anything (even 1 byte). But smaller nonces less secure.\n    if (nonce.length === 0) throw new Error('aes/gcm: empty nonce');\n    const tagLength = 16;\n    function _computeTag(authKey: Uint8Array, tagMask: Uint8Array, data: Uint8Array) {\n      const tag = computeTag(ghash, false, authKey, data, AAD);\n      for (let i = 0; i < tagMask.length; i++) tag[i] ^= tagMask[i];\n      return tag;\n    }\n    function deriveKeys() {\n      const xk = expandKeyLE(key);\n      const authKey = EMPTY_BLOCK.slice();\n      const counter = EMPTY_BLOCK.slice();\n      ctr32(xk, false, counter, counter, authKey);\n      if (nonce.length === 12) {\n        counter.set(nonce);\n      } else {\n        // Spec (NIST 800-38d) supports variable size nonce.\n        // Not supported for now, but can be useful.\n        const nonceLen = EMPTY_BLOCK.slice();\n        const view = createView(nonceLen);\n        setBigUint64(view, 8, BigInt(nonce.length * 8), false);\n        // ghash(nonce || u64be(0) || u64be(nonceLen*8))\n        ghash.create(authKey).update(nonce).update(nonceLen).digestInto(counter);\n      }\n      const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);\n      return { xk, authKey, counter, tagMask };\n    }\n    return {\n      encrypt: (plaintext: Uint8Array) => {\n        abytes(plaintext);\n        const { xk, authKey, counter, tagMask } = deriveKeys();\n        const out = new Uint8Array(plaintext.length + tagLength);\n        ctr32(xk, false, counter, plaintext, out);\n        const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));\n        out.set(tag, plaintext.length);\n        xk.fill(0);\n        return out;\n      },\n      decrypt: (ciphertext: Uint8Array) => {\n        abytes(ciphertext);\n        if (ciphertext.length < tagLength)\n          throw new Error(`aes/gcm: ciphertext less than tagLen (${tagLength})`);\n        const { xk, authKey, counter, tagMask } = deriveKeys();\n        const data = ciphertext.subarray(0, -tagLength);\n        const passedTag = ciphertext.subarray(-tagLength);\n        const tag = _computeTag(authKey, tagMask, data);\n        if (!equalBytes(tag, passedTag)) throw new Error('aes/gcm: invalid ghash tag');\n        const out = ctr32(xk, false, counter, data);\n        authKey.fill(0);\n        tagMask.fill(0);\n        xk.fill(0);\n        return out;\n      },\n    };\n  }\n);\n\nconst limit = (name: string, min: number, max: number) => (value: number) => {\n  if (!Number.isSafeInteger(value) || min > value || value > max)\n    throw new Error(`${name}: invalid value=${value}, must be [${min}..${max}]`);\n};\n\n/**\n * AES-GCM-SIV: classic AES-GCM with nonce-misuse resistance.\n * Guarantees that, when a nonce is repeated, the only security loss is that identical\n * plaintexts will produce identical ciphertexts.\n * RFC 8452, https://datatracker.ietf.org/doc/html/rfc8452\n */\nexport const siv = wrapCipher(\n  { blockSize: 16, nonceLength: 12, tagLength: 16 },\n  function siv(key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): Cipher {\n    const tagLength = 16;\n    // From RFC 8452: Section 6\n    const AAD_LIMIT = limit('AAD', 0, 2 ** 36);\n    const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36);\n    const NONCE_LIMIT = limit('nonce', 12, 12);\n    const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16);\n    abytes(nonce);\n    NONCE_LIMIT(nonce.length);\n    if (AAD) {\n      abytes(AAD);\n      AAD_LIMIT(AAD.length);\n    }\n    function deriveKeys() {\n      const len = key.length;\n      if (len !== 16 && len !== 24 && len !== 32)\n        throw new Error(`key length must be 16, 24 or 32 bytes, got: ${len} bytes`);\n      const xk = expandKeyLE(key);\n      const encKey = new Uint8Array(len);\n      const authKey = new Uint8Array(16);\n      const n32 = u32(nonce);\n      // prettier-ignore\n      let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2];\n      let counter = 0;\n      for (const derivedKey of [authKey, encKey].map(u32)) {\n        const d32 = u32(derivedKey);\n        for (let i = 0; i < d32.length; i += 2) {\n          // aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ...\n          const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3);\n          d32[i + 0] = o0;\n          d32[i + 1] = o1;\n          s0 = ++counter; // increment counter inside state\n        }\n      }\n      xk.fill(0);\n      return { authKey, encKey: expandKeyLE(encKey) };\n    }\n    function _computeTag(encKey: Uint32Array, authKey: Uint8Array, data: Uint8Array) {\n      const tag = computeTag(polyval, true, authKey, data, AAD);\n      // Compute the expected tag by XORing S_s and the nonce, clearing the\n      // most significant bit of the last byte and encrypting with the\n      // message-encryption key.\n      for (let i = 0; i < 12; i++) tag[i] ^= nonce[i];\n      tag[15] &= 0x7f; // Clear the highest bit\n      // encrypt tag as block\n      const t32 = u32(tag);\n      // prettier-ignore\n      let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3];\n      ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3));\n      (t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3);\n      return tag;\n    }\n    // actual decrypt/encrypt of message.\n    function processSiv(encKey: Uint32Array, tag: Uint8Array, input: Uint8Array) {\n      let block = tag.slice();\n      block[15] |= 0x80; // Force highest bit\n      return ctr32(encKey, true, block, input);\n    }\n    return {\n      encrypt: (plaintext: Uint8Array) => {\n        abytes(plaintext);\n        PLAIN_LIMIT(plaintext.length);\n        const { encKey, authKey } = deriveKeys();\n        const tag = _computeTag(encKey, authKey, plaintext);\n        const out = new Uint8Array(plaintext.length + tagLength);\n        out.set(tag, plaintext.length);\n        out.set(processSiv(encKey, tag, plaintext));\n        encKey.fill(0);\n        authKey.fill(0);\n        return out;\n      },\n      decrypt: (ciphertext: Uint8Array) => {\n        abytes(ciphertext);\n        CIPHER_LIMIT(ciphertext.length);\n        const tag = ciphertext.subarray(-tagLength);\n        const { encKey, authKey } = deriveKeys();\n        const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));\n        const expectedTag = _computeTag(encKey, authKey, plaintext);\n        encKey.fill(0);\n        authKey.fill(0);\n        if (!equalBytes(tag, expectedTag)) throw new Error('invalid polyval tag');\n        return plaintext;\n      },\n    };\n  }\n);\n\nfunction isBytes32(a: unknown): a is Uint8Array {\n  return (\n    a != null &&\n    typeof a === 'object' &&\n    (a instanceof Uint32Array || a.constructor.name === 'Uint32Array')\n  );\n}\n\nfunction encryptBlock(xk: Uint32Array, block: Uint8Array) {\n  abytes(block, 16);\n  if (!isBytes32(xk)) throw new Error('_encryptBlock accepts result of expandKeyLE');\n  const b32 = u32(block);\n  let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n  (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n  return block;\n}\n\nfunction decryptBlock(xk: Uint32Array, block: Uint8Array) {\n  abytes(block, 16);\n  if (!isBytes32(xk)) throw new Error('_decryptBlock accepts result of expandKeyLE');\n  const b32 = u32(block);\n  let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n  (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n  return block;\n}\n\n// Highly unsafe private functions for implementing new modes or ciphers based on AES\n// Can change at any time, no API guarantees\nexport const unsafe = {\n  expandKeyLE,\n  expandKeyDecLE,\n  encrypt,\n  decrypt,\n  encryptBlock,\n  decryptBlock,\n  ctrCounter,\n  ctr32,\n};\n","import { ProfilePointer } from './nip19.ts'\n\nexport type Nip05 = `${string}@${string}`\n\n/**\n * NIP-05 regex. The localpart is optional, and should be assumed to be `_` otherwise.\n *\n * - 0: full match\n * - 1: name (optional)\n * - 2: domain\n */\nexport const NIP05_REGEX = /^(?:([\\w.+-]+)@)?([\\w_-]+(\\.[\\w_-]+)+)$/\nexport const isNip05 = (value?: string | null): value is Nip05 => NIP05_REGEX.test(value || '')\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _fetch: any\n\ntry {\n  _fetch = fetch\n} catch (_) {\n  null\n}\n\nexport function useFetchImplementation(fetchImplementation: unknown) {\n  _fetch = fetchImplementation\n}\n\nexport async function searchDomain(domain: string, query = ''): Promise<{ [name: string]: string }> {\n  try {\n    const url = `https://${domain}/.well-known/nostr.json?name=${query}`\n    const res = await _fetch(url, { redirect: 'manual' })\n    if (res.status !== 200) {\n      throw Error('Wrong response code')\n    }\n    const json = await res.json()\n    return json.names\n  } catch (_) {\n    return {}\n  }\n}\n\nexport async function queryProfile(fullname: string): Promise<ProfilePointer | null> {\n  const match = fullname.match(NIP05_REGEX)\n  if (!match) return null\n\n  const [, name = '_', domain] = match\n\n  try {\n    const url = `https://${domain}/.well-known/nostr.json?name=${name}`\n    const res = await _fetch(url, { redirect: 'manual' })\n    if (res.status !== 200) {\n      throw Error('Wrong response code')\n    }\n    const json = await res.json()\n\n    const pubkey = json.names[name]\n    return pubkey ? { pubkey, relays: json.relays?.[pubkey] } : null\n  } catch (_e) {\n    return null\n  }\n}\n\nexport async function isValid(pubkey: string, nip05: Nip05): Promise<boolean> {\n  const res = await queryProfile(nip05)\n  return res ? res.pubkey === pubkey : false\n}\n","import type { Event } from './core.ts'\nimport type { EventPointer, ProfilePointer } from './nip19.ts'\n\nexport function parse(event: Pick<Event, 'tags'>): {\n  /**\n   * Pointer to the root of the thread.\n   */\n  root: EventPointer | undefined\n\n  /**\n   * Pointer to a \"parent\" event that parsed event replies to (responded to).\n   */\n  reply: EventPointer | undefined\n\n  /**\n   * Pointers to events that may or may not be in the reply chain.\n   */\n  mentions: EventPointer[]\n\n  /**\n   * Pointers to events that were directly quoted.\n   */\n  quotes: EventPointer[]\n\n  /**\n   * List of pubkeys that are involved in the thread in no particular order.\n   */\n  profiles: ProfilePointer[]\n} {\n  const result: ReturnType<typeof parse> = {\n    reply: undefined,\n    root: undefined,\n    mentions: [],\n    profiles: [],\n    quotes: [],\n  }\n\n  let maybeParent: EventPointer | undefined\n  let maybeRoot: EventPointer | undefined\n\n  for (let i = event.tags.length - 1; i >= 0; i--) {\n    const tag = event.tags[i]\n\n    if (tag[0] === 'e' && tag[1]) {\n      const [_, eTagEventId, eTagRelayUrl, eTagMarker, eTagAuthor] = tag as [\n        string,\n        string,\n        undefined | string,\n        undefined | string,\n        undefined | string,\n      ]\n\n      const eventPointer: EventPointer = {\n        id: eTagEventId,\n        relays: eTagRelayUrl ? [eTagRelayUrl] : [],\n        author: eTagAuthor,\n      }\n\n      if (eTagMarker === 'root') {\n        result.root = eventPointer\n        continue\n      }\n\n      if (eTagMarker === 'reply') {\n        result.reply = eventPointer\n        continue\n      }\n\n      if (eTagMarker === 'mention') {\n        result.mentions.push(eventPointer)\n        continue\n      }\n\n      if (!maybeParent) {\n        maybeParent = eventPointer\n      } else {\n        maybeRoot = eventPointer\n      }\n\n      result.mentions.push(eventPointer)\n      continue\n    }\n\n    if (tag[0] === 'q' && tag[1]) {\n      const [_, eTagEventId, eTagRelayUrl] = tag as [string, string, undefined | string]\n      result.quotes.push({\n        id: eTagEventId,\n        relays: eTagRelayUrl ? [eTagRelayUrl] : [],\n      })\n    }\n\n    if (tag[0] === 'p' && tag[1]) {\n      result.profiles.push({\n        pubkey: tag[1],\n        relays: tag[2] ? [tag[2]] : [],\n      })\n      continue\n    }\n  }\n\n  // get legacy (positional) markers, set reply to root and vice-versa if one of them is missing\n  if (!result.root) {\n    result.root = maybeRoot || maybeParent || result.reply\n  }\n  if (!result.reply) {\n    result.reply = maybeParent || result.root\n  }\n\n  // remove root and reply from mentions, inherit relay hints from authors if any\n  ;[result.reply, result.root].forEach(ref => {\n    if (!ref) return\n\n    let idx = result.mentions.indexOf(ref)\n    if (idx !== -1) {\n      result.mentions.splice(idx, 1)\n    }\n    if (ref.author) {\n      let author = result.profiles.find(p => p.pubkey === ref.author)\n      if (author && author.relays) {\n        if (!ref.relays) {\n          ref.relays = []\n        }\n        author.relays.forEach(url => {\n          if (ref.relays!?.indexOf(url) === -1) ref.relays!.push(url)\n        })\n        author.relays = ref.relays\n      }\n    }\n  })\n\n  result.mentions.forEach(ref => {\n    if (ref!.author) {\n      let author = result.profiles.find(p => p.pubkey === ref.author)\n      if (author && author.relays) {\n        if (!ref.relays) {\n          ref.relays = []\n        }\n        author.relays.forEach(url => {\n          if (ref.relays!.indexOf(url) === -1) ref.relays!.push(url)\n        })\n        author.relays = ref.relays\n      }\n    }\n  })\n\n  return result\n}\n","var _fetch: any\n\ntry {\n  _fetch = fetch\n} catch {}\n\nexport function useFetchImplementation(fetchImplementation: any): void {\n  _fetch = fetchImplementation\n}\n\nexport async function fetchRelayInformation(url: string): Promise<RelayInformation> {\n  return (await (\n    await fetch(url.replace('ws://', 'http://').replace('wss://', 'https://'), {\n      headers: { Accept: 'application/nostr+json' },\n    })\n  ).json()) as RelayInformation\n}\n\n/**\n * ## Relay Information Document\n\n * Relays may provide server metadata to clients to inform\n * them of capabilities, administrative contacts, and\n * various server attributes. This is made available as a\n * JSON document over HTTP, on the same URI as the relay's\n * websocket.\n\n * Any field may be omitted, and clients MUST ignore any\n * additional fields they do not understand. Relays MUST\n * accept CORS requests by sending\n * `Access-Control-Allow-Origin`,\n * `Access-Control-Allow-Headers`, and\n * `Access-Control-Allow-Methods` headers.\n * @param name string identifying relay\n * @param description string with detailed information\n * @param pubkey administrative contact pubkey\n * @param contact: administrative alternate contact\n * @param supported_nips a list of NIP numbers supported by\n * the relay\n * @param software identifying relay software URL\n * @param version string version identifier\n */\nexport interface BasicRelayInformation {\n  // string identifying relay\n  name: string\n  description: string\n  pubkey: string\n  contact: string\n  supported_nips: number[]\n  software: string\n  version: string\n  // limitation?: Limitations<A, P>\n}\n\n/**\n *  * ## Extra Fields\n\n *  * ### Server Limitations\n\n * These are limitations imposed by the relay on clients.\n * Your client should expect that requests which exceed\n * these practical_ limitations are rejected or fail immediately.\n * @param max_message_length this is the maximum number of\n * bytes for incoming JSON that the relay will attempt to\n * decode and act upon. When you send large subscriptions,\n * you will be limited by this value. It also effectively\n * limits the maximum size of any event. Value is calculated\n * from `[` to `]` and is after UTF-8 serialization (so some\n * unicode characters will cost 2-3 bytes). It is equal to\n * the maximum size of the WebSocket message frame.\n * @param max_subscriptions total number of subscriptions\n * that may be active on a single websocket connection to\n * this relay. It's possible that authenticated clients with\n * a (paid) relationship to the relay may have higher limits.\n * @param max_filters maximum number of filter values in\n * each subscription. Must be one or higher.\n * @param max_limit the relay server will clamp each\n * filter's `limit` value to this number.\n * This means the client won't be able to get more than this\n * number of events from a single subscription filter. This\n * clamping is typically done silently by the relay, but\n * with this number, you can know that there are additional\n * results if you narrowed your filter's time range or other\n * parameters.\n * @param max_subid_length maximum length of subscription id as a\n * string.\n * @param min_prefix for `authors` and `ids` filters which\n * are to match against a hex prefix, you must provide at\n * least this many hex digits in the prefix.\n * @param max_event_tags in any event, this is the maximum\n * number of elements in the `tags` list.\n * @param max_content_length maximum number of characters in\n * the `content` field of any event. This is a count of\n * unicode characters. After serializing into JSON it may be\n * larger (in bytes), and is still subject to the\n * max_message_length`, if defined.\n * @param min_pow_difficulty new events will require at\n * least this difficulty of PoW, based on [NIP-13](13.md),\n * or they will be rejected by this server.\n * @param auth_required this relay requires [NIP-42](42.md)\n * authentication to happen before a new connection may\n * perform any other action. Even if set to False,\n * authentication may be required for specific actions.\n * @param restricted_writes: this relay requires some kind\n * of condition to be fulfilled in order to accept events\n * (not necessarily, but including\n * @param payment_required this relay requires payment\n * before a new connection may perform any action.\n * @param created_at_lower_limit: 'created_at' lower limit\n * @param created_at_upper_limit: 'created_at' upper limit\n */\nexport interface Limitations {\n  max_message_length: number\n  max_subscriptions: number\n  max_filters: number\n  max_limit: number\n  max_subid_length: number\n  min_prefix: number\n  max_event_tags: number\n  max_content_length: number\n  min_pow_difficulty: number\n  auth_required: boolean\n  payment_required: boolean\n  created_at_lower_limit: number\n  created_at_upper_limit: number\n  restricted_writes: boolean\n}\n\nexport interface RetentionDetails {\n  kinds: (number | number[])[]\n  time?: number | null\n  count?: number | null\n}\ntype AnyRetentionDetails = RetentionDetails\n/**\n * ### Event Retention\n\n * There may be a cost associated with storing data forever,\n * so relays may wish to state retention times. The values\n * stated here are defaults for unauthenticated users and\n * visitors. Paid users would likely have other policies.\n\n * Retention times are given in seconds, with `null`\n * indicating infinity. If zero is provided, this means the\n * event will not be stored at all, and preferably an error\n * will be provided when those are received.\n * ```json\n{\n...\n  \"retention\": [\n    { \"kinds\": [0, 1, [5, 7], [40, 49]], \"time\": 3600 },\n    { \"kinds\": [[40000, 49999]], \"time\": 100 },\n    { \"kinds\": [[30000, 39999]], \"count\": 1000 },\n    { \"time\": 3600, \"count\": 10000 }\n  ]\n...\n}\n```\n * @param retention is a list of specifications: each will\n * apply to either all kinds, or a subset of kinds. Ranges\n * may be specified for the kind field as a tuple of\n * inclusive start and end values. Events of indicated kind\n * (or all) are then limited to a `count` and/or time\n * period.\n\n * It is possible to effectively blacklist Nostr-based\n * protocols that rely on a specific `kind` number, by\n * giving a retention time of zero for those `kind` values.\n * While that is unfortunate, it does allow clients to\n * discover servers that will support their protocol quickly\n * via a single HTTP fetch.\n\n * There is no need to specify retention times for\n * _ephemeral events_ as defined in [NIP-16](16.md) since\n * they are not retained.\n */\nexport interface Retention {\n  retention: AnyRetentionDetails[]\n}\n\n/**\n * Some relays may be governed by the arbitrary laws of a\n * nation state. This may limit what content can be stored\n * in cleartext on those relays. All clients are encouraged\n * to use encryption to work around this limitation.\n\n * It is not possible to describe the limitations of each\n * country's laws and policies which themselves are\n * typically vague and constantly shifting.\n\n * Therefore, this field allows the relay operator to\n * indicate which countries' laws might end up being\n * enforced on them, and then indirectly on their users'\n * content.\n\n * Users should be able to avoid relays in countries they\n * don't like, and/or select relays in more favourable\n * zones. Exposing this flexibility is up to the client\n * software.\n\n * @param relay_countries a list of two-level ISO country\n * codes (ISO 3166-1 alpha-2) whose laws and policies may\n * affect this relay. `EU` may be used for European Union\n * countries.\n\n * Remember that a relay may be hosted in a country which is\n * not the country of the legal entities who own the relay,\n * so it's very likely a number of countries are involved.\n */\nexport interface ContentLimitations {\n  relay_countries: string[]\n}\n\n/**\n * ### Community Preferences\n\n * For public text notes at least, a relay may try to foster\n * a local community. This would encourage users to follow\n * the global feed on that relay, in addition to their usual\n * individual follows. To support this goal, relays MAY\n * specify some of the following values.\n\n * @param language_tags  is an ordered list of [IETF\n * language\n * tags](https://en.wikipedia.org/wiki/IETF_language_tag\n * indicating the major languages spoken on the relay.\n * @param tags is a list of limitations on the topics to be\n * discussed. For example `sfw-only` indicates that only\n * \"Safe For Work\" content is encouraged on this relay. This\n * relies on assumptions of what the \"work\" \"community\"\n * feels \"safe\" talking about. In time, a common set of tags\n * may emerge that allow users to find relays that suit\n * their needs, and client software will be able to parse\n * these tags easily. The `bitcoin-only` tag indicates that\n * any _altcoin_, _\"crypto\"_ or _blockchain_ comments will\n * be ridiculed without mercy.\n * @param posting_policy is a link to a human-readable page\n * which specifies the community policies for the relay. In\n * cases where `sfw-only` is True, it's important to link to\n * a page which gets into the specifics of your posting\n * policy.\n\n * The `description` field should be used to describe your\n * community goals and values, in brief. The\n * `posting_policy` is for additional detail and legal\n * terms. Use the `tags` field to signify limitations on\n * content, or topics to be discussed, which could be\n * machine processed by appropriate client software.\n */\nexport interface CommunityPreferences {\n  language_tags: string[]\n  tags: string[]\n  posting_policy: string\n}\n\nexport interface Amount {\n  amount: number\n  unit: 'msat'\n}\nexport interface PublicationAmount extends Amount {\n  kinds: number[]\n}\nexport interface Subscription extends Amount {\n  period: number\n}\nexport interface Fees {\n  admission: Amount[]\n  subscription: Subscription[]\n  publication: PublicationAmount[]\n}\n/**\n * Relays that require payments may want to expose their fee\n * schedules.\n */\nexport interface PayToRelay {\n  payments_url: string\n  fees: Fees\n}\n\n/**\n * A URL pointing to an image to be used as an icon for the\n * relay. Recommended to be squared in shape.\n */\nexport interface Icon {\n  icon: string\n}\n\nexport type RelayInformation = BasicRelayInformation &\n  Partial<Retention> & {\n    limitation?: Partial<Limitations>\n  } & Partial<ContentLimitations> &\n  Partial<CommunityPreferences> &\n  Partial<PayToRelay> &\n  Partial<Icon>\n","import { bytesToHex } from '@noble/hashes/utils'\nimport { type UnsignedEvent, type Event } from './pure.ts'\nimport { sha256 } from '@noble/hashes/sha256'\n\nimport { utf8Encoder } from './utils.ts'\n\n/** Get POW difficulty from a Nostr hex ID. */\nexport function getPow(hex: string): number {\n  let count = 0\n\n  for (let i = 0; i < 64; i += 8) {\n    const nibble = parseInt(hex.substring(i, i + 8), 16)\n    if (nibble === 0) {\n      count += 32\n    } else {\n      count += Math.clz32(nibble)\n      break\n    }\n  }\n\n  return count\n}\n\n/**\n * Mine an event with the desired POW. This function mutates the event.\n * Note that this operation is synchronous and should be run in a worker context to avoid blocking the main thread.\n */\nexport function minePow(unsigned: UnsignedEvent, difficulty: number): Omit<Event, 'sig'> {\n  let count = 0\n\n  const event = unsigned as Omit<Event, 'sig'>\n  const tag = ['nonce', count.toString(), difficulty.toString()]\n\n  event.tags.push(tag)\n\n  while (true) {\n    const now = Math.floor(new Date().getTime() / 1000)\n\n    if (now !== event.created_at) {\n      count = 0\n      event.created_at = now\n    }\n\n    tag[1] = (++count).toString()\n\n    event.id = fastEventHash(event)\n\n    if (getPow(event.id) >= difficulty) {\n      break\n    }\n  }\n\n  return event\n}\n\nexport function fastEventHash(evt: UnsignedEvent): string {\n  return bytesToHex(\n    sha256(utf8Encoder.encode(JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]))),\n  )\n}\n","import { PrivateDirectMessage } from './kinds.ts'\nimport { EventTemplate, NostrEvent, getPublicKey } from './pure.ts'\nimport * as nip59 from './nip59.ts'\n\ntype Recipient = {\n  publicKey: string\n  relayUrl?: string\n}\n\ntype ReplyTo = {\n  eventId: string\n  relayUrl?: string\n}\n\nfunction createEvent(\n  recipients: Recipient | Recipient[],\n  message: string,\n  conversationTitle?: string,\n  replyTo?: ReplyTo,\n): EventTemplate {\n  const baseEvent: EventTemplate = {\n    created_at: Math.ceil(Date.now() / 1000),\n    kind: PrivateDirectMessage,\n    tags: [],\n    content: message,\n  }\n\n  const recipientsArray = Array.isArray(recipients) ? recipients : [recipients]\n\n  recipientsArray.forEach(({ publicKey, relayUrl }) => {\n    baseEvent.tags.push(relayUrl ? ['p', publicKey, relayUrl] : ['p', publicKey])\n  })\n\n  if (replyTo) {\n    baseEvent.tags.push(['e', replyTo.eventId, replyTo.relayUrl || '', 'reply'])\n  }\n\n  if (conversationTitle) {\n    baseEvent.tags.push(['subject', conversationTitle])\n  }\n\n  return baseEvent\n}\n\nexport function wrapEvent(\n  senderPrivateKey: Uint8Array,\n  recipient: Recipient,\n  message: string,\n  conversationTitle?: string,\n  replyTo?: ReplyTo,\n): NostrEvent {\n  const event = createEvent(recipient, message, conversationTitle, replyTo)\n  return nip59.wrapEvent(event, senderPrivateKey, recipient.publicKey)\n}\n\nexport function wrapManyEvents(\n  senderPrivateKey: Uint8Array,\n  recipients: Recipient[],\n  message: string,\n  conversationTitle?: string,\n  replyTo?: ReplyTo,\n): NostrEvent[] {\n  if (!recipients || recipients.length === 0) {\n    throw new Error('At least one recipient is required.')\n  }\n\n  const senderPublicKey = getPublicKey(senderPrivateKey)\n\n  // wrap the event for the sender and then for each recipient\n  return [{ publicKey: senderPublicKey }, ...recipients].map(recipient =>\n    wrapEvent(senderPrivateKey, recipient, message, conversationTitle, replyTo),\n  )\n}\n\nexport const unwrapEvent = nip59.unwrapEvent\n\nexport const unwrapManyEvents = nip59.unwrapManyEvents\n","import { EventTemplate, UnsignedEvent, NostrEvent } from './core.ts'\nimport { getConversationKey, decrypt, encrypt } from './nip44.ts'\nimport { getEventHash, generateSecretKey, finalizeEvent, getPublicKey } from './pure.ts'\nimport { Seal, GiftWrap } from './kinds.ts'\n\ntype Rumor = UnsignedEvent & { id: string }\n\nconst TWO_DAYS = 2 * 24 * 60 * 60\n\nconst now = () => Math.round(Date.now() / 1000)\nconst randomNow = () => Math.round(now() - Math.random() * TWO_DAYS)\n\nconst nip44ConversationKey = (privateKey: Uint8Array, publicKey: string) => getConversationKey(privateKey, publicKey)\n\nconst nip44Encrypt = (data: EventTemplate, privateKey: Uint8Array, publicKey: string) =>\n  encrypt(JSON.stringify(data), nip44ConversationKey(privateKey, publicKey))\n\nconst nip44Decrypt = (data: NostrEvent, privateKey: Uint8Array) =>\n  JSON.parse(decrypt(data.content, nip44ConversationKey(privateKey, data.pubkey)))\n\nexport function createRumor(event: Partial<UnsignedEvent>, privateKey: Uint8Array): Rumor {\n  const rumor = {\n    created_at: now(),\n    content: '',\n    tags: [],\n    ...event,\n    pubkey: getPublicKey(privateKey),\n  } as any\n\n  rumor.id = getEventHash(rumor)\n\n  return rumor as Rumor\n}\n\nexport function createSeal(rumor: Rumor, privateKey: Uint8Array, recipientPublicKey: string): NostrEvent {\n  return finalizeEvent(\n    {\n      kind: Seal,\n      content: nip44Encrypt(rumor, privateKey, recipientPublicKey),\n      created_at: randomNow(),\n      tags: [],\n    },\n    privateKey,\n  )\n}\n\nexport function createWrap(seal: NostrEvent, recipientPublicKey: string): NostrEvent {\n  const randomKey = generateSecretKey()\n\n  return finalizeEvent(\n    {\n      kind: GiftWrap,\n      content: nip44Encrypt(seal, randomKey, recipientPublicKey),\n      created_at: randomNow(),\n      tags: [['p', recipientPublicKey]],\n    },\n    randomKey,\n  ) as NostrEvent\n}\n\nexport function wrapEvent(\n  event: Partial<UnsignedEvent>,\n  senderPrivateKey: Uint8Array,\n  recipientPublicKey: string,\n): NostrEvent {\n  const rumor = createRumor(event, senderPrivateKey)\n\n  const seal = createSeal(rumor, senderPrivateKey, recipientPublicKey)\n  return createWrap(seal, recipientPublicKey)\n}\n\nexport function wrapManyEvents(\n  event: Partial<UnsignedEvent>,\n  senderPrivateKey: Uint8Array,\n  recipientsPublicKeys: string[],\n): NostrEvent[] {\n  if (!recipientsPublicKeys || recipientsPublicKeys.length === 0) {\n    throw new Error('At least one recipient is required.')\n  }\n\n  const senderPublicKey = getPublicKey(senderPrivateKey)\n\n  const wrappeds = [wrapEvent(event, senderPrivateKey, senderPublicKey)]\n\n  recipientsPublicKeys.forEach(recipientPublicKey => {\n    wrappeds.push(wrapEvent(event, senderPrivateKey, recipientPublicKey))\n  })\n\n  return wrappeds\n}\n\nexport function unwrapEvent(wrap: NostrEvent, recipientPrivateKey: Uint8Array): Rumor {\n  const unwrappedSeal = nip44Decrypt(wrap, recipientPrivateKey)\n  return nip44Decrypt(unwrappedSeal, recipientPrivateKey)\n}\n\nexport function unwrapManyEvents(wrappedEvents: NostrEvent[], recipientPrivateKey: Uint8Array): Rumor[] {\n  let unwrappedEvents: Rumor[] = []\n\n  wrappedEvents.forEach(e => {\n    unwrappedEvents.push(unwrapEvent(e, recipientPrivateKey))\n  })\n\n  unwrappedEvents.sort((a, b) => a.created_at - b.created_at)\n\n  return unwrappedEvents\n}\n","import { chacha20 } from '@noble/ciphers/chacha'\nimport { equalBytes } from '@noble/ciphers/utils'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { extract as hkdf_extract, expand as hkdf_expand } from '@noble/hashes/hkdf'\nimport { hmac } from '@noble/hashes/hmac'\nimport { sha256 } from '@noble/hashes/sha256'\nimport { concatBytes, randomBytes } from '@noble/hashes/utils'\nimport { base64 } from '@scure/base'\n\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nconst minPlaintextSize = 0x0001 // 1b msg => padded to 32b\nconst maxPlaintextSize = 0xffff // 65535 (64kb-1) => padded to 64kb\n\nexport function getConversationKey(privkeyA: Uint8Array, pubkeyB: string): Uint8Array {\n  const sharedX = secp256k1.getSharedSecret(privkeyA, '02' + pubkeyB).subarray(1, 33)\n  return hkdf_extract(sha256, sharedX, 'nip44-v2')\n}\n\nfunction getMessageKeys(\n  conversationKey: Uint8Array,\n  nonce: Uint8Array,\n): { chacha_key: Uint8Array; chacha_nonce: Uint8Array; hmac_key: Uint8Array } {\n  const keys = hkdf_expand(sha256, conversationKey, nonce, 76)\n  return {\n    chacha_key: keys.subarray(0, 32),\n    chacha_nonce: keys.subarray(32, 44),\n    hmac_key: keys.subarray(44, 76),\n  }\n}\n\nfunction calcPaddedLen(len: number): number {\n  if (!Number.isSafeInteger(len) || len < 1) throw new Error('expected positive integer')\n  if (len <= 32) return 32\n  const nextPower = 1 << (Math.floor(Math.log2(len - 1)) + 1)\n  const chunk = nextPower <= 256 ? 32 : nextPower / 8\n  return chunk * (Math.floor((len - 1) / chunk) + 1)\n}\n\nfunction writeU16BE(num: number): Uint8Array {\n  if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize)\n    throw new Error('invalid plaintext size: must be between 1 and 65535 bytes')\n  const arr = new Uint8Array(2)\n  new DataView(arr.buffer).setUint16(0, num, false)\n  return arr\n}\n\nfunction pad(plaintext: string): Uint8Array {\n  const unpadded = utf8Encoder.encode(plaintext)\n  const unpaddedLen = unpadded.length\n  const prefix = writeU16BE(unpaddedLen)\n  const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen)\n  return concatBytes(prefix, unpadded, suffix)\n}\n\nfunction unpad(padded: Uint8Array): string {\n  const unpaddedLen = new DataView(padded.buffer).getUint16(0)\n  const unpadded = padded.subarray(2, 2 + unpaddedLen)\n  if (\n    unpaddedLen < minPlaintextSize ||\n    unpaddedLen > maxPlaintextSize ||\n    unpadded.length !== unpaddedLen ||\n    padded.length !== 2 + calcPaddedLen(unpaddedLen)\n  )\n    throw new Error('invalid padding')\n  return utf8Decoder.decode(unpadded)\n}\n\nfunction hmacAad(key: Uint8Array, message: Uint8Array, aad: Uint8Array): Uint8Array {\n  if (aad.length !== 32) throw new Error('AAD associated data must be 32 bytes')\n  const combined = concatBytes(aad, message)\n  return hmac(sha256, key, combined)\n}\n\n// metadata: always 65b (version: 1b, nonce: 32b, max: 32b)\n// plaintext: 1b to 0xffff\n// padded plaintext: 32b to 0xffff\n// ciphertext: 32b+2 to 0xffff+2\n// raw payload: 99 (65+32+2) to 65603 (65+0xffff+2)\n// compressed payload (base64): 132b to 87472b\nfunction decodePayload(payload: string): { nonce: Uint8Array; ciphertext: Uint8Array; mac: Uint8Array } {\n  if (typeof payload !== 'string') throw new Error('payload must be a valid string')\n  const plen = payload.length\n  if (plen < 132 || plen > 87472) throw new Error('invalid payload length: ' + plen)\n  if (payload[0] === '#') throw new Error('unknown encryption version')\n  let data: Uint8Array\n  try {\n    data = base64.decode(payload)\n  } catch (error) {\n    throw new Error('invalid base64: ' + (error as any).message)\n  }\n  const dlen = data.length\n  if (dlen < 99 || dlen > 65603) throw new Error('invalid data length: ' + dlen)\n  const vers = data[0]\n  if (vers !== 2) throw new Error('unknown encryption version ' + vers)\n  return {\n    nonce: data.subarray(1, 33),\n    ciphertext: data.subarray(33, -32),\n    mac: data.subarray(-32),\n  }\n}\n\nexport function encrypt(plaintext: string, conversationKey: Uint8Array, nonce: Uint8Array = randomBytes(32)): string {\n  const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n  const padded = pad(plaintext)\n  const ciphertext = chacha20(chacha_key, chacha_nonce, padded)\n  const mac = hmacAad(hmac_key, ciphertext, nonce)\n  return base64.encode(concatBytes(new Uint8Array([2]), nonce, ciphertext, mac))\n}\n\nexport function decrypt(payload: string, conversationKey: Uint8Array): string {\n  const { nonce, ciphertext, mac } = decodePayload(payload)\n  const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)\n  const calculatedMac = hmacAad(hmac_key, ciphertext, nonce)\n  if (!equalBytes(calculatedMac, mac)) throw new Error('invalid MAC')\n  const padded = chacha20(chacha_key, chacha_nonce, ciphertext)\n  return unpad(padded)\n}\n\nexport const v2 = {\n  utils: {\n    getConversationKey,\n    calcPaddedLen,\n  },\n  encrypt,\n  decrypt,\n}\n","import { exists as aexists, bytes as abytes, output as aoutput } from './_assert.js';\nimport { Input, toBytes, Hash } from './utils.js';\n\n// Poly1305 is a fast and parallel secret-key message-authentication code.\n// https://cr.yp.to/mac.html, https://cr.yp.to/mac/poly1305-20050329.pdf\n// https://datatracker.ietf.org/doc/html/rfc8439\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  }\n  update(data: Input): this {\n    aexists(this);\n    const { buffer, blockLen } = this;\n    data = toBytes(data);\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    this.h.fill(0);\n    this.r.fill(0);\n    this.buffer.fill(0);\n    this.pad.fill(0);\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      // buffer.subarray(pos).fill(0);\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>>(hashCons: (key: Input) => Hash<H>) {\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\nexport const poly1305 = wrapConstructorWithKey((key) => new Poly1305(key));\n","// Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.\nimport { number as anumber, bytes as abytes, bool as abool } from './_assert.js';\nimport { XorStream, checkOpts, u32, utf8ToBytes } from './utils.js';\n\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\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\nexport type CipherCoreFn = (\n  sigma: Uint32Array,\n  key: Uint32Array,\n  nonce: Uint32Array,\n  output: Uint32Array,\n  counter: number,\n  rounds?: number\n) => void;\n\nexport type ExtendNonceFn = (\n  sigma: Uint32Array,\n  key: Uint32Array,\n  input: Uint32Array,\n  output: Uint32Array\n) => void;\n\nexport type CipherOpts = {\n  allowShortKeys?: boolean; // Original salsa / chacha allow 16-byte keys\n  extendNonceFn?: ExtendNonceFn;\n  counterLength?: number;\n  counterRight?: boolean; // right: nonce|counter; left: counter|nonce\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\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) 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      k: Uint8Array,\n      sigma: Uint32Array;\n    if (l === 32) {\n      k = key.slice();\n      toClean.push(k);\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)) {\n      nonce = nonce.slice();\n      toClean.push(nonce);\n    }\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    while (toClean.length > 0) toClean.pop()!.fill(0);\n    return output;\n  };\n}\n","// prettier-ignore\nimport {\n  wrapCipher, CipherWithOutput, XorStream, createView, equalBytes, setBigUint64,\n} from './utils.js';\nimport { poly1305 } from './_poly1305.js';\nimport { createCipher, rotl } from './_arx.js';\nimport { bytes as abytes } from './_assert.js';\n\n// ChaCha20 stream cipher was released in 2008. ChaCha aims to increase\n// the diffusion per round, but had slightly less cryptanalysis.\n// https://cr.yp.to/chacha.html, http://cr.yp.to/chacha/chacha-20080128.pdf\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) {\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 = /* @__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 = /* @__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 = /* @__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 = /* @__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 = /* @__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 = new Uint8Array(16);\n  const view = createView(num);\n  setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n  setBigUint64(view, 8, BigInt(data.length), true);\n  h.update(num);\n  const res = h.digest();\n  authKey.fill(0);\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    abytes(key, 32);\n    abytes(nonce);\n    return {\n      encrypt: (plaintext: Uint8Array, output?: Uint8Array) => {\n        const plength = plaintext.length;\n        const clength = plength + tagLength;\n        if (output) {\n          abytes(output, clength);\n        } else {\n          output = new Uint8Array(clength);\n        }\n        xorStream(key, nonce, plaintext, output, 1);\n        const tag = computeTag(xorStream, key, nonce, output.subarray(0, -tagLength), AAD);\n        output.set(tag, plength); // append tag\n        return output;\n      },\n      decrypt: (ciphertext: Uint8Array, output?: Uint8Array) => {\n        const clength = ciphertext.length;\n        const plength = clength - tagLength;\n        if (clength < tagLength)\n          throw new Error(`encrypted data must be at least ${tagLength} bytes`);\n        if (output) {\n          abytes(output, plength);\n        } else {\n          output = new Uint8Array(plength);\n        }\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        xorStream(key, nonce, data, output, 1);\n        return output;\n      },\n    };\n  };\n\n/**\n * ChaCha20-Poly1305 from RFC 8439.\n * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.\n */\nexport const chacha20poly1305 = /* @__PURE__ */ wrapCipher(\n  { blockSize: 64, nonceLength: 12, tagLength: 16 },\n  _poly1305_aead(chacha20)\n);\n/**\n * XChaCha20-Poly1305 extended-nonce chacha.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha\n * With 24-byte nonce, it's safe to use fill it with random (CSPRNG).\n */\nexport const xchacha20poly1305 = /* @__PURE__ */ wrapCipher(\n  { blockSize: 64, nonceLength: 24, tagLength: 16 },\n  _poly1305_aead(xchacha20)\n);\n","import assert 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    assert.hash(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    assert.exists(this);\n    this.iHash.update(buf);\n    return this;\n  }\n  digestInto(out: Uint8Array) {\n    assert.exists(this);\n    assert.bytes(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 assert 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  assert.hash(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 = new Uint8Array([0]);\nconst EMPTY_BUFFER = 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  assert.hash(hash);\n  assert.number(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","import { GenericRepost, Repost, ShortTextNote } from './kinds.ts'\nimport { EventPointer } from './nip19.ts'\nimport { Event, finalizeEvent, verifyEvent } from './pure.ts'\n\nexport type RepostEventTemplate = {\n  /**\n   * Pass only non-nip18 tags if you have to.\n   * Nip18 tags ('e' and 'p' tags pointing to the reposted event) will be added automatically.\n   */\n  tags?: string[][]\n\n  /**\n   * Pass an empty string to NOT include the stringified JSON of the reposted event.\n   * Any other content will be ignored and replaced with the stringified JSON of the reposted event.\n   * @default Stringified JSON of the reposted event\n   */\n  content?: ''\n\n  created_at: number\n}\n\nexport function finishRepostEvent(\n  t: RepostEventTemplate,\n  reposted: Event,\n  relayUrl: string,\n  privateKey: Uint8Array,\n): Event {\n  let kind: Repost | GenericRepost\n  const tags = [...(t.tags ?? []), ['e', reposted.id, relayUrl], ['p', reposted.pubkey]]\n  if (reposted.kind === ShortTextNote) {\n    kind = Repost\n  } else {\n    kind = GenericRepost\n    tags.push(['k', String(reposted.kind)])\n  }\n\n  return finalizeEvent(\n    {\n      kind,\n      tags,\n      content: t.content === '' || reposted.tags?.find(tag => tag[0] === '-') ? '' : JSON.stringify(reposted),\n      created_at: t.created_at,\n    },\n    privateKey,\n  )\n}\n\nexport function getRepostedEventPointer(event: Event): undefined | EventPointer {\n  if (![Repost, GenericRepost].includes(event.kind)) {\n    return undefined\n  }\n\n  let lastETag: undefined | string[]\n  let lastPTag: undefined | string[]\n\n  for (let i = event.tags.length - 1; i >= 0 && (lastETag === undefined || lastPTag === undefined); i--) {\n    const tag = event.tags[i]\n    if (tag.length >= 2) {\n      if (tag[0] === 'e' && lastETag === undefined) {\n        lastETag = tag\n      } else if (tag[0] === 'p' && lastPTag === undefined) {\n        lastPTag = tag\n      }\n    }\n  }\n\n  if (lastETag === undefined) {\n    return undefined\n  }\n\n  return {\n    id: lastETag[1],\n    relays: [lastETag[2], lastPTag?.[2]].filter((x): x is string => typeof x === 'string'),\n    author: lastPTag?.[1],\n  }\n}\n\nexport type GetRepostedEventOptions = {\n  skipVerification?: boolean\n}\n\nexport function getRepostedEvent(event: Event, { skipVerification }: GetRepostedEventOptions = {}): undefined | Event {\n  const pointer = getRepostedEventPointer(event)\n\n  if (pointer === undefined || event.content === '') {\n    return undefined\n  }\n\n  let repostedEvent: undefined | Event\n\n  try {\n    repostedEvent = JSON.parse(event.content) as Event\n  } catch (error) {\n    return undefined\n  }\n\n  if (repostedEvent.id !== pointer.id) {\n    return undefined\n  }\n\n  if (!skipVerification && !verifyEvent(repostedEvent)) {\n    return undefined\n  }\n\n  return repostedEvent\n}\n","import { AddressPointer, BECH32_REGEX, decode, EventPointer, ProfilePointer } from './nip19.ts'\n\n/** Nostr URI regex, eg `nostr:npub1...` */\nexport const NOSTR_URI_REGEX: RegExp = new RegExp(`nostr:(${BECH32_REGEX.source})`)\n\n/** Test whether the value is a Nostr URI. */\nexport function test(value: unknown): value is `nostr:${string}` {\n  return typeof value === 'string' && new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(value)\n}\n\n/** Parsed Nostr URI data. */\nexport interface NostrURI {\n  /** Full URI including the `nostr:` protocol. */\n  uri: `nostr:${string}`\n  /** The bech32-encoded data (eg `npub1...`). */\n  value: string\n  /** Decoded bech32 string, according to NIP-19. */\n  decoded:\n    | {\n        type: 'nevent'\n        data: EventPointer\n      }\n    | {\n        type: 'nprofile'\n        data: ProfilePointer\n      }\n    | {\n        type: 'naddr'\n        data: AddressPointer\n      }\n    | {\n        type: 'npub'\n        data: string\n      }\n    | {\n        type: 'nsec'\n        data: Uint8Array\n      }\n    | {\n        type: 'note'\n        data: string\n      }\n}\n\n/** Parse and decode a Nostr URI. */\nexport function parse(uri: string): NostrURI {\n  const match = uri.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`))\n  if (!match) throw new Error(`Invalid Nostr URI: ${uri}`)\n  return {\n    uri: match[0] as `nostr:${string}`,\n    value: match[1],\n    decoded: decode(match[1]),\n  }\n}\n","import { Event, finalizeEvent } from './pure.ts'\nimport { Reaction } from './kinds.ts'\n\nimport type { EventPointer } from './nip19.ts'\n\nexport type ReactionEventTemplate = {\n  /**\n   * Pass only non-nip25 tags if you have to. Nip25 tags ('e' and 'p' tags from reacted event) will be added automatically.\n   */\n  tags?: string[][]\n\n  /**\n   * @default '+'\n   */\n  content?: string\n\n  created_at: number\n}\n\nexport function finishReactionEvent(t: ReactionEventTemplate, reacted: Event, privateKey: Uint8Array): Event {\n  const inheritedTags = reacted.tags.filter(tag => tag.length >= 2 && (tag[0] === 'e' || tag[0] === 'p'))\n\n  return finalizeEvent(\n    {\n      ...t,\n      kind: Reaction,\n      tags: [...(t.tags ?? []), ...inheritedTags, ['e', reacted.id], ['p', reacted.pubkey]],\n      content: t.content ?? '+',\n    },\n    privateKey,\n  )\n}\n\nexport function getReactedEventPointer(event: Event): undefined | EventPointer {\n  if (event.kind !== Reaction) {\n    return undefined\n  }\n\n  let lastETag: undefined | string[]\n  let lastPTag: undefined | string[]\n\n  for (let i = event.tags.length - 1; i >= 0 && (lastETag === undefined || lastPTag === undefined); i--) {\n    const tag = event.tags[i]\n    if (tag.length >= 2) {\n      if (tag[0] === 'e' && lastETag === undefined) {\n        lastETag = tag\n      } else if (tag[0] === 'p' && lastPTag === undefined) {\n        lastPTag = tag\n      }\n    }\n  }\n\n  if (lastETag === undefined || lastPTag === undefined) {\n    return undefined\n  }\n\n  return {\n    id: lastETag[1],\n    relays: [lastETag[2], lastPTag[2]].filter(x => x !== undefined),\n    author: lastPTag[1],\n  }\n}\n","import { AddressPointer, EventPointer, ProfilePointer, decode } from './nip19.ts'\n\nexport type Block =\n  | {\n      type: 'text'\n      text: string\n    }\n  | {\n      type: 'reference'\n      pointer: ProfilePointer | AddressPointer | EventPointer\n    }\n  | {\n      type: 'url'\n      url: string\n    }\n  | {\n      type: 'relay'\n      url: string\n    }\n  | {\n      type: 'image'\n      url: string\n    }\n  | {\n      type: 'video'\n      url: string\n    }\n  | {\n      type: 'audio'\n      url: string\n    }\n\nconst noCharacter = /\\W/m\nconst noURLCharacter = /\\W |\\W$|$|,| /m\n\nexport function* parse(content: string): Iterable<Block> {\n  const max = content.length\n  let prevIndex = 0\n  let index = 0\n  while (index < max) {\n    let u = content.indexOf(':', index)\n    if (u === -1) {\n      // reached end\n      break\n    }\n\n    if (content.substring(u - 5, u) === 'nostr') {\n      const m = content.substring(u + 60).match(noCharacter)\n      const end = m ? u + 60 + m.index! : max\n      try {\n        let pointer: ProfilePointer | AddressPointer | EventPointer\n        let { data, type } = decode(content.substring(u + 1, end))\n\n        switch (type) {\n          case 'npub':\n            pointer = { pubkey: data } as ProfilePointer\n            break\n          case 'nsec':\n          case 'note':\n            // ignore this, treat it as not a valid uri\n            index = end + 1\n            continue\n          default:\n            pointer = data as any\n        }\n\n        if (prevIndex !== u - 5) {\n          yield { type: 'text', text: content.substring(prevIndex, u - 5) }\n        }\n        yield { type: 'reference', pointer }\n        index = end\n        prevIndex = index\n        continue\n      } catch (_err) {\n        // ignore this, not a valid nostr uri\n        index = u + 1\n        continue\n      }\n    } else if (content.substring(u - 5, u) === 'https' || content.substring(u - 4, u) === 'http') {\n      const m = content.substring(u + 4).match(noURLCharacter)\n      const end = m ? u + 4 + m.index! : max\n      const prefixLen = content[u - 1] === 's' ? 5 : 4\n      try {\n        let url = new URL(content.substring(u - prefixLen, end))\n        if (url.hostname.indexOf('.') === -1) {\n          throw new Error('invalid url')\n        }\n\n        if (prevIndex !== u - prefixLen) {\n          yield { type: 'text', text: content.substring(prevIndex, u - prefixLen) }\n        }\n\n        if (/\\.(png|jpe?g|gif|webp)$/i.test(url.pathname)) {\n          yield { type: 'image', url: url.toString() }\n          index = end\n          prevIndex = index\n          continue\n        }\n        if (/\\.(mp4|avi|webm|mkv)$/i.test(url.pathname)) {\n          yield { type: 'video', url: url.toString() }\n          index = end\n          prevIndex = index\n          continue\n        }\n        if (/\\.(mp3|aac|ogg|opus)$/i.test(url.pathname)) {\n          yield { type: 'audio', url: url.toString() }\n          index = end\n          prevIndex = index\n          continue\n        }\n\n        yield { type: 'url', url: url.toString() }\n        index = end\n        prevIndex = index\n        continue\n      } catch (_err) {\n        // ignore this, not a valid url\n        index = end + 1\n        continue\n      }\n    } else if (content.substring(u - 3, u) === 'wss' || content.substring(u - 2, u) === 'ws') {\n      const m = content.substring(u + 4).match(noURLCharacter)\n      const end = m ? u + 4 + m.index! : max\n      const prefixLen = content[u - 1] === 's' ? 3 : 2\n      try {\n        let url = new URL(content.substring(u - prefixLen, end))\n        if (url.hostname.indexOf('.') === -1) {\n          throw new Error('invalid ws url')\n        }\n\n        if (prevIndex !== u - prefixLen) {\n          yield { type: 'text', text: content.substring(prevIndex, u - prefixLen) }\n        }\n        yield { type: 'relay', url: url.toString() }\n        index = end\n        prevIndex = index\n        continue\n      } catch (_err) {\n        // ignore this, not a valid url\n        index = end + 1\n        continue\n      }\n    } else {\n      // ignore this, it is nothing\n      index = u + 1\n      continue\n    }\n  }\n\n  if (prevIndex !== max) {\n    yield { type: 'text', text: content.substring(prevIndex) }\n  }\n}\n","import { Event, finalizeEvent } from './pure.ts'\nimport {\n  ChannelCreation,\n  ChannelHideMessage,\n  ChannelMessage,\n  ChannelMetadata as KindChannelMetadata,\n  ChannelMuteUser,\n} from './kinds.ts'\n\nexport interface ChannelMetadata {\n  name: string\n  about: string\n  picture: string\n}\n\nexport interface ChannelCreateEventTemplate {\n  /* JSON string containing ChannelMetadata as defined for Kind 40 and 41 in nip-28. */\n  content: string | ChannelMetadata\n  created_at: number\n  tags?: string[][]\n}\n\nexport interface ChannelMetadataEventTemplate {\n  channel_create_event_id: string\n  /* JSON string containing ChannelMetadata as defined for Kind 40 and 41 in nip-28. */\n  content: string | ChannelMetadata\n  created_at: number\n  tags?: string[][]\n}\n\nexport interface ChannelMessageEventTemplate {\n  channel_create_event_id: string\n  reply_to_channel_message_event_id?: string\n  relay_url: string\n  content: string\n  created_at: number\n  tags?: string[][]\n}\n\nexport interface ChannelHideMessageEventTemplate {\n  channel_message_event_id: string\n  content: string | { reason: string }\n  created_at: number\n  tags?: string[][]\n}\n\nexport interface ChannelMuteUserEventTemplate {\n  content: string | { reason: string }\n  created_at: number\n  pubkey_to_mute: string\n  tags?: string[][]\n}\n\nexport const channelCreateEvent = (t: ChannelCreateEventTemplate, privateKey: Uint8Array): Event | undefined => {\n  let content: string\n  if (typeof t.content === 'object') {\n    content = JSON.stringify(t.content)\n  } else if (typeof t.content === 'string') {\n    content = t.content\n  } else {\n    return undefined\n  }\n\n  return finalizeEvent(\n    {\n      kind: ChannelCreation,\n      tags: [...(t.tags ?? [])],\n      content: content,\n      created_at: t.created_at,\n    },\n    privateKey,\n  )\n}\n\nexport const channelMetadataEvent = (t: ChannelMetadataEventTemplate, privateKey: Uint8Array): Event | undefined => {\n  let content: string\n  if (typeof t.content === 'object') {\n    content = JSON.stringify(t.content)\n  } else if (typeof t.content === 'string') {\n    content = t.content\n  } else {\n    return undefined\n  }\n\n  return finalizeEvent(\n    {\n      kind: KindChannelMetadata,\n      tags: [['e', t.channel_create_event_id], ...(t.tags ?? [])],\n      content: content,\n      created_at: t.created_at,\n    },\n    privateKey,\n  )\n}\n\nexport const channelMessageEvent = (t: ChannelMessageEventTemplate, privateKey: Uint8Array): Event => {\n  const tags = [['e', t.channel_create_event_id, t.relay_url, 'root']]\n\n  if (t.reply_to_channel_message_event_id) {\n    tags.push(['e', t.reply_to_channel_message_event_id, t.relay_url, 'reply'])\n  }\n\n  return finalizeEvent(\n    {\n      kind: ChannelMessage,\n      tags: [...tags, ...(t.tags ?? [])],\n      content: t.content,\n      created_at: t.created_at,\n    },\n    privateKey,\n  )\n}\n\n/* \"e\" tag should be the kind 42 event to hide */\nexport const channelHideMessageEvent = (\n  t: ChannelHideMessageEventTemplate,\n  privateKey: Uint8Array,\n): Event | undefined => {\n  let content: string\n  if (typeof t.content === 'object') {\n    content = JSON.stringify(t.content)\n  } else if (typeof t.content === 'string') {\n    content = t.content\n  } else {\n    return undefined\n  }\n\n  return finalizeEvent(\n    {\n      kind: ChannelHideMessage,\n      tags: [['e', t.channel_message_event_id], ...(t.tags ?? [])],\n      content: content,\n      created_at: t.created_at,\n    },\n    privateKey,\n  )\n}\n\nexport const channelMuteUserEvent = (t: ChannelMuteUserEventTemplate, privateKey: Uint8Array): Event | undefined => {\n  let content: string\n  if (typeof t.content === 'object') {\n    content = JSON.stringify(t.content)\n  } else if (typeof t.content === 'string') {\n    content = t.content\n  } else {\n    return undefined\n  }\n\n  return finalizeEvent(\n    {\n      kind: ChannelMuteUser,\n      tags: [['p', t.pubkey_to_mute], ...(t.tags ?? [])],\n      content: content,\n      created_at: t.created_at,\n    },\n    privateKey,\n  )\n}\n","/** Regex for a single emoji shortcode. */\nexport const EMOJI_SHORTCODE_REGEX = /:(\\w+):/\n\n/** Regex to find emoji shortcodes in content. */\nexport const regex = (): RegExp => new RegExp(`\\\\B${EMOJI_SHORTCODE_REGEX.source}\\\\B`, 'g')\n\n/** Represents a Nostr custom emoji. */\nexport interface CustomEmoji {\n  /** The matched emoji name with colons. */\n  shortcode: `:${string}:`\n  /** The matched emoji name without colons. */\n  name: string\n}\n\n/** Match result for a custom emoji in text content. */\nexport interface CustomEmojiMatch extends CustomEmoji {\n  /** Index where the emoji begins in the text content. */\n  start: number\n  /** Index where the emoji ends in the text content. */\n  end: number\n}\n\n/** Find all custom emoji shortcodes. */\nexport function* matchAll(content: string): Iterable<CustomEmojiMatch> {\n  const matches = content.matchAll(regex())\n\n  for (const match of matches) {\n    try {\n      const [shortcode, name] = match\n\n      yield {\n        shortcode: shortcode as `:${string}:`,\n        name,\n        start: match.index!,\n        end: match.index! + shortcode.length,\n      }\n    } catch (_e) {\n      // do nothing\n    }\n  }\n}\n\n/** Replace all emoji shortcodes in the content. */\nexport function replaceAll(content: string, replacer: (match: CustomEmoji) => string): string {\n  return content.replaceAll(regex(), (shortcode, name) => {\n    return replacer({\n      shortcode: shortcode as `:${string}:`,\n      name,\n    })\n  })\n}\n","var _fetch: any\n\ntry {\n  _fetch = fetch\n} catch {}\n\nexport function useFetchImplementation(fetchImplementation: any) {\n  _fetch = fetchImplementation\n}\n\nexport async function validateGithub(pubkey: string, username: string, proof: string): Promise<boolean> {\n  try {\n    let res = await (await _fetch(`https://gist.github.com/${username}/${proof}/raw`)).text()\n    return res === `Verifying that I control the following Nostr public key: ${pubkey}`\n  } catch (_) {\n    return false\n  }\n}\n","import { type VerifiedEvent, finalizeEvent } from './pure.ts'\nimport { NWCWalletRequest } from './kinds.ts'\nimport { encrypt } from './nip04.ts'\n\ninterface NWCConnection {\n  pubkey: string\n  relay: string\n  secret: string\n}\n\nexport function parseConnectionString(connectionString: string): NWCConnection {\n  const { host, pathname, searchParams } = new URL(connectionString)\n  const pubkey = pathname || host\n  const relay = searchParams.get('relay')\n  const secret = searchParams.get('secret')\n\n  if (!pubkey || !relay || !secret) {\n    throw new Error('invalid connection string')\n  }\n\n  return { pubkey, relay, secret }\n}\n\nexport async function makeNwcRequestEvent(\n  pubkey: string,\n  secretKey: Uint8Array,\n  invoice: string,\n): Promise<VerifiedEvent> {\n  const content = {\n    method: 'pay_invoice',\n    params: {\n      invoice,\n    },\n  }\n  const encryptedContent = encrypt(secretKey, pubkey, JSON.stringify(content))\n  const eventTemplate = {\n    kind: NWCWalletRequest,\n    created_at: Math.round(Date.now() / 1000),\n    content: encryptedContent,\n    tags: [['p', pubkey]],\n  }\n\n  return finalizeEvent(eventTemplate, secretKey)\n}\n","export function normalizeIdentifier(name: string): string {\n  // Trim and lowercase\n  name = name.trim().toLowerCase()\n\n  // Normalize Unicode to NFKC form\n  name = name.normalize('NFKC')\n\n  // Convert to array of characters and map each one\n  return Array.from(name)\n    .map(char => {\n      // Check if character is letter or number using Unicode ranges\n      if (/\\p{Letter}/u.test(char) || /\\p{Number}/u.test(char)) {\n        return char\n      }\n\n      return '-'\n    })\n    .join('')\n}\n","import { bech32 } from '@scure/base'\n\nimport { NostrEvent, validateEvent, verifyEvent, type Event, type EventTemplate } from './pure.ts'\nimport { utf8Decoder } from './utils.ts'\nimport { isReplaceableKind, isAddressableKind } from './kinds.ts'\n\nvar _fetch: any\n\ntry {\n  _fetch = fetch\n} catch {}\n\nexport function useFetchImplementation(fetchImplementation: any) {\n  _fetch = fetchImplementation\n}\n\nexport async function getZapEndpoint(metadata: Event): Promise<null | string> {\n  try {\n    let lnurl: string = ''\n    let { lud06, lud16 } = JSON.parse(metadata.content)\n    if (lud06) {\n      let { words } = bech32.decode(lud06, 1000)\n      let data = bech32.fromWords(words)\n      lnurl = utf8Decoder.decode(data)\n    } else if (lud16) {\n      let [name, domain] = lud16.split('@')\n      lnurl = new URL(`/.well-known/lnurlp/${name}`, `https://${domain}`).toString()\n    } else {\n      return null\n    }\n\n    let res = await _fetch(lnurl)\n    let body = await res.json()\n\n    if (body.allowsNostr && body.nostrPubkey) {\n      return body.callback\n    }\n  } catch (err) {\n    /*-*/\n  }\n\n  return null\n}\n\ntype ProfileZap = {\n  pubkey: string\n  amount: number\n  comment?: string\n  relays: string[]\n}\n\ntype EventZap = {\n  event: NostrEvent\n  amount: number\n  comment?: string\n  relays: string[]\n}\n\nexport function makeZapRequest(params: ProfileZap | EventZap): EventTemplate {\n  let zr: EventTemplate = {\n    kind: 9734,\n    created_at: Math.round(Date.now() / 1000),\n    content: params.comment || '',\n    tags: [\n      ['p', 'pubkey' in params ? params.pubkey : params.event.pubkey],\n      ['amount', params.amount.toString()],\n      ['relays', ...params.relays],\n    ],\n  }\n\n  if ('event' in params) {\n    zr.tags.push(['e', params.event.id])\n    if (isReplaceableKind(params.event.kind)) {\n      const a = ['a', `${params.event.kind}:${params.event.pubkey}:`]\n      zr.tags.push(a)\n    } else if (isAddressableKind(params.event.kind)) {\n      let d = params.event.tags.find(([t, v]) => t === 'd' && v)\n      if (!d) throw new Error('d tag not found or is empty')\n      const a = ['a', `${params.event.kind}:${params.event.pubkey}:${d[1]}`]\n      zr.tags.push(a)\n    }\n    zr.tags.push(['k', params.event.kind.toString()])\n  }\n\n  return zr\n}\n\nexport function validateZapRequest(zapRequestString: string): string | null {\n  let zapRequest: Event\n\n  try {\n    zapRequest = JSON.parse(zapRequestString)\n  } catch (err) {\n    return 'Invalid zap request JSON.'\n  }\n\n  if (!validateEvent(zapRequest)) return 'Zap request is not a valid Nostr event.'\n\n  if (!verifyEvent(zapRequest)) return 'Invalid signature on zap request.'\n\n  let p = zapRequest.tags.find(([t, v]) => t === 'p' && v)\n  if (!p) return \"Zap request doesn't have a 'p' tag.\"\n  if (!p[1].match(/^[a-f0-9]{64}$/)) return \"Zap request 'p' tag is not valid hex.\"\n\n  let e = zapRequest.tags.find(([t, v]) => t === 'e' && v)\n  if (e && !e[1].match(/^[a-f0-9]{64}$/)) return \"Zap request 'e' tag is not valid hex.\"\n\n  let relays = zapRequest.tags.find(([t, v]) => t === 'relays' && v)\n  if (!relays) return \"Zap request doesn't have a 'relays' tag.\"\n\n  return null\n}\n\nexport function makeZapReceipt({\n  zapRequest,\n  preimage,\n  bolt11,\n  paidAt,\n}: {\n  zapRequest: string\n  preimage?: string\n  bolt11: string\n  paidAt: Date\n}): EventTemplate {\n  let zr: Event = JSON.parse(zapRequest)\n  let tagsFromZapRequest = zr.tags.filter(([t]) => t === 'e' || t === 'p' || t === 'a')\n\n  let zap: EventTemplate = {\n    kind: 9735,\n    created_at: Math.round(paidAt.getTime() / 1000),\n    content: '',\n    tags: [...tagsFromZapRequest, ['P', zr.pubkey], ['bolt11', bolt11], ['description', zapRequest]],\n  }\n\n  if (preimage) {\n    zap.tags.push(['preimage', preimage])\n  }\n\n  return zap\n}\n\nexport function getSatoshisAmountFromBolt11(bolt11: string): number {\n  if (bolt11.length < 50) {\n    return 0\n  }\n  bolt11 = bolt11.substring(0, 50)\n  const idx = bolt11.lastIndexOf('1')\n  if (idx === -1) {\n    return 0\n  }\n  const hrp = bolt11.substring(0, idx)\n  if (!hrp.startsWith('lnbc')) {\n    return 0\n  }\n  const amount = hrp.substring(4) // equivalent to strings.CutPrefix\n\n  if (amount.length < 1) {\n    return 0\n  }\n\n  // if last character is a digit, then the amount can just be interpreted as BTC\n  const char = amount[amount.length - 1]\n  const digit = char.charCodeAt(0) - '0'.charCodeAt(0)\n  const isDigit = digit >= 0 && digit <= 9\n\n  let cutPoint = amount.length - 1\n  if (isDigit) {\n    cutPoint++\n  }\n\n  if (cutPoint < 1) {\n    return 0\n  }\n\n  const num = parseInt(amount.substring(0, cutPoint))\n\n  switch (char) {\n    case 'm':\n      return num * 100000\n    case 'u':\n      return num * 100\n    case 'n':\n      return num / 10\n    case 'p':\n      return num / 10000\n    default:\n      return num * 100000000\n  }\n}\n","import { sha256 } from '@noble/hashes/sha256'\nimport { bytesToHex } from '@noble/hashes/utils'\nimport { base64 } from '@scure/base'\n\nimport { HTTPAuth } from './kinds.ts'\nimport { Event, EventTemplate, verifyEvent } from './pure.ts'\nimport { utf8Decoder, utf8Encoder } from './utils.ts'\n\nconst _authorizationScheme = 'Nostr '\n\n/**\n * Generate token for NIP-98 flow.\n *\n * @example\n * const sign = window.nostr.signEvent\n * await nip98.getToken('https://example.com/login', 'post', (e) => sign(e), true)\n */\nexport async function getToken(\n  loginUrl: string,\n  httpMethod: string,\n  sign: (e: EventTemplate) => Promise<Event> | Event,\n  includeAuthorizationScheme: boolean = false,\n  payload?: Record<string, any>,\n): Promise<string> {\n  const event: EventTemplate = {\n    kind: HTTPAuth,\n    tags: [\n      ['u', loginUrl],\n      ['method', httpMethod],\n    ],\n    created_at: Math.round(new Date().getTime() / 1000),\n    content: '',\n  }\n\n  if (payload) {\n    event.tags.push(['payload', hashPayload(payload)])\n  }\n\n  const signedEvent = await sign(event)\n  const authorizationScheme = includeAuthorizationScheme ? _authorizationScheme : ''\n\n  return authorizationScheme + base64.encode(utf8Encoder.encode(JSON.stringify(signedEvent)))\n}\n\n/**\n * Validate token for NIP-98 flow.\n *\n * @example\n * await nip98.validateToken('Nostr base64token', 'https://example.com/login', 'post')\n */\nexport async function validateToken(token: string, url: string, method: string): Promise<boolean> {\n  const event = await unpackEventFromToken(token).catch(error => {\n    throw error\n  })\n\n  const valid = await validateEvent(event, url, method).catch(error => {\n    throw error\n  })\n\n  return valid\n}\n\n/**\n * Unpacks an event from a token.\n *\n * @param token - The token to unpack.\n * @returns A promise that resolves to the unpacked event.\n * @throws {Error} If the token is missing, invalid, or cannot be parsed.\n */\nexport async function unpackEventFromToken(token: string): Promise<Event> {\n  if (!token) {\n    throw new Error('Missing token')\n  }\n\n  token = token.replace(_authorizationScheme, '')\n\n  const eventB64 = utf8Decoder.decode(base64.decode(token))\n  if (!eventB64 || eventB64.length === 0 || !eventB64.startsWith('{')) {\n    throw new Error('Invalid token')\n  }\n\n  const event = JSON.parse(eventB64) as Event\n\n  return event\n}\n\n/**\n * Validates the timestamp of an event.\n * @param event - The event object to validate.\n * @returns A boolean indicating whether the event timestamp is within the last 60 seconds.\n */\nexport function validateEventTimestamp(event: Event): boolean {\n  if (!event.created_at) {\n    return false\n  }\n\n  return Math.round(new Date().getTime() / 1000) - event.created_at < 60\n}\n\n/**\n * Validates the kind of an event.\n * @param event The event to validate.\n * @returns A boolean indicating whether the event kind is valid.\n */\nexport function validateEventKind(event: Event): boolean {\n  return event.kind === HTTPAuth\n}\n\n/**\n * Validates if the given URL matches the URL tag of the event.\n * @param event - The event object.\n * @param url - The URL to validate.\n * @returns A boolean indicating whether the URL is valid or not.\n */\nexport function validateEventUrlTag(event: Event, url: string): boolean {\n  const urlTag = event.tags.find(t => t[0] === 'u')\n\n  if (!urlTag) {\n    return false\n  }\n\n  return urlTag.length > 0 && urlTag[1] === url\n}\n\n/**\n * Validates if the given event has a method tag that matches the specified method.\n * @param event - The event to validate.\n * @param method - The method to match against the method tag.\n * @returns A boolean indicating whether the event has a matching method tag.\n */\nexport function validateEventMethodTag(event: Event, method: string): boolean {\n  const methodTag = event.tags.find(t => t[0] === 'method')\n\n  if (!methodTag) {\n    return false\n  }\n\n  return methodTag.length > 0 && methodTag[1].toLowerCase() === method.toLowerCase()\n}\n\n/**\n * Calculates the hash of a payload.\n * @param payload - The payload to be hashed.\n * @returns The hash value as a string.\n */\nexport function hashPayload(payload: any): string {\n  const hash = sha256(utf8Encoder.encode(JSON.stringify(payload)))\n  return bytesToHex(hash)\n}\n\n/**\n * Validates the event payload tag against the provided payload.\n * @param event The event object.\n * @param payload The payload to validate.\n * @returns A boolean indicating whether the payload tag is valid.\n */\nexport function validateEventPayloadTag(event: Event, payload: any): boolean {\n  const payloadTag = event.tags.find(t => t[0] === 'payload')\n\n  if (!payloadTag) {\n    return false\n  }\n\n  const payloadHash = hashPayload(payload)\n  return payloadTag.length > 0 && payloadTag[1] === payloadHash\n}\n\n/**\n * Validates a Nostr event for the NIP-98 flow.\n *\n * @param event - The Nostr event to validate.\n * @param url - The URL associated with the event.\n * @param method - The HTTP method associated with the event.\n * @param body - The request body associated with the event (optional).\n * @returns A promise that resolves to a boolean indicating whether the event is valid.\n * @throws An error if the event is invalid.\n */\nexport async function validateEvent(event: Event, url: string, method: string, body?: any): Promise<boolean> {\n  if (!verifyEvent(event)) {\n    throw new Error('Invalid nostr event, signature invalid')\n  }\n\n  if (!validateEventKind(event)) {\n    throw new Error('Invalid nostr event, kind invalid')\n  }\n\n  if (!validateEventTimestamp(event)) {\n    throw new Error('Invalid nostr event, created_at timestamp invalid')\n  }\n\n  if (!validateEventUrlTag(event, url)) {\n    throw new Error('Invalid nostr event, url tag invalid')\n  }\n\n  if (!validateEventMethodTag(event, method)) {\n    throw new Error('Invalid nostr event, method tag invalid')\n  }\n\n  if (Boolean(body) && typeof body === 'object' && Object.keys(body).length > 0) {\n    if (!validateEventPayloadTag(event, body)) {\n      throw new Error('Invalid nostr event, payload tag does not match request body hash')\n    }\n  }\n\n  return true\n}\n"]}