{
  "version": 3,
  "sources": ["../src/utils.ts", "../src/errors.ts", "../src/version.ts", "../src/helpers/blockchain.ts", "../src/chain/account.ts", "../src/chain/asset.ts", "../src/helpers/broadcast.ts", "../src/helpers/database.ts", "../src/helpers/hivemind.ts", "../src/helpers/key.ts", "../src/helpers/market.ts", "../src/chain/misc.ts", "../src/helpers/rc.ts", "../src/helpers/transaction.ts", "../src/health-tracker.ts", "../src/client.ts", "../node_modules/.pnpm/@scure+base@2.2.0/node_modules/@scure/base/index.ts", "../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/utils.ts", "../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/_md.ts", "../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/legacy.ts", "../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/_u64.ts", "../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/sha2.ts", "../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/src/utils.ts", "../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/src/abstract/modular.ts", "../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/src/abstract/curve.ts", "../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/hmac.ts", "../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/src/abstract/weierstrass.ts", "../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/src/secp256k1.ts", "../src/crypto.ts", "../src/chain/serializer.ts", "../src/chain/op-filter.ts", "../src/chain/deserializer.ts", "../node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/src/utils.ts", "../node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/src/aes.ts", "../src/helpers/aes.ts", "../src/memo.ts"],
  "sourcesContent": ["/**\n * @file Misc utility functions.\n * @author Johan Nordberg <code@johan-nordberg.com>\n * @license\n * Copyright (c) 2017 Johan Nordberg. All Rights Reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n *  1. Redistribution of source code must retain the above copyright notice, this\n *     list of conditions and the following disclaimer.\n *\n *  2. Redistribution in binary form must reproduce the above copyright notice,\n *     this list of conditions and the following disclaimer in the documentation\n *     and/or other materials provided with the distribution.\n *\n *  3. Neither the name of the copyright holder nor the names of its contributors\n *     may be used to endorse or promote products derived from this software without\n *     specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * You acknowledge that this software is not designed, licensed or intended for use\n * in the design, construction, operation or maintenance of any military facility.\n */\n\nimport { NodeHealthTracker } from \"./health-tracker.js\";\n\n// Errors that indicate the request never reached the server \u2014 safe to retry even for broadcasts\nconst PRE_CONNECTION_ERRORS = [\"ECONNREFUSED\", \"ENOTFOUND\", \"EHOSTUNREACH\", \"EAI_AGAIN\"];\n\n// All errors that should trigger failover for read operations\nconst FAILOVER_ERRORS = [\n  ...PRE_CONNECTION_ERRORS,\n  \"timeout\",\n  \"database lock\",\n  \"CERT_HAS_EXPIRED\",\n  \"ECONNRESET\",\n  \"ERR_TLS_CERT_ALTNAME_INVALID\",\n  \"ETIMEDOUT\",\n  \"EPIPE\",\n  \"EPROTO\",\n];\n\n/**\n * Context for smart retry and failover decisions.\n */\nexport interface RetryContext {\n  healthTracker?: NodeHealthTracker;\n  api?: string;\n  isBroadcast?: boolean;\n  consoleOnFailover?: boolean;\n}\n\n/**\n * Asserts that a condition is truthy.\n *\n * @param condition - The condition to check.\n * @param message - Optional error message.\n *\n * @throws Error\n * Thrown when `condition` is falsy.\n */\nexport function assert(condition: any, message?: string): asserts condition {\n  if (!condition) {\n    throw new Error(message || \"Assertion failed\");\n  }\n}\n\n/**\n * Converts a Uint8Array to a hex-encoded string.\n *\n * @param data - Native byte array to encode.\n * @returns Lowercase hex string with two characters per byte.\n *\n * @remarks\n * Pollen uses this helper at RPC and JSON boundaries where Hive expects binary\n * protocol values to be represented as hex text.\n *\n * @example\n * ```ts\n * const hex = toHex(new Uint8Array([0xde, 0xad, 0xbe, 0xef]))\n * ```\n */\nexport function toHex(data: Uint8Array): string {\n  let out = \"\";\n  for (let i = 0; i < data.length; i++) {\n    out += data[i].toString(16).padStart(2, \"0\");\n  }\n  return out;\n}\n\n/**\n * Converts a hex-encoded string to a Uint8Array.\n *\n * @param hex - Hex string with an even number of characters.\n * @returns Native bytes represented by the string.\n *\n * @throws Error\n * Thrown when `hex` has an odd number of characters.\n *\n * @example\n * ```ts\n * const bytes = fromHex('deadbeef')\n * ```\n */\nexport function fromHex(hex: string): Uint8Array {\n  if (hex.length % 2 !== 0) {\n    throw new Error(\"Invalid hex string\");\n  }\n  const out = new Uint8Array(hex.length / 2);\n  for (let i = 0; i < out.length; i++) {\n    out[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);\n  }\n  return out;\n}\n\n/**\n * Concatenates multiple Uint8Arrays into one.\n *\n * @param arrays - Byte arrays to join in order.\n * @returns A new `Uint8Array` containing all input bytes.\n *\n * @remarks\n * This replaces Node `Buffer.concat` in protocol paths that must run the same\n * way in Node and browsers.\n *\n * @example\n * ```ts\n * const digestInput = concat([chainId, transactionBytes])\n * ```\n */\nexport function concat(arrays: Uint8Array[]): Uint8Array {\n  const totalLength = arrays.reduce((acc, arr) => acc + arr.length, 0);\n  const result = new Uint8Array(totalLength);\n  let offset = 0;\n  for (const arr of arrays) {\n    result.set(arr, offset);\n    offset += arr.length;\n  }\n  return result;\n}\n\n/**\n * Compares two byte arrays for equality.\n *\n * @param a - First byte array.\n * @param b - Second byte array.\n * @returns True when both arrays have the same length and byte values.\n *\n * @example\n * ```ts\n * if (!bytesEqual(expected, actual)) {\n *   throw new Error('checksum mismatch')\n * }\n * ```\n */\nexport function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n  if (a.length !== b.length) {\n    return false;\n  }\n  for (let i = 0; i < a.length; i++) {\n    if (a[i] !== b[i]) {\n      return false;\n    }\n  }\n  return true;\n}\n\n/**\n * Growable little-endian byte writer used by Hive serializers.\n *\n * @remarks\n * The writer is built on `Uint8Array` and `DataView`, so protocol serialization\n * does not depend on Node `Buffer` or third-party byte-buffer packages. 64-bit\n * integers are accepted as `number`, decimal `string`, or native `bigint` and\n * are written in Hive's little-endian wire order.\n */\nexport class BinaryWriter {\n  private buffer: Uint8Array;\n  private cursor = 0;\n\n  constructor(size = 1024) {\n    this.buffer = new Uint8Array(size);\n  }\n\n  private ensureCapacity(size: number) {\n    if (this.cursor + size > this.buffer.length) {\n      const newBuffer = new Uint8Array(this.buffer.length * 2 + size);\n      newBuffer.set(this.buffer);\n      this.buffer = newBuffer;\n    }\n  }\n\n  public writeInt8(value: number) {\n    this.ensureCapacity(1);\n    new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength).setInt8(\n      this.cursor++,\n      value,\n    );\n  }\n\n  public writeUint8(value: number) {\n    this.ensureCapacity(1);\n    this.buffer[this.cursor++] = value;\n  }\n\n  public writeInt16(value: number) {\n    this.ensureCapacity(2);\n    new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength).setInt16(\n      this.cursor,\n      value,\n      true,\n    );\n    this.cursor += 2;\n  }\n\n  public writeUint16(value: number) {\n    this.ensureCapacity(2);\n    new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength).setUint16(\n      this.cursor,\n      value,\n      true,\n    );\n    this.cursor += 2;\n  }\n\n  public writeInt32(value: number) {\n    this.ensureCapacity(4);\n    new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength).setInt32(\n      this.cursor,\n      value,\n      true,\n    );\n    this.cursor += 4;\n  }\n\n  public writeUint32(value: number) {\n    this.ensureCapacity(4);\n    new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength).setUint32(\n      this.cursor,\n      value,\n      true,\n    );\n    this.cursor += 4;\n  }\n\n  public writeInt64(value: number | string | bigint) {\n    this.ensureCapacity(8);\n    const val = BigInt(value.toString());\n    const low = Number(val & 0xffffffffn);\n    const high = Number(val >> 32n);\n    const view = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength);\n    view.setUint32(this.cursor, low, true);\n    view.setUint32(this.cursor + 4, high, true);\n    this.cursor += 8;\n  }\n\n  public writeUint64(value: number | string | bigint) {\n    this.ensureCapacity(8);\n    const val = BigInt(value.toString());\n    const low = Number(val & 0xffffffffn);\n    const high = Number(val >> 32n);\n    const view = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength);\n    view.setUint32(this.cursor, low, true);\n    view.setUint32(this.cursor + 4, high, true);\n    this.cursor += 8;\n  }\n\n  public writeVarint32(value: number) {\n    while (value >= 0x80) {\n      this.writeUint8((value & 0x7f) | 0x80);\n      value >>>= 7;\n    }\n    this.writeUint8(value);\n  }\n\n  public writeString(value: string) {\n    const bytes = new TextEncoder().encode(value);\n    this.writeVarint32(bytes.length);\n    this.writeBytes(bytes);\n  }\n\n  public writeBytes(bytes: Uint8Array) {\n    this.ensureCapacity(bytes.length);\n    this.buffer.set(bytes, this.cursor);\n    this.cursor += bytes.length;\n  }\n\n  public getBuffer(): Uint8Array {\n    return this.buffer.slice(0, this.cursor);\n  }\n}\n\n/**\n * Little-endian byte reader used by Hive deserializers and memo decoding.\n *\n * @remarks\n * The constructor copies input into a clean `Uint8Array` before creating its\n * `DataView`. That avoids backing-store offset surprises from Buffer-like\n * views while preserving a browser-native byte engine. 64-bit readers return\n * native `bigint`, matching the Phase 8 removal of JSBI from the hot path.\n */\nexport class BinaryReader {\n  private view: DataView;\n  private cursor = 0;\n\n  constructor(private buffer: Uint8Array) {\n    // Normalize to a clean view so byte offsets never leak into DataView reads.\n    const b = new Uint8Array(buffer);\n    this.buffer = b;\n    this.view = new DataView(b.buffer, b.byteOffset, b.byteLength);\n  }\n\n  public readInt8(): number {\n    return this.view.getInt8(this.cursor++);\n  }\n\n  public readUint8(): number {\n    return this.view.getUint8(this.cursor++);\n  }\n\n  public readInt16(): number {\n    const val = this.view.getInt16(this.cursor, true);\n    this.cursor += 2;\n    return val;\n  }\n\n  public readUint16(): number {\n    const val = this.view.getUint16(this.cursor, true);\n    this.cursor += 2;\n    return val;\n  }\n\n  public readInt32(): number {\n    const val = this.view.getInt32(this.cursor, true);\n    this.cursor += 4;\n    return val;\n  }\n\n  public readUint32(): number {\n    const val = this.view.getUint32(this.cursor, true);\n    this.cursor += 4;\n    return val;\n  }\n\n  public readInt64(): bigint {\n    const low = BigInt(this.view.getUint32(this.cursor, true));\n    const high = BigInt(this.view.getUint32(this.cursor + 4, true));\n    this.cursor += 8;\n    return low + (high << 32n);\n  }\n\n  public readUint64(): bigint {\n    return this.readInt64();\n  }\n\n  public readVarint32(): number {\n    let value = 0;\n    let shift = 0;\n    let b: number;\n    do {\n      b = this.readUint8();\n      value |= (b & 0x7f) << shift;\n      shift += 7;\n    } while (b & 0x80);\n    return value;\n  }\n\n  public readString(): string {\n    const length = this.readVarint32();\n    return new TextDecoder().decode(this.readBytes(length));\n  }\n\n  public readBytes(length: number): Uint8Array {\n    if (this.cursor + length > this.buffer.length) {\n      throw new Error(\n        `Out of bounds read: requested ${length} bytes but only ${this.buffer.length - this.cursor} available`,\n      );\n    }\n    const bytes = this.buffer.slice(this.cursor, this.cursor + length);\n    this.cursor += length;\n    return bytes;\n  }\n\n  public skip(length: number) {\n    this.cursor += length;\n  }\n}\n\n/**\n * Pauses execution for a fixed number of milliseconds.\n */\nexport function sleep(ms: number): Promise<void> {\n  return new Promise<void>((resolve) => {\n    setTimeout(resolve, ms);\n  });\n}\n\n/**\n * Converts an async iterator into a native Web ReadableStream.\n *\n * @remarks\n * This replaces the Node-specific `PassThrough` implementation with a browser-native\n * stream engine, enabling zero-dependency streaming in both environments.\n */\nexport function iteratorStream<T>(iterator: AsyncIterableIterator<T>): ReadableStream<T> {\n  return new ReadableStream({\n    async pull(controller) {\n      try {\n        const { value, done } = await iterator.next();\n        if (done) {\n          controller.close();\n        } else {\n          controller.enqueue(value);\n        }\n      } catch (error) {\n        controller.error(error);\n      }\n    },\n  });\n}\n\n/**\n * Creates a deep copy of a JSON-serializable object.\n */\nexport function copy<T>(object: T): T {\n  return JSON.parse(JSON.stringify(object));\n}\n\n/**\n * Check if an error code indicates the request never reached the server.\n */\nfunction isPreConnectionError(error: unknown): boolean {\n  if (!error || typeof error !== \"object\" || !(\"code\" in error)) return false;\n  const code = (error as { code: string }).code;\n  return PRE_CONNECTION_ERRORS.some((errCode) => code.includes(errCode));\n}\n\n/**\n * Check if an error should trigger failover for read operations.\n * Matches any known network/timeout error, or errors with no code (HTTP errors).\n */\nfunction shouldFailover(error: unknown): boolean {\n  if (!error) return true;\n  // HTTP errors (from !response.ok) have no .code \u2014 they should trigger failover\n  if (typeof error !== \"object\" || !(\"code\" in error)) return true;\n  const code = (error as { code: string }).code;\n  return FAILOVER_ERRORS.some((errCode) => code.includes(errCode));\n}\n\n/**\n * Get the next node in the ordered list (wraps around).\n */\nfunction nextNode(nodes: string[], currentIndex: number): number {\n  return (currentIndex + 1) % nodes.length;\n}\n\n/**\n * Computes an exponential retry delay with random jitter.\n */\nexport function exponentialBackoffWithJitter(\n  tries: number,\n  baseDelay = 500,\n  maxDelay = 10000,\n  jitter = 100,\n): number {\n  const delay = Math.min(maxDelay, baseDelay * Math.pow(2, tries));\n  return delay + Math.floor(Math.random() * jitter);\n}\n\n/**\n * Sends an RPC request with ordered node failover and health tracking.\n */\nexport async function retryingFetch(\n  currentAddress: string,\n  allAddresses: string | string[],\n  opts: RequestInit & { agent?: unknown; timeout?: number },\n  timeout: number,\n  failoverThreshold: number,\n  consoleOnFailover: boolean,\n  backoff: (tries: number) => number,\n  fetchTimeout?: (tries: number) => number,\n  retryContext?: RetryContext,\n) {\n  const { healthTracker, api, isBroadcast } = retryContext || {};\n  const logFailover = retryContext?.consoleOnFailover ?? consoleOnFailover;\n\n  // Build ordered node list: healthy nodes first, then unhealthy as fallback\n  let orderedNodes: string[];\n  if (Array.isArray(allAddresses) && allAddresses.length > 1) {\n    orderedNodes = healthTracker\n      ? healthTracker.getOrderedNodes(allAddresses, api)\n      : [...allAddresses];\n  } else {\n    orderedNodes = Array.isArray(allAddresses) ? allAddresses : [allAddresses];\n  }\n\n  let nodeIndex = 0;\n\n  const totalNodes = orderedNodes.length;\n  const startTime = Date.now();\n  let nodesTriedInRound = 0;\n  let round = 0;\n  let lastError: unknown;\n\n  while (true) {\n    const node = orderedNodes[nodeIndex];\n\n    try {\n      if (healthTracker && healthTracker.isRateLimited(node)) {\n        lastError = new Error(`Node ${node} is rate-limited, skipping`);\n        if (healthTracker && api) healthTracker.recordFailure(node, api);\n        throw lastError;\n      }\n\n      if (fetchTimeout) {\n        opts.timeout = fetchTimeout(nodesTriedInRound);\n      }\n\n      // Validate node URL to mitigate SSRF (CWE-918)\n      try {\n        const parsedUrl = new URL(node);\n        if (parsedUrl.protocol !== \"http:\" && parsedUrl.protocol !== \"https:\") {\n          const err = new Error(`Forbidden protocol: ${parsedUrl.protocol}`) as any;\n          err.code = \"EINVALURL\";\n          throw err;\n        }\n      } catch (err: any) {\n        if (err.code === \"EINVALURL\") {\n          throw err;\n        }\n        const message = err instanceof Error ? err.message : String(err);\n        const formatErr = new Error(`Invalid or insecure RPC node URL: ${node}. Details: ${message}`) as any;\n        formatErr.code = \"EINVALURL\";\n        throw formatErr;\n      }\n\n      const response = await fetch(node, opts);\n\n      if (!response.ok) {\n        if (response.status === 429) {\n          const retryAfterHeader = response.headers?.get?.(\"retry-after\");\n          const retryAfterSec = retryAfterHeader ? parseInt(retryAfterHeader, 10) : undefined;\n          if (healthTracker) {\n            healthTracker.recordRateLimit(\n              node,\n              !isNaN(retryAfterSec as number) ? retryAfterSec : undefined,\n            );\n          }\n          throw new Error(`HTTP 429: Too Many Requests`);\n        }\n\n        if (response.status === 503) {\n          if (healthTracker && api) healthTracker.recordFailure(node, api);\n          throw new Error(`HTTP 503: Service Temporarily Unavailable`);\n        }\n\n        try {\n          const resJson = await response.json();\n          if (resJson.jsonrpc === \"2.0\") {\n            if (healthTracker && api) healthTracker.recordSuccess(node, api);\n            return { response: resJson, currentAddress: node };\n          }\n        } catch {}\n        const statusText = response.statusText || `status code ${response.status}`;\n        throw new Error(`HTTP ${response.status}: ${statusText}`);\n      }\n\n      const responseJson = await response.json();\n\n      if (healthTracker && api) {\n        healthTracker.recordSuccess(node, api);\n      }\n\n      return { response: responseJson, currentAddress: node };\n    } catch (error: any) {\n      lastError = error;\n\n      if (healthTracker && api) {\n        healthTracker.recordFailure(node, api);\n      }\n\n      if (isBroadcast) {\n        if (isPreConnectionError(error) && totalNodes > 1) {\n          nodeIndex = nextNode(orderedNodes, nodeIndex);\n          nodesTriedInRound++;\n          if (nodesTriedInRound >= totalNodes) {\n            throw error;\n          }\n          if (logFailover) {\n            console.log(\n              `Broadcast failover to: ${orderedNodes[nodeIndex]} (${error.code}, request never sent)`,\n            );\n          }\n          continue;\n        }\n        throw error;\n      }\n\n      if (!shouldFailover(error)) {\n        throw error;\n      }\n\n      if (totalNodes > 1 && nodesTriedInRound > 0) {\n        await sleep(50 + Math.random() * 50);\n      }\n\n      if (totalNodes > 1) {\n        nodeIndex = nextNode(orderedNodes, nodeIndex);\n        nodesTriedInRound++;\n\n        if (nodesTriedInRound >= totalNodes) {\n          nodesTriedInRound = 0;\n          if (failoverThreshold > 0) {\n            round++;\n            if (round >= failoverThreshold) {\n              error.message =\n                `All ${totalNodes} nodes failed after ${failoverThreshold} rounds. ` +\n                `Last error: [${error.code || \"HTTP\"}] ${error.message}. ` +\n                `Nodes: ${orderedNodes.join(\", \")}`;\n              throw error;\n            }\n          }\n          if (timeout !== 0 && Date.now() - startTime > timeout) {\n            throw error;\n          }\n          await sleep(backoff(round));\n        }\n\n        if (logFailover) {\n          console.log(\n            `Switched Hive RPC: ${orderedNodes[nodeIndex]} (previous: ${node}, error: ${error.code || error.message})`,\n          );\n        }\n      } else {\n        if (timeout !== 0 && Date.now() - startTime > timeout) {\n          throw error;\n        }\n        await sleep(backoff(nodesTriedInRound++));\n      }\n    }\n  }\n}\n\nimport { Asset, PriceType } from \"./chain/asset.js\";\nimport { WitnessSetPropertiesOperation } from \"./chain/operation.js\";\nimport { Serializer, Types } from \"./chain/serializer.js\";\nimport { PublicKey } from \"./crypto.js\";\n\nexport interface WitnessProps {\n  account_creation_fee?: string | Asset;\n  account_subsidy_budget?: number; // uint32_t\n  account_subsidy_decay?: number; // uint32_t\n  key: PublicKey | string;\n  maximum_block_size?: number; // uint32_t\n  new_signing_key?: PublicKey | string | null;\n  hbd_exchange_rate?: PriceType;\n  hbd_interest_rate?: number; // uint16_t\n  url?: string;\n}\n\nconst serialize = (serializer: Serializer, data: unknown) => {\n  const writer = new BinaryWriter();\n  serializer(writer, data);\n  return toHex(writer.getBuffer());\n};\n\nexport const buildWitnessUpdateOp = (\n  owner: string,\n  props: WitnessProps,\n): WitnessSetPropertiesOperation => {\n  const data: WitnessSetPropertiesOperation[1] = {\n    extensions: [],\n    owner,\n    props: [],\n  };\n  for (const key of Object.keys(props)) {\n    let type: Serializer;\n    switch (key) {\n      case \"key\":\n      case \"new_signing_key\":\n        type = Types.PublicKey;\n        break;\n      case \"account_subsidy_budget\":\n      case \"account_subsidy_decay\":\n      case \"maximum_block_size\":\n        type = Types.UInt32;\n        break;\n      case \"hbd_interest_rate\":\n        type = Types.UInt16;\n        break;\n      case \"url\":\n        type = Types.String;\n        break;\n      case \"hbd_exchange_rate\":\n        type = Types.Price;\n        break;\n      case \"account_creation_fee\":\n        type = Types.Asset;\n        break;\n      default:\n        throw new Error(`Unknown witness prop: ${key}`);\n    }\n    data.props.push([key, serialize(type, props[key])]);\n  }\n  data.props.sort((a, b) => a[0].localeCompare(b[0]));\n  return [\"witness_set_properties\", data];\n};\n\nexport const operationOrders = {\n  vote: 0,\n  comment: 1,\n  transfer: 2,\n  transfer_to_vesting: 3,\n  withdraw_vesting: 4,\n  limit_order_create: 5,\n  limit_order_cancel: 6,\n  feed_publish: 7,\n  convert: 8,\n  account_create: 9,\n  account_update: 10,\n  witness_update: 11,\n  account_witness_vote: 12,\n  account_witness_proxy: 13,\n  pow: 14,\n  custom: 15,\n  report_over_production: 16,\n  delete_comment: 17,\n  custom_json: 18,\n  comment_options: 19,\n  set_withdraw_vesting_route: 20,\n  limit_order_create2: 21,\n  claim_account: 22,\n  create_claimed_account: 23,\n  request_account_recovery: 24,\n  recover_account: 25,\n  change_recovery_account: 26,\n  escrow_transfer: 27,\n  escrow_dispute: 28,\n  escrow_release: 29,\n  pow2: 30,\n  escrow_approve: 31,\n  transfer_to_savings: 32,\n  transfer_from_savings: 33,\n  cancel_transfer_from_savings: 34,\n  custom_binary: 35,\n  decline_voting_rights: 36,\n  reset_account: 37,\n  set_reset_account: 38,\n  claim_reward_balance: 39,\n  delegate_vesting_shares: 40,\n  account_create_with_delegation: 41,\n  witness_set_properties: 42,\n  account_update2: 43,\n  create_proposal: 44,\n  update_proposal_votes: 45,\n  remove_proposal: 46,\n  update_proposal: 47,\n  collateralized_convert: 48,\n  recurrent_transfer: 49,\n  // virtual ops\n  fill_convert_request: 50,\n  author_reward: 51,\n  curation_reward: 52,\n  comment_reward: 53,\n  liquidity_reward: 54,\n  interest: 55,\n  fill_vesting_withdraw: 56,\n  fill_order: 57,\n  shutdown_witness: 58,\n  fill_transfer_from_savings: 59,\n  hardfork: 60,\n  comment_payout_update: 61,\n  return_vesting_delegation: 62,\n  comment_benefactor_reward: 63,\n  producer_reward: 64,\n  clear_null_account_balance: 65,\n  proposal_pay: 66,\n  sps_fund: 67,\n  hardfork_hive: 68,\n  hardfork_hive_restore: 69,\n  delayed_voting: 70,\n  consolidate_treasury_balance: 71,\n  effective_comment_vote: 72,\n  ineffective_delete_comment: 73,\n  sps_convert: 74,\n  expired_account_notification: 75,\n  changed_recovery_account: 76,\n  transfer_to_vesting_completed: 77,\n  pow_reward: 78,\n  vesting_shares_split: 79,\n  account_created: 80,\n  fill_collateralized_convert_request: 81,\n  system_warning: 82,\n  fill_recurrent_transfer: 83,\n  failed_recurrent_transfer: 84,\n};\n\n/**\n * Builds the two-word account-history operation mask accepted by Hive.\n *\n * @param allowedOperations - Operation ids from {@link operationOrders}.\n * @returns Low/high mask words as decimal strings, with zero words represented\n * as `null`.\n *\n * @remarks\n * Native `bigint` is used for the 64-bit mask words, replacing the older JSBI\n * shim while keeping the returned RPC shape as decimal strings or `null`.\n *\n * @example\n * ```ts\n * const mask = makeBitMaskFilter([\n *   operationOrders.transfer,\n *   operationOrders.claim_reward_balance\n * ])\n * ```\n */\nexport function makeBitMaskFilter(allowedOperations: number[]) {\n  return allowedOperations\n    .reduce(redFunction, [0n, 0n])\n    .map((value) => (value !== 0n ? value.toString() : null));\n}\n\nconst redFunction = ([low, high]: [bigint, bigint], allowedOperation: number): [bigint, bigint] => {\n  if (allowedOperation < 64) {\n    return [low | (1n << BigInt(allowedOperation)), high];\n  } else {\n    return [low, high | (1n << BigInt(allowedOperation - 64))];\n  }\n};\n", "/**\n * @file Native error classes for Pollen.\n * @license BSD-3-Clause-No-Military-License\n */\n\n/**\n * Base error class for all Pollen-specific failures.\n *\n * @remarks\n * Pollen error classes preserve the original contextual payload on `info` so\n * applications can log RPC details, serialization causes, or protocol metadata\n * without parsing the message string.\n *\n * @example\n * ```ts\n * try {\n *   await client.database.getAccounts(['srbde'])\n * } catch (error) {\n *   if (error instanceof PollenError) {\n *     console.error(error.name, error.info)\n *   }\n * }\n * ```\n */\nexport class PollenError extends Error {\n  public readonly info?: unknown;\n\n  /**\n   * Creates a Pollen error with optional structured context.\n   *\n   * @param message - Human-readable error message.\n   * @param info - Optional structured details from the failing subsystem.\n   */\n  constructor(message: string, info?: unknown) {\n    super(message);\n    this.name = \"PollenError\";\n    this.info = info;\n    Object.setPrototypeOf(this, PollenError.prototype);\n  }\n}\n\n/**\n * Error thrown when a Hive RPC node returns a JSON-RPC error.\n *\n * @remarks\n * The `info` property contains the original RPC error data when the node\n * provides it, including assertion stacks from `hived` or plugin-specific\n * details. Catch this around read and broadcast calls when user-facing recovery\n * should distinguish network/API failures from local validation.\n *\n * @example\n * ```ts\n * try {\n *   await client.broadcast.transfer(transfer, activeKey)\n * } catch (error) {\n *   if (error instanceof RPCError) {\n *     console.error('Hive rejected the transaction', error.info)\n *   }\n * }\n * ```\n */\nexport class RPCError extends PollenError {\n  /**\n   * Creates an RPC error.\n   *\n   * @param message - Formatted RPC error message.\n   * @param info - Raw RPC error data, when provided by the node.\n   */\n  constructor(message: string, info?: unknown) {\n    super(message, info);\n    this.name = \"RPCError\";\n    Object.setPrototypeOf(this, RPCError.prototype);\n  }\n}\n\n/**\n * Error thrown when Hive binary serialization or deserialization fails.\n *\n * @remarks\n * Transaction signing, transaction id generation, and memo handling all depend\n * on exact Hive wire encoding. This error indicates that a payload could not be\n * represented in the expected binary format.\n *\n * @example\n * ```ts\n * try {\n *   const signed = cryptoUtils.signTransaction(transaction, activeKey)\n * } catch (error) {\n *   if (error instanceof SerializationError) {\n *     console.error('Invalid transaction shape', error.info)\n *   }\n * }\n * ```\n */\nexport class SerializationError extends PollenError {\n  /**\n   * Creates a serialization error.\n   *\n   * @param message - Human-readable serialization failure.\n   * @param info - Optional underlying cause or field-level context.\n   */\n  constructor(message: string, info?: unknown) {\n    super(message, info);\n    this.name = \"SerializationError\";\n    Object.setPrototypeOf(this, SerializationError.prototype);\n  }\n}\n", "export default '1.0.5';\n", "/**\n * @file Hive blockchain helpers.\n * @author Johan Nordberg <code@johan-nordberg.com>\n * @license\n * Copyright (c) 2017 Johan Nordberg. All Rights Reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n *  1. Redistribution of source code must retain the above copyright notice, this\n *     list of conditions and the following disclaimer.\n *\n *  2. Redistribution in binary form must reproduce the above copyright notice,\n *     this list of conditions and the following disclaimer in the documentation\n *     and/or other materials provided with the distribution.\n *\n *  3. Neither the name of the copyright holder nor the names of its contributors\n *     may be used to endorse or promote products derived from this software without\n *     specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * You acknowledge that this software is not designed, licensed or intended for use\n * in the design, construction, operation or maintenance of any military facility.\n */\n\nimport { Client } from \"./../client.js\";\nimport { iteratorStream, sleep } from \"./../utils.js\";\n\nexport enum BlockchainMode {\n  /**\n   * Stream only blocks that the Hive consensus protocol has made irreversible.\n   *\n   * @remarks\n   * This is the safest mode for indexing, accounting, and other workflows that\n   * must not react to a block that can still be replaced by a fork.\n   */\n  Irreversible,\n  /**\n   * Stream from the latest head block, including blocks that are still reversible.\n   *\n   * @remarks\n   * Use this mode when low latency matters more than finality. Applications\n   * should be prepared to reconcile forked blocks when consuming latest mode.\n   */\n  Latest,\n}\n\n/**\n * Controls the block range and finality policy used by blockchain streams.\n *\n * @example\n * ```ts\n * import { BlockchainMode, Client } from '@srbde/pollen'\n *\n * const client = new Client('https://api.hive.blog')\n *\n * for await (const block of client.blockchain.getBlocks({\n *   from: 90_000_000,\n *   to: 90_000_010,\n *   mode: BlockchainMode.Irreversible\n * })) {\n *   console.log(block.block_id)\n * }\n * ```\n */\nexport interface BlockchainStreamOptions {\n  /**\n   * Start block number, inclusive. If omitted generation will start from current block height.\n   */\n  from?: number;\n  /**\n   * End block number, inclusive. If omitted stream will continue indefinitely.\n   */\n  to?: number;\n  /**\n   * Streaming mode, if set to `Latest` may include blocks that are not applied to the final chain.\n   * Defaults to `Irreversible`.\n   */\n  mode?: BlockchainMode;\n}\n\n/**\n * Convenience helper for reading Hive blocks and operations as async iterators\n * or native Web Streams.\n *\n * @remarks\n * `Blockchain` builds on {@link DatabaseAPI} and adds polling, block-number\n * range management, and finality selection. It is the preferred entry point for\n * indexers and Resilience-style background workers that need a steady feed of\n * blocks or operations without hand-writing polling loops.\n *\n * @example\n * ```ts\n * import { Client } from '@srbde/pollen'\n *\n * const client = new Client('https://api.hive.blog')\n *\n * for await (const op of client.blockchain.getOperations({ from: 90_000_000 })) {\n *   console.log(op.op[0], op.trx_id)\n * }\n * ```\n *\n * @see {@link BlockchainStreamOptions}\n * @see {@link DatabaseAPI.getBlock}\n */\nexport class Blockchain {\n  /**\n   * Creates a blockchain helper bound to a client.\n   *\n   * @param client - Client used for database API reads.\n   */\n  constructor(readonly client: Client) {}\n\n  /**\n   * Resolves the current block number for the selected finality mode.\n   *\n   * @param mode - Whether to read the irreversible block number or the latest\n   * head block number.\n   * @returns The current Hive block number for the selected mode.\n   *\n   * @throws RPCError\n   * Thrown when the underlying `get_dynamic_global_properties` call fails.\n   *\n   * @example\n   * ```ts\n   * const irreversible = await client.blockchain.getCurrentBlockNum()\n   * const latest = await client.blockchain.getCurrentBlockNum(BlockchainMode.Latest)\n   * ```\n   */\n  public async getCurrentBlockNum(mode = BlockchainMode.Irreversible) {\n    const props = await this.client.database.getDynamicGlobalProperties();\n    switch (mode) {\n      case BlockchainMode.Irreversible:\n        return props.last_irreversible_block_num;\n      case BlockchainMode.Latest:\n        return props.head_block_number;\n    }\n  }\n\n  /**\n   * Fetches the current block header for the selected finality mode.\n   *\n   * @param mode - Optional finality mode. Defaults to irreversible blocks.\n   * @returns The Hive block header at the resolved current block number.\n   *\n   * @throws RPCError\n   * Thrown when the RPC node rejects either the properties or block-header call.\n   *\n   * @example\n   * ```ts\n   * const header = await client.blockchain.getCurrentBlockHeader()\n   * console.log(header.timestamp)\n   * ```\n   */\n  public async getCurrentBlockHeader(mode?: BlockchainMode) {\n    return this.client.database.getBlockHeader(await this.getCurrentBlockNum(mode));\n  }\n\n  /**\n   * Fetches the current block for the selected finality mode.\n   *\n   * @param mode - Optional finality mode. Defaults to irreversible blocks.\n   * @returns The signed block at the resolved current block number.\n   *\n   * @throws RPCError\n   * Thrown when the RPC node rejects either the properties or block call.\n   *\n   * @example\n   * ```ts\n   * const block = await client.blockchain.getCurrentBlock()\n   * console.log(block.transactions.length)\n   * ```\n   */\n  public async getCurrentBlock(mode?: BlockchainMode) {\n    return this.client.database.getBlock(await this.getCurrentBlockNum(mode));\n  }\n\n  /**\n   * Creates an async iterator that yields block numbers as they become available.\n   *\n   * @param options - Stream options, or a block number shorthand for `from`.\n   * @returns An async iterable of monotonically increasing block numbers.\n   *\n   * @remarks\n   * The iterator polls every three seconds, matching Hive block cadence. When\n   * `to` is omitted it continues indefinitely; when `from` is omitted it starts\n   * from the current block height for the selected mode.\n   *\n   * @throws Error\n   * Thrown when `from` is greater than the current block number.\n   * @throws RPCError\n   * Thrown when polling dynamic global properties fails.\n   *\n   * @example\n   * ```ts\n   * for await (const blockNum of client.blockchain.getBlockNumbers({\n   *   from: 90_000_000,\n   *   to: 90_000_005\n   * })) {\n   *   console.log(blockNum)\n   * }\n   * ```\n   */\n  public async *getBlockNumbers(options?: BlockchainStreamOptions | number) {\n    // const config = await this.client.database.getConfig()\n    // const interval = config['BLOCK_INTERVAL'] as number\n    const interval = 3;\n    if (!options) {\n      options = {};\n    } else if (typeof options === \"number\") {\n      options = { from: options };\n    }\n    let current = await this.getCurrentBlockNum(options.mode);\n    if (options.from !== undefined && options.from > current) {\n      throw new Error(`From can't be larger than current block num (${current})`);\n    }\n    let seen = options.from !== undefined ? options.from : current;\n    while (true) {\n      while (current > seen) {\n        yield seen++;\n        if (options.to !== undefined && seen > options.to) {\n          return;\n        }\n      }\n      await sleep(interval * 1000);\n      current = await this.getCurrentBlockNum(options.mode);\n    }\n  }\n\n  /**\n   * Creates a native Web ReadableStream of block numbers.\n   *\n   * @param options - Same options accepted by {@link getBlockNumbers}.\n   * @returns A stream backed by the async block-number iterator.\n   *\n   * @example\n   * ```ts\n   * const stream = client.blockchain.getBlockNumberStream(90_000_000)\n   * // Use native Web Stream API or async iteration\n   * for await (const blockNum of stream) {\n   *   console.log(blockNum)\n   * }\n   * ```\n   */\n  public getBlockNumberStream(options?: BlockchainStreamOptions | number) {\n    return iteratorStream(this.getBlockNumbers(options));\n  }\n\n  /**\n   * Creates an async iterator that yields full signed blocks.\n   *\n   * @param options - Same options accepted by {@link getBlockNumbers}.\n   * @returns An async iterable of Hive signed blocks.\n   *\n   * @throws RPCError\n   * Thrown when block-number polling or block retrieval fails.\n   *\n   * @example\n   * ```ts\n   * for await (const block of client.blockchain.getBlocks(90_000_000)) {\n   *   console.log(block.witness, block.transactions.length)\n   * }\n   * ```\n   */\n  public async *getBlocks(options?: BlockchainStreamOptions | number) {\n    for await (const num of this.getBlockNumbers(options)) {\n      yield await this.client.database.getBlock(num);\n    }\n  }\n\n  /**\n   * Creates a native Web ReadableStream of full signed blocks.\n   *\n   * @param options - Same options accepted by {@link getBlockNumbers}.\n   * @returns A stream backed by the async block iterator.\n   *\n   * @example\n   * ```ts\n   * const stream = client.blockchain.getBlockStream({ from: 90_000_000 })\n   * for await (const block of stream) {\n   *   console.log(block.block_id)\n   * }\n   * ```\n   */\n  public getBlockStream(options?: BlockchainStreamOptions | number) {\n    return iteratorStream(this.getBlocks(options));\n  }\n\n  /**\n   * Creates an async iterator that yields applied operations from each block.\n   *\n   * @param options - Same options accepted by {@link getBlockNumbers}.\n   * @returns An async iterable of applied operations in chain order.\n   *\n   * @remarks\n   * This is the most direct way to build an operation indexer. Pollen reads each\n   * block's operation list through `get_ops_in_block` and yields individual\n   * applied-operation records so callers can filter by operation type.\n   *\n   * @throws RPCError\n   * Thrown when block-number polling or operation retrieval fails.\n   *\n   * @example\n   * ```ts\n   * for await (const applied of client.blockchain.getOperations({\n   *   from: 90_000_000,\n   *   to: 90_000_010\n   * })) {\n   *   if (applied.op[0] === 'transfer') {\n   *     console.log(applied.op[1])\n   *   }\n   * }\n   * ```\n   */\n  public async *getOperations(options?: BlockchainStreamOptions | number) {\n    for await (const num of this.getBlockNumbers(options)) {\n      const operations = await this.client.database.getOperations(num);\n      for (const operation of operations) {\n        yield operation;\n      }\n    }\n  }\n\n  /**\n   * Creates a native Web ReadableStream of applied operations.\n   *\n   * @param options - Same options accepted by {@link getBlockNumbers}.\n   * @returns A stream backed by the async operation iterator.\n   *\n   * @example\n   * ```ts\n   * const stream = client.blockchain.getOperationsStream({ from: 90_000_000 })\n   * for await (const applied of stream) {\n   *   console.log(applied.op[0])\n   * }\n   * ```\n   */\n  public getOperationsStream(options?: BlockchainStreamOptions | number) {\n    return iteratorStream(this.getOperations(options));\n  }\n}\n", "/**\n * @file Hive account type definitions.\n * @author Johan Nordberg <code@johan-nordberg.com>\n * @license\n * Copyright (c) 2017 Johan Nordberg. All Rights Reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n *  1. Redistribution of source code must retain the above copyright notice, this\n *     list of conditions and the following disclaimer.\n *\n *  2. Redistribution in binary form must reproduce the above copyright notice,\n *     this list of conditions and the following disclaimer in the documentation\n *     and/or other materials provided with the distribution.\n *\n *  3. Neither the name of the copyright holder nor the names of its contributors\n *     may be used to endorse or promote products derived from this software without\n *     specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * You acknowledge that this software is not designed, licensed or intended for use\n * in the design, construction, operation or maintenance of any military facility.\n */\n\nimport { PublicKey } from \"../crypto.js\";\nimport { Asset } from \"./asset.js\";\nimport { AppliedOperation } from \"./operation.js\";\n\n/**\n * Raw Hive authority object.\n *\n * @remarks\n * Hive authorities combine weighted account references and public-key\n * references. A transaction is authorized when collected signatures and nested\n * authorities meet `weight_threshold`.\n *\n * @example\n * ```ts\n * const authority: AuthorityType = {\n *   weight_threshold: 1,\n *   account_auths: [],\n *   key_auths: [[publicKey, 1]]\n * }\n * ```\n */\nexport interface AuthorityType {\n  weight_threshold: number; // uint32_t\n  account_auths: [string, number][]; // flat_map< account_name_type, uint16_t >\n  key_auths: [string | PublicKey, number][]; // flat_map< public_key_type, uint16_t >\n}\n\n/**\n * Convenience wrapper for Hive owner, active, and posting authorities.\n *\n * @remarks\n * `Authority` can be created from a single public key for simple one-signature\n * accounts or from a full weighted authority object for multisig setups.\n *\n * @example\n * ```ts\n * const posting = Authority.from(postingPublicKey)\n * ```\n */\nexport class Authority implements AuthorityType {\n  public weight_threshold: number;\n  public account_auths: [string, number][];\n  public key_auths: [string | PublicKey, number][];\n\n  /**\n   * Creates an authority from explicit threshold and auth lists.\n   *\n   * @param authority - Raw authority fields from Hive.\n   */\n  constructor({ weight_threshold, account_auths, key_auths }: AuthorityType) {\n    this.weight_threshold = weight_threshold;\n    this.account_auths = account_auths;\n    this.key_auths = key_auths;\n  }\n\n  /**\n   * Normalizes a public key or raw authority into an {@link Authority}.\n   *\n   * @param value - Public key string, {@link PublicKey}, existing authority, or\n   * raw authority object.\n   * @returns A normalized authority.\n   *\n   * @example\n   * ```ts\n   * const authority = Authority.from('STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA')\n   * ```\n   */\n  public static from(value: string | PublicKey | AuthorityType) {\n    if (value instanceof Authority) {\n      return value;\n    } else if (typeof value === \"string\" || value instanceof PublicKey) {\n      return new Authority({\n        account_auths: [],\n        key_auths: [[value, 1]],\n        weight_threshold: 1,\n      });\n    } else {\n      return new Authority(value);\n    }\n  }\n}\n\n/**\n * Core Hive account object returned by condenser account lookups.\n *\n * @remarks\n * This shape includes authority keys, balances, savings balances, vesting\n * state, voting state, recovery metadata, and historical counters. Use\n * {@link ExtendedAccount} when condenser returns augmented social/history\n * fields.\n *\n * @example\n * ```ts\n * const [account] = await client.database.getAccounts(['srbde'])\n * console.log(account.balance, account.vesting_shares)\n * ```\n */\nexport interface Account {\n  id: number; // account_id_type\n  name: string; // account_name_type\n  owner: Authority;\n  active: Authority;\n  posting: Authority;\n  memo_key: string; // public_key_type\n  json_metadata: string;\n  posting_json_metadata: string;\n  proxy: string; // account_name_type\n  last_owner_update: string; // time_point_sec\n  last_account_update: string; // time_point_sec\n  created: string; // time_point_sec\n  mined: boolean;\n  owner_challenged: boolean;\n  active_challenged: boolean;\n  last_owner_proved: string; // time_point_sec\n  last_active_proved: string; // time_point_sec\n  recovery_account: string; // account_name_type\n  reset_account: string; // account_name_type\n  last_account_recovery: string; // time_point_sec\n  comment_count: number; // uint32_t\n  lifetime_vote_count: number; // uint32_t\n  post_count: number; // uint32_t\n  can_vote: boolean;\n  voting_power: number; // uint16_t\n  last_vote_time: string; // time_point_sec\n  voting_manabar: {\n    current_mana: string | number;\n    last_update_time: number;\n  };\n  balance: string | Asset;\n  savings_balance: string | Asset;\n  hbd_balance: string | Asset;\n  hbd_seconds: string; // uint128_t\n  hbd_seconds_last_update: string; // time_point_sec\n  hbd_last_interest_payment: string; // time_point_sec\n  savings_hbd_balance: string | Asset; // asset\n  savings_hbd_seconds: string; // uint128_t\n  savings_hbd_seconds_last_update: string; // time_point_sec\n  savings_hbd_last_interest_payment: string; // time_point_sec\n  savings_withdraw_requests: number; // uint8_t\n  reward_hbd_balance: string | Asset;\n  reward_hive_balance: string | Asset;\n  reward_vesting_balance: string | Asset;\n  reward_vesting_hive: string | Asset;\n  curation_rewards: number | string; // share_type\n  posting_rewards: number | string; // share_type\n  vesting_shares: string | Asset;\n  delegated_vesting_shares: string | Asset;\n  received_vesting_shares: string | Asset;\n  vesting_withdraw_rate: string | Asset;\n  next_vesting_withdrawal: string; // time_point_sec\n  withdrawn: number | string; // share_type\n  to_withdraw: number | string; // share_type\n  withdraw_routes: number; // uint16_t\n  proxied_vsf_votes: number[]; // vector< share_type >\n  witnesses_voted_for: number; // uint16_t\n  average_bandwidth: number | string; // share_type\n  lifetime_bandwidth: number | string; // share_type\n  last_bandwidth_update: string; // time_point_sec\n  average_market_bandwidth: number | string; // share_type\n  lifetime_market_bandwidth: number | string; // share_type\n  last_market_bandwidth_update: string; // time_point_sec\n  last_post: string; // time_point_sec\n  last_root_post: string; // time_point_sec\n}\n\n/**\n * Augmented account object returned by condenser `get_accounts`.\n *\n * @remarks\n * Extended accounts add reputation, converted vesting balance, witness votes,\n * and several legacy history collections used by social applications.\n *\n * @example\n * ```ts\n * const [account] = await client.database.getAccounts(['srbde'])\n * console.log(account.reputation, account.witness_votes)\n * ```\n */\nexport interface ExtendedAccount extends Account {\n  /**\n   * Vesting shares converted to vesting HIVE for display.\n   */\n  vesting_balance: string | Asset;\n  reputation: string | number; // share_type\n  /**\n   * Transfer and vesting operation history.\n   */\n  transfer_history: [number, AppliedOperation][]; // map<uint64_t,applied_operation>\n  /**\n   * Limit order, cancel, and fill history.\n   */\n  market_history: [number, AppliedOperation][]; // map<uint64_t,applied_operation>\n  post_history: [number, AppliedOperation][]; // map<uint64_t,applied_operation>\n  vote_history: [number, AppliedOperation][]; // map<uint64_t,applied_operation>\n  other_history: [number, AppliedOperation][]; // map<uint64_t,applied_operation>\n  witness_votes: string[]; // set<string>\n  tags_usage: string[]; // vector<pair<string,uint32_t>>\n  guest_bloggers: string[]; // vector<pair<account_name_type,uint32_t>>\n  open_orders?: unknown[]; // optional<map<uint32_t,extended_limit_order>>\n  comments?: string[]; // / permlinks for this user // optional<vector<string>>\n  blog?: string[]; // / blog posts for this user // optional<vector<string>>\n  feed?: string[]; // / feed posts for this user // optional<vector<string>>\n  recent_replies?: string[]; // / blog posts for this user // optional<vector<string>>\n  recommended?: string[]; // / posts recommened for this user // optional<vector<string>>\n}\n", "/**\n * @file Hive asset type definitions and helpers.\n * @author Johan Nordberg <code@johan-nordberg.com>\n * @license\n * Copyright (c) 2017 Johan Nordberg. All Rights Reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n *  1. Redistribution of source code must retain the above copyright notice, this\n *     list of conditions and the following disclaimer.\n *\n *  2. Redistribution in binary form must reproduce the above copyright notice,\n *     this list of conditions and the following disclaimer in the documentation\n *     and/or other materials provided with the distribution.\n *\n *  3. Neither the name of the copyright holder nor the names of its contributors\n *     may be used to endorse or promote products derived from this software without\n *     specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * You acknowledge that this software is not designed, licensed or intended for use\n * in the design, construction, operation or maintenance of any military facility.\n */\n\nimport { assert } from \"../utils.js\";\n\nexport interface SMTAsset {\n  /**\n   * Integer amount in the token's smallest precision unit.\n   */\n  amount: string | number;\n  /**\n   * Number of decimal places used by the token.\n   */\n  precision: number;\n  /**\n   * Numeric asset identifier assigned by Hive's SMT protocol.\n   */\n  nai: string;\n}\n\n/**\n * Asset symbol supported by Hive-compatible asset serialization.\n *\n * @example\n * ```ts\n * const symbol: AssetSymbol = 'HIVE'\n * ```\n */\nexport type AssetSymbol = \"HIVE\" | \"VESTS\" | \"HBD\" | \"TESTS\" | \"TBD\" | \"STEEM\" | \"SBD\";\n\n/**\n * Immutable representation of a Hive asset amount and symbol.\n *\n * @remarks\n * Hive serializes liquid assets at three decimal places and VESTS at six.\n * `Asset` keeps arithmetic symbol-aware so accidental HIVE/HBD/VESTS mixing is\n * caught before a transaction is signed.\n *\n * @example\n * ```ts\n * const balance = Asset.from('12.345 HIVE')\n * const payout = balance.add('1.000 HIVE')\n *\n * console.log(payout.toString())\n * ```\n */\nexport class Asset {\n  /**\n   * Creates an asset from an amount and symbol.\n   *\n   * @param amount - Numeric amount in display units.\n   * @param symbol - Hive asset symbol.\n   */\n  constructor(\n    public readonly amount: number,\n    public readonly symbol: AssetSymbol,\n  ) {}\n\n  /**\n   * Parses a Hive asset string.\n   *\n   * @param string - Asset string such as `42.000 HIVE`.\n   * @param expectedSymbol - Optional symbol guard.\n   * @returns A parsed {@link Asset}.\n   *\n   * @throws Error\n   * Thrown when the string has an unsupported symbol, a non-numeric amount, or\n   * a symbol that does not match `expectedSymbol`.\n   *\n   * @example\n   * ```ts\n   * const amount = Asset.fromString('42.000 HIVE', 'HIVE')\n   * ```\n   */\n  public static fromString(string: string, expectedSymbol?: AssetSymbol) {\n    const [amountString, symbol] = string.split(\" \");\n    if (![\"HIVE\", \"VESTS\", \"HBD\", \"TESTS\", \"TBD\", \"SBD\", \"STEEM\"].includes(symbol)) {\n      throw new Error(`Invalid asset symbol: ${symbol}`);\n    }\n    if (expectedSymbol && symbol !== expectedSymbol) {\n      throw new Error(`Invalid asset, expected symbol: ${expectedSymbol} got: ${symbol}`);\n    }\n    const amount = Number.parseFloat(amountString);\n    if (!Number.isFinite(amount)) {\n      throw new Error(`Invalid asset amount: ${amountString}`);\n    }\n    return new Asset(amount, symbol as AssetSymbol);\n  }\n\n  /**\n   * Normalizes an asset-like value into an {@link Asset}.\n   *\n   * @param value - Asset instance, asset string, or numeric amount.\n   * @param symbol - Symbol to use for numeric values and to validate asset\n   * strings or existing instances.\n   * @returns A normalized asset.\n   *\n   * @throws Error\n   * Thrown when the value cannot be parsed or fails the symbol guard.\n   *\n   * @example\n   * ```ts\n   * const fee = Asset.from(3, 'HIVE')\n   * const balance = Asset.from('10.000 HBD', 'HBD')\n   * ```\n   */\n  public static from(value: string | Asset | number, symbol?: AssetSymbol) {\n    if (value instanceof Asset) {\n      if (symbol && value.symbol !== symbol) {\n        throw new Error(`Invalid asset, expected symbol: ${symbol} got: ${value.symbol}`);\n      }\n      return value;\n    } else if (typeof value === \"number\" && Number.isFinite(value)) {\n      return new Asset(value, symbol || \"STEEM\");\n    } else if (typeof value === \"string\") {\n      return Asset.fromString(value, symbol);\n    } else {\n      throw new Error(`Invalid asset '${String(value)}'`);\n    }\n  }\n\n  /**\n   * Returns the smaller of two same-symbol assets.\n   *\n   * @param a - First asset.\n   * @param b - Second asset.\n   * @returns The asset with the lower amount.\n   *\n   * @throws AssertionError\n   * Thrown when the two assets use different symbols.\n   *\n   * @example\n   * ```ts\n   * const capped = Asset.min(requested, available)\n   * ```\n   */\n  public static min(a: Asset, b: Asset) {\n    assert(a.symbol === b.symbol, \"can not compare assets with different symbols\");\n    return a.amount < b.amount ? a : b;\n  }\n\n  /**\n   * Returns the larger of two same-symbol assets.\n   *\n   * @param a - First asset.\n   * @param b - Second asset.\n   * @returns The asset with the higher amount.\n   *\n   * @throws AssertionError\n   * Thrown when the two assets use different symbols.\n   *\n   * @example\n   * ```ts\n   * const required = Asset.max(minimumFee, offeredFee)\n   * ```\n   */\n  public static max(a: Asset, b: Asset) {\n    assert(a.symbol === b.symbol, \"can not compare assets with different symbols\");\n    return a.amount > b.amount ? a : b;\n  }\n\n  /**\n   * Resolves the display precision for this asset symbol.\n   *\n   * @returns `3` for liquid Hive-family assets and `6` for VESTS.\n   *\n   * @example\n   * ```ts\n   * Asset.from('1.000000 VESTS').getPrecision()\n   * ```\n   */\n  public getPrecision(): number {\n    switch (this.symbol) {\n      case \"TESTS\":\n      case \"TBD\":\n      case \"HIVE\":\n      case \"HBD\":\n      case \"SBD\":\n      case \"STEEM\":\n        return 3;\n      case \"VESTS\":\n        return 6;\n    }\n  }\n\n  /**\n   * Converts display Hive symbols to protocol serialization symbols.\n   *\n   * @returns An asset using `STEEM` for `HIVE` and `SBD` for `HBD`, or this\n   * asset unchanged for symbols that already serialize directly.\n   *\n   * @remarks\n   * Hive inherited protocol-level asset symbols from Steem. Pollen keeps public\n   * APIs Hive-native while mapping to legacy wire symbols during serialization.\n   *\n   * @example\n   * ```ts\n   * const wireAsset = Asset.from('1.000 HIVE').steem_symbols()\n   * console.log(wireAsset.toString()) // 1.000 STEEM\n   * ```\n   */\n  public steem_symbols(): Asset {\n    switch (this.symbol) {\n      case \"HIVE\":\n        return Asset.from(this.amount, \"STEEM\");\n      case \"HBD\":\n        return Asset.from(this.amount, \"SBD\");\n      default:\n        return this;\n    }\n  }\n\n  /**\n   * Renders the asset using Hive display precision.\n   *\n   * @returns Asset string such as `42.000 HIVE`.\n   *\n   * @example\n   * ```ts\n   * Asset.from(42, 'HIVE').toString()\n   * ```\n   */\n  public toString(): string {\n    return `${this.amount.toFixed(this.getPrecision())} ${this.symbol}`;\n  }\n\n  /**\n   * Adds another amount with the same symbol.\n   *\n   * @param amount - Asset-like amount to add.\n   * @returns A new asset containing the sum.\n   *\n   * @throws AssertionError\n   * Thrown when `amount` uses a different symbol.\n   *\n   * @example\n   * ```ts\n   * const total = Asset.from('1.000 HIVE').add('2.500 HIVE')\n   * ```\n   */\n  public add(amount: Asset | string | number): Asset {\n    const other = Asset.from(amount, this.symbol);\n    assert(this.symbol === other.symbol, \"can not add with different symbols\");\n    return new Asset(this.amount + other.amount, this.symbol);\n  }\n\n  /**\n   * Subtracts another amount with the same symbol.\n   *\n   * @param amount - Asset-like amount to subtract.\n   * @returns A new asset containing the difference.\n   *\n   * @throws AssertionError\n   * Thrown when `amount` uses a different symbol.\n   *\n   * @example\n   * ```ts\n   * const remaining = Asset.from('5.000 HIVE').subtract('1.250 HIVE')\n   * ```\n   */\n  public subtract(amount: Asset | string | number): Asset {\n    const other = Asset.from(amount, this.symbol);\n    assert(this.symbol === other.symbol, \"can not subtract with different symbols\");\n    return new Asset(this.amount - other.amount, this.symbol);\n  }\n\n  /**\n   * Multiplies this asset amount by another same-symbol amount.\n   *\n   * @param factor - Asset-like factor.\n   * @returns A new asset containing the product.\n   *\n   * @throws AssertionError\n   * Thrown when `factor` uses a different symbol.\n   *\n   * @example\n   * ```ts\n   * const doubled = Asset.from('2.000 HIVE').multiply('2.000 HIVE')\n   * ```\n   */\n  public multiply(factor: Asset | string | number): Asset {\n    const other = Asset.from(factor, this.symbol);\n    assert(this.symbol === other.symbol, \"can not multiply with different symbols\");\n    return new Asset(this.amount * other.amount, this.symbol);\n  }\n\n  /**\n   * Divides this asset amount by another same-symbol amount.\n   *\n   * @param divisor - Asset-like divisor.\n   * @returns A new asset containing the quotient.\n   *\n   * @throws AssertionError\n   * Thrown when `divisor` uses a different symbol.\n   *\n   * @example\n   * ```ts\n   * const half = Asset.from('2.000 HIVE').divide('2.000 HIVE')\n   * ```\n   */\n  public divide(divisor: Asset | string | number): Asset {\n    const other = Asset.from(divisor, this.symbol);\n    assert(this.symbol === other.symbol, \"can not divide with different symbols\");\n    return new Asset(this.amount / other.amount, this.symbol);\n  }\n\n  /**\n   * For JSON serialization, same as toString().\n   */\n  public toJSON(): string {\n    return this.toString();\n  }\n}\n\n/**\n * Value accepted anywhere Pollen needs a Hive price ratio.\n *\n * @example\n * ```ts\n * const feed: PriceType = {\n *   base: '1.000 HIVE',\n *   quote: '0.300 HBD'\n * }\n * ```\n */\nexport type PriceType = Price | { base: Asset | string; quote: Asset | string };\n\n/**\n * Price ratio between two different Hive assets.\n *\n * @remarks\n * `Price` behaves like a currency pair: `base` is expressed relative to\n * `quote`. Witness feeds commonly describe how much HBD one HIVE is worth.\n *\n * @example\n * ```ts\n * const price = Price.from({\n *   base: '1.000 HIVE',\n *   quote: '0.300 HBD'\n * })\n *\n * const hbd = price.convert(Asset.from('10.000 HIVE'))\n * ```\n */\nexport class Price {\n  /**\n   * Creates a price ratio from non-zero base and quote assets.\n   *\n   * @param base - Asset being priced.\n   * @param quote - Relative asset used to express the price.\n   *\n   * @throws AssertionError\n   * Thrown when either amount is zero or both assets use the same symbol.\n   *\n   * @example\n   * ```ts\n   * const price = new Price(Asset.from('1.000 HIVE'), Asset.from('0.300 HBD'))\n   * ```\n   */\n  constructor(\n    public readonly base: Asset,\n    public readonly quote: Asset,\n  ) {\n    assert(base.amount !== 0 && quote.amount !== 0, \"base and quote assets must be non-zero\");\n    assert(base.symbol !== quote.symbol, \"base and quote can not have the same symbol\");\n  }\n\n  /**\n   * Normalizes a price-like value into a {@link Price}.\n   *\n   * @param value - Existing price or object containing base and quote assets.\n   * @returns A normalized price.\n   *\n   * @example\n   * ```ts\n   * const price = Price.from({ base: '1.000 HIVE', quote: '0.300 HBD' })\n   * ```\n   */\n  public static from(value: PriceType) {\n    if (value instanceof Price) {\n      return value;\n    } else {\n      return new Price(Asset.from(value.base), Asset.from(value.quote));\n    }\n  }\n\n  /**\n   * Renders the price pair.\n   *\n   * @returns String in `base:quote` form.\n   *\n   * @example\n   * ```ts\n   * price.toString()\n   * ```\n   */\n  public toString() {\n    return `${this.base}:${this.quote}`;\n  }\n\n  /**\n   * Converts an asset between the price pair's two symbols.\n   *\n   * @param asset - Asset using either the base or quote symbol.\n   * @returns Converted asset using the opposite symbol.\n   *\n   * @throws Error\n   * Thrown when `asset.symbol` is not part of this price pair.\n   *\n   * @example\n   * ```ts\n   * const hbd = price.convert(Asset.from('10.000 HIVE'))\n   * ```\n   */\n  public convert(asset: Asset) {\n    if (asset.symbol === this.base.symbol) {\n      assert(this.base.amount > 0);\n      return new Asset((asset.amount * this.quote.amount) / this.base.amount, this.quote.symbol);\n    } else if (asset.symbol === this.quote.symbol) {\n      assert(this.quote.amount > 0);\n      return new Asset((asset.amount * this.base.amount) / this.quote.amount, this.base.symbol);\n    } else {\n      throw new Error(`Can not convert ${asset} with ${this}`);\n    }\n  }\n}\n", "/**\n * @file Broadcast API helpers.\n * @author Johan Nordberg <code@johan-nordberg.com>\n * @license\n * Copyright (c) 2017 Johan Nordberg. All Rights Reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n *  1. Redistribution of source code must retain the above copyright notice, this\n *     list of conditions and the following disclaimer.\n *\n *  2. Redistribution in binary form must reproduce the above copyright notice,\n *     this list of conditions and the following disclaimer in the documentation\n *     and/or other materials provided with the distribution.\n *\n *  3. Neither the name of the copyright holder nor the names of its contributors\n *     may be used to endorse or promote products derived from this software without\n *     specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * You acknowledge that this software is not designed, licensed or intended for use\n * in the design, construction, operation or maintenance of any military facility.\n */\n\nimport { assert, fromHex } from \"./../utils.js\";\n\nimport { Authority, AuthorityType } from \"../chain/account.js\";\nimport { Asset } from \"../chain/asset.js\";\nimport {\n  AccountUpdateOperation,\n  ClaimAccountOperation,\n  CommentOperation,\n  CommentOptionsOperation,\n  CreateClaimedAccountOperation,\n  CustomJsonOperation,\n  DelegateVestingSharesOperation,\n  Operation,\n  TransferOperation,\n  VoteOperation,\n} from \"../chain/operation.js\";\nimport { SignedTransaction, Transaction, TransactionConfirmation } from \"../chain/transaction.js\";\nimport { Client } from \"./../client.js\";\nimport { cryptoUtils, PrivateKey, PublicKey } from \"./../crypto.js\";\n\n/**\n * Options used by {@link BroadcastAPI.createTestAccount}.\n *\n * @remarks\n * Tests can either provide a master password, letting Pollen derive role keys\n * with Hive's login convention, or provide explicit authorities for deterministic\n * account fixtures.\n *\n * @example\n * ```ts\n * const options: CreateAccountOptions = {\n *   username: 'pollen-dev',\n *   password: 'correct horse battery staple',\n *   creator: 'initminer',\n *   metadata: { app: 'pollen-tests' }\n * }\n * ```\n */\nexport interface CreateAccountOptions {\n  /**\n   * Username for the new account.\n   */\n  username: string;\n  /**\n   * Password for the new account, if set, all keys will be derived from this.\n   */\n  password?: string;\n  /**\n   * Account authorities, used to manually set account keys.\n   * Can not be used together with the password option.\n   */\n  auths?: {\n    owner: AuthorityType | string | PublicKey;\n    active: AuthorityType | string | PublicKey;\n    posting: AuthorityType | string | PublicKey;\n    memoKey: PublicKey | string;\n  };\n  /**\n   * Creator account, fee will be deducted from this and the key to sign\n   * the transaction must be the creators active key.\n   */\n  creator: string;\n  /**\n   * Account creation fee. If omitted fee will be set to lowest possible.\n   */\n  fee?: string | Asset | number;\n  /**\n   * Account delegation, amount of VESTS to delegate to the new account.\n   * If omitted the delegation amount will be the lowest possible based\n   * on the fee. Can be set to zero to disable delegation.\n   */\n  delegation?: string | Asset | number;\n  /**\n   * Optional account meta-data.\n   */\n  metadata?: { [key: string]: any };\n}\n\n/**\n * Helper for signing and broadcasting Hive operations.\n *\n * @remarks\n * `BroadcastAPI` turns typed operation payloads into signed Hive transactions,\n * derives TAPOS reference fields from the current head block, and submits the\n * signed transaction through the configured client. Signing uses Pollen's Noble\n * secp256k1-backed crypto layer through {@link cryptoUtils} for modern audited\n * primitives.\n *\n * @example\n * ```ts\n * import { Client, PrivateKey } from '@srbde/pollen'\n *\n * const client = new Client('https://api.hive.blog')\n * const key = PrivateKey.fromString(process.env.HIVE_ACTIVE_KEY!)\n *\n * const confirmation = await client.broadcast.transfer(\n *   {\n *     from: 'srbde',\n *     to: 'alice',\n *     amount: '0.001 HIVE',\n *     memo: 'Pollen transfer'\n *   },\n *   key\n * )\n *\n * console.log(confirmation.id)\n * ```\n *\n * @see {@link cryptoUtils.signTransaction}\n * @see {@link Client.call}\n */\nexport class BroadcastAPI {\n  /**\n   * How many milliseconds in the future to set the expiry time to when\n   * broadcasting a transaction, defaults to 1 minute.\n   */\n  public expireTime = 60 * 1000;\n\n  /**\n   * Creates a broadcast helper bound to a client.\n   *\n   * @param client - Client used for chain-property reads and transaction\n   * submission.\n   */\n  constructor(readonly client: Client) {}\n\n  /**\n   * Broadcasts a Hive `comment` operation.\n   *\n   * @param comment - Comment payload. Empty `parent_author` creates a top-level\n   * post; a populated `parent_author` creates a reply.\n   * @param key - Private posting key for `comment.author`.\n   * @returns Transaction confirmation containing the generated transaction id.\n   *\n   * @throws RPCError\n   * Thrown when the node rejects the transaction, the posting authority is\n   * missing, or the comment payload violates chain rules.\n   *\n   * @example\n   * ```ts\n   * await client.broadcast.comment(\n   *   {\n   *     parent_author: '',\n   *     parent_permlink: 'hive-139531',\n   *     author: 'srbde',\n   *     permlink: 'hello-pollen',\n   *     title: 'Hello Pollen',\n   *     body: 'Published through the Pollen SDK.',\n   *     json_metadata: JSON.stringify({ tags: ['hive-139531'] })\n   *   },\n   *   postingKey\n   * )\n   * ```\n   */\n  public async comment(comment: CommentOperation[1], key: PrivateKey) {\n    const op: Operation = [\"comment\", comment];\n    return this.sendOperations([op], key);\n  }\n\n  /**\n   * Broadcasts a comment together with its payout and beneficiary options.\n   *\n   * @param comment - Comment or post payload.\n   * @param options - Matching `comment_options` payload for the same author and\n   * permlink.\n   * @param key - Private posting key for the comment author.\n   * @returns Transaction confirmation containing the generated transaction id.\n   *\n   * @remarks\n   * Sending both operations in one transaction prevents a post from briefly\n   * existing with default payout settings.\n   *\n   * @throws RPCError\n   * Thrown when either operation fails chain validation.\n   *\n   * @example\n   * ```ts\n   * await client.broadcast.commentWithOptions(comment, {\n   *   author: comment.author,\n   *   permlink: comment.permlink,\n   *   max_accepted_payout: '1000000.000 HBD',\n   *   percent_hbd: 10000,\n   *   allow_votes: true,\n   *   allow_curation_rewards: true,\n   *   extensions: []\n   * }, postingKey)\n   * ```\n   */\n  public async commentWithOptions(\n    comment: CommentOperation[1],\n    options: CommentOptionsOperation[1],\n    key: PrivateKey,\n  ) {\n    const ops: Operation[] = [\n      [\"comment\", comment],\n      [\"comment_options\", options],\n    ];\n    return this.sendOperations(ops, key);\n  }\n\n  /**\n   * Broadcasts a vote operation.\n   *\n   * @param vote - Vote payload including voter, author, permlink, and weight.\n   * @param key - Private posting key for `vote.voter`.\n   * @returns Transaction confirmation containing the generated transaction id.\n   *\n   * @throws RPCError\n   * Thrown when the vote is outside chain limits or the posting authority is\n   * invalid.\n   *\n   * @example\n   * ```ts\n   * await client.broadcast.vote(\n   *   {\n   *     voter: 'srbde',\n   *     author: 'alice',\n   *     permlink: 'field-notes',\n   *     weight: 10_000\n   *   },\n   *   postingKey\n   * )\n   * ```\n   */\n  public async vote(vote: VoteOperation[1], key: PrivateKey) {\n    const op: Operation = [\"vote\", vote];\n    return this.sendOperations([op], key);\n  }\n\n  /**\n   * Broadcasts a liquid HIVE or HBD transfer.\n   *\n   * @param data - Transfer payload with sender, recipient, amount, and memo.\n   * @param key - Private active key for `data.from`.\n   * @returns Transaction confirmation containing the generated transaction id.\n   *\n   * @throws RPCError\n   * Thrown when the sender lacks funds, active authority is missing, or the node\n   * rejects the transaction.\n   *\n   * @example\n   * ```ts\n   * await client.broadcast.transfer(\n   *   {\n   *     from: 'srbde',\n   *     to: 'alice',\n   *     amount: '1.000 HIVE',\n   *     memo: 'Invoice 42'\n   *   },\n   *   activeKey\n   * )\n   * ```\n   */\n  public async transfer(data: TransferOperation[1], key: PrivateKey) {\n    const op: Operation = [\"transfer\", data];\n    return this.sendOperations([op], key);\n  }\n\n  /**\n   * Broadcasts a `custom_json` operation for application-level protocols.\n   *\n   * @param data - Custom JSON payload, including id, required authorities, and\n   * serialized JSON string.\n   * @param key - Private posting or active key matching the required authority\n   * arrays.\n   * @returns Transaction confirmation containing the generated transaction id.\n   *\n   * @throws RPCError\n   * Thrown when authority requirements are not met or the payload is invalid.\n   *\n   * @example\n   * ```ts\n   * await client.broadcast.json(\n   *   {\n   *     required_auths: [],\n   *     required_posting_auths: ['srbde'],\n   *     id: 'pollen.demo',\n   *     json: JSON.stringify({ nectar: 'ready' })\n   *   },\n   *   postingKey\n   * )\n   * ```\n   */\n  public async json(data: CustomJsonOperation[1], key: PrivateKey) {\n    const op: Operation = [\"custom_json\", data];\n    return this.sendOperations([op], key);\n  }\n\n  /**\n   * Creates and optionally delegates to a new account in test environments.\n   *\n   * @param options - New account name, authority source, creator, fee, optional\n   * delegation, and metadata.\n   * @param key - Private active key for `options.creator`.\n   * @returns Transaction confirmation for the claim/create/delegate transaction.\n   *\n   * @remarks\n   * This helper is intentionally guarded for test suites. It can derive owner,\n   * active, posting, and memo keys from a password or accept explicit authority\n   * objects when tests need deterministic key material.\n   *\n   * @throws AssertionError\n   * Thrown when called outside a Mocha-style test environment.\n   * @throws Error\n   * Thrown when neither `password` nor `auths` is supplied, or when the provided\n   * account-creation fee does not match chain properties.\n   * @throws RPCError\n   * Thrown when the chain rejects the account creation transaction.\n   *\n   * @example\n   * ```ts\n   * await testnet.broadcast.createTestAccount(\n   *   {\n   *     username: 'pollen-dev',\n   *     password: 'correct horse battery staple',\n   *     creator: 'initminer',\n   *     metadata: { app: 'pollen-tests' }\n   *   },\n   *   initminerActiveKey\n   * )\n   * ```\n   */\n  public async createTestAccount(options: CreateAccountOptions, key: PrivateKey) {\n    assert(global.hasOwnProperty(\"it\"), \"helper to be used only for mocha tests\");\n\n    const { username, metadata, creator } = options;\n\n    const prefix = this.client.addressPrefix;\n    let owner: Authority, active: Authority, posting: Authority, memo_key: PublicKey;\n    if (options.password) {\n      const ownerKey = PrivateKey.fromLogin(username, options.password, \"owner\").createPublic(\n        prefix,\n      );\n      owner = Authority.from(ownerKey);\n      const activeKey = PrivateKey.fromLogin(username, options.password, \"active\").createPublic(\n        prefix,\n      );\n      active = Authority.from(activeKey);\n      const postingKey = PrivateKey.fromLogin(username, options.password, \"posting\").createPublic(\n        prefix,\n      );\n      posting = Authority.from(postingKey);\n      memo_key = PrivateKey.fromLogin(username, options.password, \"memo\").createPublic(prefix);\n    } else if (options.auths) {\n      owner = Authority.from(options.auths.owner);\n      active = Authority.from(options.auths.active);\n      posting = Authority.from(options.auths.posting);\n      memo_key = PublicKey.from(options.auths.memoKey);\n    } else {\n      throw new Error(\"Must specify either password or auths\");\n    }\n\n    let { fee, delegation } = options;\n\n    const symbol = prefix === \"STM\" ? \"HIVE\" : \"TESTS\";\n    delegation = Asset.from(delegation || 0, \"VESTS\");\n    fee = Asset.from(fee || 0, symbol);\n\n    if (fee.amount > 0) {\n      const chainProps = await this.client.database.getChainProperties();\n      const creationFee = Asset.from(chainProps.account_creation_fee);\n      if (fee.amount !== creationFee.amount) {\n        throw new Error(\"Fee must be exactly \" + creationFee.toString());\n      }\n    }\n\n    const claim_op: ClaimAccountOperation = [\n      \"claim_account\",\n      {\n        creator,\n        extensions: [],\n        fee,\n      },\n    ];\n\n    const create_op: CreateClaimedAccountOperation = [\n      \"create_claimed_account\",\n      {\n        active,\n        creator,\n        extensions: [],\n        json_metadata: metadata ? JSON.stringify(metadata) : \"\",\n        memo_key,\n        new_account_name: username,\n        owner,\n        posting,\n      },\n    ];\n\n    const ops: any[] = [claim_op, create_op];\n\n    if (delegation.amount > 0) {\n      const delegate_op: DelegateVestingSharesOperation = [\n        \"delegate_vesting_shares\",\n        {\n          delegatee: username,\n          delegator: creator,\n          vesting_shares: delegation,\n        },\n      ];\n      ops.push(delegate_op);\n    }\n\n    return this.sendOperations(ops, key);\n  }\n\n  /**\n   * Broadcasts an `account_update` operation.\n   *\n   * @param data - Account update payload, including optional authorities,\n   * memo key, and JSON metadata.\n   * @param key - Private key with sufficient authority for the fields being\n   * changed.\n   * @returns Transaction confirmation containing the generated transaction id.\n   *\n   * @throws RPCError\n   * Thrown when the update lacks required authority or violates account rules.\n   *\n   * @example\n   * ```ts\n   * await client.broadcast.updateAccount(\n   *   {\n   *     account: 'srbde',\n   *     memo_key: memoPublicKey,\n   *     json_metadata: JSON.stringify({ profile: { name: 'SRBDE' } }),\n   *     owner: undefined,\n   *     active: undefined,\n   *     posting: undefined\n   *   },\n   *   activeKey\n   * )\n   * ```\n   */\n  public async updateAccount(data: AccountUpdateOperation[1], key: PrivateKey) {\n    const op: Operation = [\"account_update\", data];\n    return this.sendOperations([op], key);\n  }\n\n  /**\n   * Delegates vesting shares from one account to another.\n   *\n   * @param options - Delegation payload containing delegator, delegatee, and\n   * vesting share amount.\n   * @param key - Private active key for `options.delegator`.\n   * @returns Transaction confirmation containing the generated transaction id.\n   *\n   * @remarks\n   * Delegated VESTS remain owned by the delegator, but voting influence and\n   * resource capacity move to the delegatee. Setting `vesting_shares` to zero\n   * removes the delegation; removed shares enter the protocol cooldown period\n   * before they can vote again.\n   *\n   * @throws RPCError\n   * Thrown when the delegator lacks active authority, the asset is invalid, or\n   * the chain rejects the delegation.\n   *\n   * @example\n   * ```ts\n   * await client.broadcast.delegateVestingShares(\n   *   {\n   *     delegator: 'srbde',\n   *     delegatee: 'alice',\n   *     vesting_shares: '100.000000 VESTS'\n   *   },\n   *   activeKey\n   * )\n   * ```\n   */\n  public async delegateVestingShares(options: DelegateVestingSharesOperation[1], key: PrivateKey) {\n    const op: Operation = [\"delegate_vesting_shares\", options];\n    return this.sendOperations([op], key);\n  }\n\n  /**\n   * Builds, signs, and broadcasts a transaction containing one or more operations.\n   *\n   * @param operations - Ordered Hive operations to include in the transaction.\n   * @param key - Private key or keys required by the operation authorities.\n   * @returns Transaction confirmation containing the generated transaction id.\n   *\n   * @remarks\n   * Pollen reads dynamic global properties to derive TAPOS reference fields,\n   * assigns an expiration based on {@link expireTime}, signs with the client's\n   * chain id, and submits the final signed transaction.\n   *\n   * @throws RPCError\n   * Thrown when property lookup or transaction broadcast fails.\n   *\n   * @example\n   * ```ts\n   * await client.broadcast.sendOperations(\n   *   [['vote', {\n   *     voter: 'srbde',\n   *     author: 'alice',\n   *     permlink: 'field-notes',\n   *     weight: 5_000\n   *   }]],\n   *   postingKey\n   * )\n   * ```\n   */\n  public async sendOperations(\n    operations: Operation[],\n    key: PrivateKey | PrivateKey[],\n  ): Promise<TransactionConfirmation> {\n    const props = await this.client.database.getDynamicGlobalProperties();\n\n    const ref_block_num = props.head_block_number & 0xffff;\n    const blockIdBytes = fromHex(props.head_block_id);\n    const ref_block_prefix = new DataView(\n      blockIdBytes.buffer,\n      blockIdBytes.byteOffset,\n      blockIdBytes.byteLength,\n    ).getUint32(4, true);\n    const expiration = new Date(new Date(props.time + \"Z\").getTime() + this.expireTime)\n      .toISOString()\n      .slice(0, -5);\n    const extensions: any[] = [];\n\n    const tx: Transaction = {\n      expiration,\n      extensions,\n      operations,\n      ref_block_num,\n      ref_block_prefix,\n    };\n\n    const result = await this.send(this.sign(tx, key));\n    // assert(result.expired === false, 'transaction expired')\n\n    return result;\n  }\n\n  /**\n   * Signs a transaction with one or more private keys.\n   *\n   * @param transaction - Unsigned transaction with TAPOS fields and expiration.\n   * @param key - Private key or keys required by the transaction authorities.\n   * @returns The signed transaction with compact ECDSA signatures.\n   *\n   * @remarks\n   * The signature digest includes the client's chain id, preventing signatures\n   * from being replayed across Hive-compatible networks.\n   *\n   * @example\n   * ```ts\n   * const signed = client.broadcast.sign(transaction, activeKey)\n   * console.log(signed.signatures)\n   * ```\n   *\n   * @see {@link cryptoUtils.signTransaction}\n   */\n  public sign(transaction: Transaction, key: PrivateKey | PrivateKey[]): SignedTransaction {\n    return cryptoUtils.signTransaction(transaction, key, this.client.chainId);\n  }\n\n  /**\n   * Broadcasts an already signed transaction to the active RPC node.\n   *\n   * @param transaction - Signed transaction ready for network submission.\n   * @returns Node confirmation enriched with the locally generated transaction id.\n   *\n   * @throws RPCError\n   * Thrown when the node rejects the signed transaction.\n   *\n   * @example\n   * ```ts\n   * const signed = client.broadcast.sign(transaction, activeKey)\n   * const confirmation = await client.broadcast.send(signed)\n   * console.log(confirmation.id)\n   * ```\n   */\n  public async send(transaction: SignedTransaction): Promise<TransactionConfirmation> {\n    const trxId = cryptoUtils.generateTrxId(transaction);\n    const result = await this.call<Omit<TransactionConfirmation, \"id\">>(\"broadcast_transaction\", [\n      transaction,\n    ]);\n    return { id: trxId, ...result };\n  }\n\n  /**\n   * Sends a raw broadcast-related condenser API call.\n   *\n   * @param method - Condenser method name.\n   * @param params - Positional method parameters.\n   * @returns The decoded RPC result.\n   *\n   * @throws RPCError\n   * Thrown when the node rejects the RPC call.\n   *\n   * @example\n   * ```ts\n   * const result = await client.broadcast.call('broadcast_transaction', [signed])\n   * ```\n   */\n  public call<T = unknown>(method: string, params?: unknown[]) {\n    return this.client.call<T>(\"condenser_api\", method, params);\n  }\n}\n", "/**\n * @file Database API helpers.\n * @author Johan Nordberg <code@johan-nordberg.com>\n * @license\n * Copyright (c) 2017 Johan Nordberg. All Rights Reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n *  1. Redistribution of source code must retain the above copyright notice, this\n *     list of conditions and the following disclaimer.\n *\n *  2. Redistribution in binary form must reproduce the above copyright notice,\n *     this list of conditions and the following disclaimer in the documentation\n *     and/or other materials provided with the distribution.\n *\n *  3. Neither the name of the copyright holder nor the names of its contributors\n *     may be used to endorse or promote products derived from this software without\n *     specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * You acknowledge that this software is not designed, licensed or intended for use\n * in the design, construction, operation or maintenance of any military facility.\n */\n\nimport { ExtendedAccount } from \"../chain/account.js\";\nimport { Price, PriceType } from \"../chain/asset.js\";\nimport { BlockHeader, SignedBlock } from \"../chain/block.js\";\nimport { Discussion } from \"../chain/comment.js\";\nimport { DynamicGlobalProperties } from \"../chain/misc.js\";\nimport { ChainProperties, VestingDelegation } from \"../chain/misc.js\";\nimport { AppliedOperation } from \"../chain/operation.js\";\nimport { SignedTransaction } from \"../chain/transaction.js\";\nimport { HiveAsset } from \"./market.js\";\nimport { Client } from \"./../client.js\";\n\n// \u2500\u2500 condenser_api.get_open_orders \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * A single open limit order as returned by `condenser_api.get_open_orders`.\n *\n * @remarks\n * `sell_price` here uses human-readable asset strings (`\"1.000 HIVE\"`) rather\n * than {@link HiveAsset} objects \u2014 this differs from {@link LimitOrder} returned\n * by `database_api.list_limit_orders`. Use the provided `real_price` instead of\n * computing price from `sell_price`.\n *\n * `sell_price.base` reflects the **original** order amount; `for_sale` is what\n * remains and will be less than the original when the order is partially filled.\n */\nexport interface OpenOrder {\n  id: number;\n  /** ISO-8601 without trailing Z. */\n  created: string;\n  /** ISO-8601 without trailing Z. */\n  expiration: string;\n  seller: string;\n  orderid: number;\n  /** Millis of the remaining base asset \u2014 may be less than original if partially filled. */\n  for_sale: number;\n  sell_price: {\n    /** Human-readable original order amount, e.g. `\"11089.628 HIVE\"`. */\n    base: string;\n    /** Human-readable desired amount, e.g. `\"655.397 HBD\"`. */\n    quote: string;\n  };\n  /** Pre-computed HBD-per-HIVE price as a decimal string. */\n  real_price: string;\n  /** Legacy field, always false. */\n  rewarded: boolean;\n}\n\n// \u2500\u2500 condenser_api.get_account_history types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * The payload of a `fill_order` virtual operation.\n *\n * @remarks\n * Amounts are human-readable strings (`\"602.975 HIVE\"`), not millis integers.\n * Parse with `s.split(' ')` \u2192 `[Number(amount), symbol]`. Do **not** multiply\n * by 0.001. The same trade generates one entry in both the maker's and taker's\n * account history \u2014 deduplicate on `trx_id + op_in_trx` when joining across accounts.\n */\nexport interface FillOrderOp {\n  /** Taker \u2014 account whose order triggered the match. */\n  current_owner: string;\n  current_orderid: number;\n  /** Human-readable asset string, e.g. `\"602.975 HIVE\"`. */\n  current_pays: string;\n  /** Maker \u2014 account whose resting order was matched. */\n  open_owner: string;\n  open_orderid: number;\n  /** Human-readable asset string, e.g. `\"29.787 HBD\"`. */\n  open_pays: string;\n}\n\n/**\n * A single entry from `condenser_api.get_account_history`.\n *\n * @remarks\n * Results are returned as `[index, AccountHistoryEntry]` tuples. Narrow the\n * operation type with `entry.op[0] === 'fill_order'` before casting `entry.op[1]`.\n */\nexport interface AccountHistoryEntry {\n  /** Operation tuple: `[operationName, payload]`. */\n  op: [string, unknown];\n  block: number;\n  trx_id: string;\n  op_in_trx: number;\n  /** ISO-8601 without trailing Z. */\n  timestamp: string;\n  virtual_op: boolean;\n}\n\n// \u2500\u2500 database_api.list_limit_orders \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * A single open limit order on the Hive internal market, as returned by\n * `database_api.list_limit_orders`. Includes the seller account name and full\n * price data \u2014 fields not available from `market_history_api.get_order_book`.\n */\nexport interface LimitOrder {\n  id: number;\n  /** ISO-8601 without trailing Z. */\n  created: string;\n  /** ISO-8601 without trailing Z. */\n  expiration: string;\n  /** Hive account name of the order owner. */\n  seller: string;\n  /** Seller-assigned order ID. */\n  orderid: number;\n  /** Amount remaining for sale, in millis of the base asset. */\n  for_sale: number;\n  sell_price: {\n    /** Asset being sold. */\n    base: HiveAsset;\n    /** Asset wanted in return. */\n    quote: HiveAsset;\n  };\n}\n\nexport interface ListLimitOrdersParams {\n  /**\n   * Pagination cursor as `[seller_account, orderid]`.\n   * Use `[\"\", 0]` to start from the beginning.\n   */\n  start: [string, number];\n  /** Maximum entries per page. Up to 1000. */\n  limit: number;\n  /**\n   * Must be `\"by_account\"`. The `\"by_price\"` value throws a\n   * `bad_cast_exception` on all tested nodes.\n   */\n  order: \"by_account\";\n}\n\nexport interface ListLimitOrdersResponse {\n  orders: LimitOrder[];\n}\n\n/**\n * Sort or lookup category used by Hive's `get_discussions_by_*` RPC family.\n *\n * @remarks\n * Categories map directly to condenser API method suffixes. For `blog` and\n * `feed`, Hive expects the query `tag` to be an account name rather than a\n * content tag.\n *\n * @example\n * ```ts\n * const posts = await client.database.getDiscussions('trending', {\n *   tag: 'hive-139531',\n *   limit: 10\n * })\n * ```\n */\nexport type DiscussionQueryCategory =\n  | \"active\"\n  | \"blog\"\n  | \"cashout\"\n  | \"children\"\n  | \"comments\"\n  | \"feed\"\n  | \"hot\"\n  | \"promoted\"\n  | \"trending\"\n  | \"votes\"\n  | \"created\";\n\n/**\n * Query shape accepted by Hive discussion listing endpoints.\n *\n * @remarks\n * The name is preserved for API compatibility even though the historical type\n * spelling is `DisqussionQuery`.\n *\n * @example\n * ```ts\n * const query: DisqussionQuery = {\n *   tag: 'photography',\n *   limit: 20,\n *   truncate_body: 512\n * }\n * ```\n */\nexport interface DisqussionQuery {\n  /**\n   * Name of author or tag to fetch.\n   */\n  tag?: string;\n  /**\n   * Number of results, max 100.\n   */\n  limit: number;\n  filter_tags?: string[];\n  select_authors?: string[];\n  select_tags?: string[];\n  /**\n   * Number of bytes of post body to fetch, default 0 (all)\n   */\n  truncate_body?: number;\n  /**\n   * Name of author to start from, used for paging.\n   * Should be used in conjunction with `start_permlink`.\n   */\n  start_author?: string;\n  /**\n   * Permalink of post to start from, used for paging.\n   * Should be used in conjunction with `start_author`.\n   */\n  start_permlink?: string;\n  parent_author?: string;\n  parent_permlink?: string;\n}\n\n/**\n * Read-only helper for Hive condenser/database RPC methods.\n *\n * @remarks\n * `DatabaseAPI` wraps the broad read surface used by wallets, indexers, and\n * publishing tools. Methods here keep raw condenser names visible for protocol\n * familiarity while returning Pollen chain types such as {@link Asset},\n * {@link Price}, and {@link ExtendedAccount} where richer parsing is useful.\n *\n * @example\n * ```ts\n * import { Client } from '@srbde/pollen'\n *\n * const client = new Client('https://api.hive.blog')\n * const [account] = await client.database.getAccounts(['srbde'])\n *\n * console.log(account.reputation, account.posting_json_metadata)\n * ```\n *\n * @see {@link Client.call}\n */\nexport class DatabaseAPI {\n  /**\n   * Creates a database helper bound to a client.\n   *\n   * @param client - Client used to send condenser API calls.\n   */\n  constructor(readonly client: Client) {}\n\n  /**\n   * Sends a raw condenser API call through the parent client.\n   *\n   * @param method - Bare condenser method name **without** the `condenser_api.`\n   * prefix. This helper automatically prepends `condenser_api.` before\n   * forwarding the call, so including the prefix yourself will produce a\n   * double-prefixed method name (e.g. `condenser_api.condenser_api.foo`) that\n   * every node will reject with an `RPCError: Unable to map request to endpoint`.\n   * @param params - Positional parameters for the method.\n   * @returns The decoded RPC result.\n   *\n   * @throws RPCError\n   * Thrown when the RPC node rejects the call or the method is unavailable.\n   *\n   * @example\n   * ```ts\n   * // Correct \u2014 'condenser_api.' is added automatically\n   * const result = await client.database.call('get_config')\n   * console.log(result.HIVE_BLOCK_INTERVAL)\n   *\n   * // Also correct\n   * const votes = await client.database.call('list_proposal_votes', [\n   *   [], 100, 'by_voter_proposal', 'ascending', 'votable'\n   * ])\n   *\n   * // Wrong \u2014 sends condenser_api.condenser_api.list_proposal_votes \u2192 RPCError\n   * const votes = await client.database.call('condenser_api.list_proposal_votes', [...])\n   * ```\n   */\n  public call<T = unknown>(method: string, params?: unknown[]) {\n    return this.client.call<T>(\"condenser_api\", method, params);\n  }\n\n  /**\n   * Fetches the dynamic global state maintained by the current RPC node.\n   *\n   * @returns Head block, irreversible block, supply, vesting, witness, and\n   * timing data used by Hive applications.\n   *\n   * @throws RPCError\n   * Thrown when the node cannot serve `get_dynamic_global_properties`.\n   *\n   * @example\n   * ```ts\n   * const props = await client.database.getDynamicGlobalProperties()\n   * console.log(props.head_block_number, props.time)\n   * ```\n   */\n  public getDynamicGlobalProperties(): Promise<DynamicGlobalProperties> {\n    return this.call<DynamicGlobalProperties>(\"get_dynamic_global_properties\");\n  }\n\n  /**\n   * Fetches witness-voted median chain properties.\n   *\n   * @returns Chain settings such as account creation fee and maximum block size.\n   *\n   * @throws RPCError\n   * Thrown when the RPC node cannot read chain properties.\n   *\n   * @example\n   * ```ts\n   * const props = await client.database.getChainProperties()\n   * console.log(props.account_creation_fee.toString())\n   * ```\n   */\n  public async getChainProperties(): Promise<ChainProperties> {\n    return this.call<ChainProperties>(\"get_chain_properties\");\n  }\n\n  /**\n   * Fetches condenser state for a Hive-style URL path.\n   *\n   * @param path - Path component using condenser's routing scheme, such as\n   * `@srbde` or `trending/hive-139531`.\n   * @returns The mixed state bundle returned by the condenser API.\n   *\n   * @remarks\n   * This method mirrors the legacy condenser state endpoint. Prefer focused\n   * helpers such as {@link getAccounts} or {@link getDiscussions} when an app\n   * only needs one resource category.\n   *\n   * @throws RPCError\n   * Thrown when the RPC node rejects the state lookup.\n   *\n   * @example\n   * ```ts\n   * const state = await client.database.getState('trending/hive-139531')\n   * console.log(Object.keys(state.content))\n   * ```\n   */\n  public async getState(path: string): Promise<unknown> {\n    return this.call<unknown>(\"get_state\", [path]);\n  }\n\n  /**\n   * Fetches the witness median market price for HIVE denominated in HBD.\n   *\n   * @returns A parsed {@link Price} containing the base and quote assets.\n   *\n   * @throws RPCError\n   * Thrown when the RPC node cannot serve the price feed.\n   *\n   * @example\n   * ```ts\n   * const price = await client.database.getCurrentMedianHistoryPrice()\n   * console.log(`${price.base} per ${price.quote}`)\n   * ```\n   */\n  public async getCurrentMedianHistoryPrice(): Promise<Price> {\n    return Price.from(await this.call<PriceType>(\"get_current_median_history_price\"));\n  }\n\n  /**\n   * Fetches vesting delegations made by an account.\n   *\n   * @param account - Delegator account name.\n   * @param from - Delegatee account name to start after for pagination.\n   * @param limit - Maximum number of delegations to return, up to 1000.\n   * @returns Delegation records ordered by delegatee.\n   *\n   * @throws RPCError\n   * Thrown when the account is invalid or the node rejects the request.\n   *\n   * @example\n   * ```ts\n   * const delegations = await client.database.getVestingDelegations('srbde', '', 50)\n   * for (const delegation of delegations) {\n   *   console.log(delegation.delegatee, delegation.vesting_shares.toString())\n   * }\n   * ```\n   */\n  public async getVestingDelegations(\n    account: string,\n    from = \"\",\n    limit = 1000,\n  ): Promise<VestingDelegation[]> {\n    return this.call<VestingDelegation[]>(\"get_vesting_delegations\", [account, from, limit]);\n  }\n\n  /**\n   * Fetches static protocol constants exposed by the RPC node.\n   *\n   * @returns A name-value map of chain configuration constants.\n   *\n   * @remarks\n   * Config values are useful when deriving UI limits, validating operation\n   * payloads, or teaching protocol defaults in the VitePress hub.\n   *\n   * @throws RPCError\n   * Thrown when the node cannot serve `get_config`.\n   *\n   * @example\n   * ```ts\n   * const config = await client.database.getConfig()\n   * console.log(config.HIVE_BLOCK_INTERVAL)\n   * ```\n   *\n   * @see https://github.com/steemit/steem/blob/master/libraries/protocol/include/steemit/protocol/config.hpp\n   */\n  public getConfig(): Promise<{ [name: string]: string | number | boolean }> {\n    return this.call<{ [name: string]: string | number | boolean }>(\"get_config\");\n  }\n\n  /**\n   * Fetches the header for a specific block number.\n   *\n   * @param blockNum - One-based Hive block number.\n   * @returns The signed block header without transaction bodies.\n   *\n   * @throws RPCError\n   * Thrown when the block does not exist or the node rejects the request.\n   *\n   * @example\n   * ```ts\n   * const header = await client.database.getBlockHeader(90_000_000)\n   * console.log(header.previous)\n   * ```\n   */\n  public getBlockHeader(blockNum: number): Promise<BlockHeader> {\n    return this.call<BlockHeader>(\"get_block_header\", [blockNum]);\n  }\n\n  /**\n   * Fetches a full signed block by number.\n   *\n   * @param blockNum - One-based Hive block number.\n   * @returns The signed block, including transactions and extensions.\n   *\n   * @throws RPCError\n   * Thrown when the block does not exist or the node rejects the request.\n   *\n   * @example\n   * ```ts\n   * const block = await client.database.getBlock(90_000_000)\n   * console.log(block.transactions.length)\n   * ```\n   */\n  public getBlock(blockNum: number): Promise<SignedBlock> {\n    return this.call<SignedBlock>(\"get_block\", [blockNum]);\n  }\n\n  /**\n   * Fetches applied operations recorded in a block.\n   *\n   * @param blockNum - One-based Hive block number.\n   * @param onlyVirtual - When true, returns only virtual operations generated by\n   * chain processing.\n   * @returns Applied operation records with transaction and operation indexes.\n   *\n   * @throws RPCError\n   * Thrown when the block cannot be read or the operation-history plugin is not\n   * available on the node.\n   *\n   * @example\n   * ```ts\n   * const operations = await client.database.getOperations(90_000_000)\n   * console.log(operations.map((applied) => applied.op[0]))\n   * ```\n   */\n  public getOperations(blockNum: number, onlyVirtual = false): Promise<AppliedOperation[]> {\n    return this.call<AppliedOperation[]>(\"get_ops_in_block\", [blockNum, onlyVirtual]);\n  }\n\n  /**\n   * Fetches discussion records such as posts, comments, blog entries, or feeds.\n   *\n   * @param by - Discussion category that selects the condenser method suffix.\n   * @param query - Category-specific query fields, including tag/account and\n   * pagination values.\n   * @returns Discussion objects as returned by condenser.\n   *\n   * @remarks\n   * For `blog` and `feed`, set `query.tag` to the account name. For tag-based\n   * categories such as `trending`, set it to the community or content tag.\n   *\n   * @throws RPCError\n   * Thrown when the query is invalid or the selected discussion method is\n   * unavailable on the node.\n   *\n   * @example\n   * ```ts\n   * const posts = await client.database.getDiscussions('blog', {\n   *   tag: 'srbde',\n   *   limit: 5,\n   *   truncate_body: 256\n   * })\n   *\n   * console.log(posts.map((post) => post.permlink))\n   * ```\n   */\n  public getDiscussions(\n    by: DiscussionQueryCategory,\n    query: DisqussionQuery,\n  ): Promise<Discussion[]> {\n    return this.call<Discussion[]>(`get_discussions_by_${by}`, [query]);\n  }\n\n  /**\n   * Fetches extended account objects for one or more account names.\n   *\n   * @param usernames - Account names to fetch.\n   * @returns Extended account records, including balances, authority metadata,\n   * reputation, and JSON metadata.\n   *\n   * @throws RPCError\n   * Thrown when the RPC node rejects the account lookup.\n   *\n   * @example\n   * ```ts\n   * const [account] = await client.database.getAccounts(['srbde'])\n   * console.log(account.name, account.reputation)\n   * ```\n   */\n  public getAccounts(usernames: string[]): Promise<ExtendedAccount[]> {\n    return this.call<ExtendedAccount[]>(\"get_accounts\", [usernames]);\n  }\n\n  /**\n   * Fetches a signed transaction by transaction id.\n   *\n   * @param txId - Hex transaction id.\n   * @returns The signed transaction stored by the account-history plugin.\n   *\n   * @throws RPCError\n   * Thrown when the transaction is unknown or the node lacks transaction lookup\n   * support.\n   *\n   * @example\n   * ```ts\n   * const transaction = await client.database.getTransaction(\n   *   '0000000000000000000000000000000000000000'\n   * )\n   * console.log(transaction.operations)\n   * ```\n   */\n  public async getTransaction(txId: string): Promise<SignedTransaction> {\n    return this.call<SignedTransaction>(\"get_transaction\", [txId]);\n  }\n\n  /**\n   * Fetches historical operations for an account.\n   *\n   * @param account - Account whose history should be read.\n   * @param from - Starting history index. Use `-1` for the most recent entry.\n   * Walk backwards by using the lowest index from each batch minus 1 as the\n   * next `from`.\n   * @param limit - Maximum entries to return, up to 1000.\n   * @param filter - Optional `[low, high]` BigInt pair from {@link opFilter}.\n   * Asks the node to return only the selected operation types, avoiding\n   * client-side discard. Must stay as `bigint` through serialization \u2014 passing\n   * `Number(bigint)` loses precision for bits \u2265 53 (e.g. `fill_order` is bit 57).\n   * @returns Array of `[index, AccountHistoryEntry]` tuples, newest-first when\n   * walking from `-1`.\n   *\n   * @example\n   * ```ts\n   * import { OP, opFilter } from '@srbde/pollen'\n   *\n   * const [low, high] = opFilter(OP.fill_order)\n   * const history = await client.database.getAccountHistory('srbde', -1, 1000, [low, high])\n   * const fills = history.filter(([, e]) => e.op[0] === 'fill_order')\n   * ```\n   */\n  public getAccountHistory(\n    account: string,\n    from: number,\n    limit: number,\n    filter?: [bigint, bigint],\n  ): Promise<[number, AccountHistoryEntry][]> {\n    const params: unknown[] = [account, from, limit];\n    if (filter) params.push(filter[0], filter[1]);\n    return this.call<[number, AccountHistoryEntry][]>(\"get_account_history\", params);\n  }\n\n  /**\n   * Fetches all currently open limit orders for a single account.\n   *\n   * @param account - Hive account name.\n   * @returns All open orders for the account in a single call \u2014 no pagination.\n   *\n   * @remarks\n   * `sell_price` uses human-readable strings (`\"11089.628 HIVE\"`) rather than\n   * {@link HiveAsset} millis objects. Use `order.real_price` for the\n   * pre-computed HBD-per-HIVE price. `for_sale` reflects the **remaining**\n   * amount \u2014 compare to the parsed `sell_price.base` to detect partial fills.\n   *\n   * To determine bid vs ask:\n   * ```ts\n   * const isAsk = order.sell_price.base.endsWith('HIVE')  // selling HIVE for HBD\n   * const isBid = order.sell_price.base.endsWith('HBD')   // selling HBD for HIVE\n   * ```\n   *\n   * @example\n   * ```ts\n   * const orders = await client.database.getOpenOrders('myaccount')\n   * for (const order of orders) {\n   *   console.log(order.orderid, order.real_price, order.for_sale)\n   * }\n   * ```\n   */\n  public getOpenOrders(account: string): Promise<OpenOrder[]> {\n    return this.call<OpenOrder[]>(\"get_open_orders\", [account]);\n  }\n\n  /**\n   * Verifies that a signed transaction satisfies Hive authority rules.\n   *\n   * @param stx - Signed transaction to verify.\n   * @returns True when the signatures satisfy the transaction's required\n   * authorities.\n   *\n   * @throws RPCError\n   * Thrown when the node rejects the transaction or cannot evaluate authority.\n   *\n   * @example\n   * ```ts\n   * const signed = client.broadcast.sign(transaction, privateKey)\n   * const ok = await client.database.verifyAuthority(signed)\n   * console.log(ok)\n   * ```\n   */\n  public async verifyAuthority(stx: SignedTransaction): Promise<boolean> {\n    return this.call<boolean>(\"verify_authority\", [stx]);\n  }\n\n  /**\n   * Lists open limit orders across the entire internal market, paginated by account.\n   *\n   * @param params - Cursor `start` as `[\"\", 0]` for the first page, then the\n   * last returned `[seller, orderid]` for subsequent pages. `limit` up to 1000.\n   * `order` must be `\"by_account\"` \u2014 `\"by_price\"` throws a `bad_cast_exception`\n   * on all tested nodes.\n   * @returns Up to `limit` open orders with seller account names and full price data.\n   *\n   * @remarks\n   * Prefer this over `market_history_api.get_order_book` when seller identity or\n   * the complete order book is needed: `get_order_book` caps at 500 entries per\n   * side and omits the seller. As of 2026-06-19 the full market has ~1349 orders,\n   * requiring two pages at `limit=1000`. Use `[seller, orderid]` of the last entry\n   * as the next `start` and loop until batch size < limit.\n   *\n   * To determine bid vs ask from `sell_price`:\n   * ```ts\n   * import { HIVE_NAI, HBD_NAI } from '@srbde/pollen'\n   *\n   * const isAsk = order.sell_price.base.nai === HIVE_NAI  // selling HIVE for HBD\n   * const isBid = order.sell_price.base.nai === HBD_NAI   // selling HBD for HIVE\n   * ```\n   *\n   * @example\n   * ```ts\n   * const orders: LimitOrder[] = []\n   * let cursor: [string, number] = ['', 0]\n   * while (true) {\n   *   const { orders: page } = await client.database.listLimitOrders({\n   *     start: cursor, limit: 1000, order: 'by_account'\n   *   })\n   *   orders.push(...page)\n   *   if (page.length < 1000) break\n   *   cursor = [page.at(-1)!.seller, page.at(-1)!.orderid]\n   * }\n   * ```\n   */\n  public listLimitOrders(params: ListLimitOrdersParams): Promise<ListLimitOrdersResponse> {\n    return this.client.call<ListLimitOrdersResponse>(\"database_api\", \"list_limit_orders\", params);\n  }\n\n  /**\n   * Fetches version information from the active RPC node.\n   *\n   * @returns Version fields reported by the node software.\n   *\n   * @throws RPCError\n   * Thrown when the node does not expose `get_version`.\n   *\n   * @example\n   * ```ts\n   * const version = await client.database.getVersion()\n   * console.log(version)\n   * ```\n   */\n  public async getVersion(): Promise<object> {\n    return this.call<object>(\"get_version\", []);\n  }\n}\n", "/**\n * Hivemind database query wrapper\n */\n\nimport { Account } from \"../chain/account.js\";\nimport { Discussion } from \"../chain/comment.js\";\nimport { CommunityDetail, Notifications } from \"../chain/hivemind.js\";\nimport { Client } from \"./../client.js\";\n\n/**\n * Query options for ranked Hivemind post feeds.\n *\n * @remarks\n * Bridge ranking supports global feeds, community feeds, pagination, and an\n * observer account for personalized muted/reputation context.\n *\n * @example\n * ```ts\n * const query: PostsQuery = {\n *   sort: 'trending',\n *   tag: 'hive-139531',\n *   limit: 10,\n *   observer: 'srbde'\n * }\n * ```\n */\nexport interface PostsQuery {\n  /**\n   * Number of posts to fetch\n   */\n  limit?: number;\n  /**\n   * Sorting posts\n   */\n  sort: \"trending\" | \"hot\" | \"created\" | \"promoted\" | \"payout\" | \"payout_comments\" | \"muted\";\n  /**\n   * Filtering with tags\n   */\n  tag?: string[] | string;\n  /**\n   * Observer account\n   */\n  observer?: string;\n  /**\n   * Paginating last post author\n   */\n  start_author?: string;\n  /**\n   * Paginating last post permlink\n   */\n  start_permlink?: string;\n}\n\n/**\n * Omitting sort extended from BridgeParam\n */\n/**\n * Query options for posts associated with a specific account.\n *\n * @example\n * ```ts\n * const query: AccountPostsQuery = {\n *   account: 'srbde',\n *   sort: 'posts',\n *   limit: 10\n * }\n * ```\n */\nexport interface AccountPostsQuery extends Omit<PostsQuery, \"sort\"> {\n  account: string;\n  sort: \"posts\";\n}\n\n/**\n * Query options for fetching a single community.\n */\nexport interface CommunityQuery {\n  name: string;\n  observer: string;\n}\n\n/**\n * Query options for community role lookups.\n *\n * @remarks\n * Reserved for bridge role endpoints that identify moderators, admins, and\n * other community team assignments.\n */\nexport interface CommunityRolesQuery {\n  community: string;\n}\n\n/**\n * Query options for an account notification feed.\n *\n * @example\n * ```ts\n * const query: AccountNotifsQuery = {\n *   account: 'srbde',\n *   limit: 25\n * }\n * ```\n */\nexport interface AccountNotifsQuery {\n  account: Account[\"name\"];\n  limit: number;\n  type?: \"new_community\" | \"pin_post\";\n}\n\n/**\n * Query options for listing communities known to Hivemind.\n *\n * @example\n * ```ts\n * const query: ListCommunitiesQuery = {\n *   limit: 20,\n *   observer: 'srbde'\n * }\n * ```\n */\nexport interface ListCommunitiesQuery {\n  /**\n   * Paginating last\n   */\n  last?: string;\n  /**\n   * Number of communities to fetch\n   */\n  limit: number;\n  /**\n   * To be developed, not ready yet\n   */\n  query?: string | any;\n  /**\n   * Observer account\n   */\n  observer?: Account[\"name\"];\n}\n\n/**\n * Helper for Hive Hivemind and bridge API reads.\n *\n * @remarks\n * Hivemind powers social data that is not stored directly in block operations:\n * ranked posts, community metadata, subscriptions, and notification feeds. This\n * helper routes calls through the `bridge` API namespace used by modern Hive\n * front ends.\n *\n * @example\n * ```ts\n * const posts = await client.hivemind.getRankedPosts({\n *   sort: 'trending',\n *   tag: 'hive-139531',\n *   limit: 10\n * })\n *\n * console.log(posts.map((post) => post.title))\n * ```\n */\nexport class HivemindAPI {\n  /**\n   * Creates a Hivemind helper bound to a client.\n   *\n   * @param client - Client used to call the bridge API namespace.\n   */\n  constructor(readonly client: Client) {}\n\n  /**\n   * Sends a raw bridge API call.\n   *\n   * @param method - Bridge method name.\n   * @param params - Method-specific named parameters.\n   * @returns The decoded bridge result.\n   *\n   * @throws RPCError\n   * Thrown when the active node does not expose bridge or rejects the request.\n   *\n   * @example\n   * ```ts\n   * const posts = await client.hivemind.call('get_ranked_posts', {\n   *   sort: 'hot',\n   *   tag: 'hive-139531',\n   *   limit: 5\n   * })\n   * ```\n   */\n  public call<T = unknown>(method: string, params?: unknown) {\n    return this.client.call<T>(\"bridge\", method, params);\n  }\n\n  /**\n   * Fetches ranked posts from Hivemind.\n   *\n   * @param options - Sort, tag/community, pagination, observer, and limit\n   * settings.\n   * @returns Discussion records ordered by the selected ranking mode.\n   *\n   * @throws RPCError\n   * Thrown when bridge rejects the ranking query.\n   *\n   * @example\n   * ```ts\n   * const posts = await client.hivemind.getRankedPosts({\n   *   sort: 'created',\n   *   tag: 'hive-139531',\n   *   limit: 20,\n   *   observer: 'srbde'\n   * })\n   * ```\n   */\n  public getRankedPosts(options: PostsQuery): Promise<Discussion[]> {\n    return this.call<Discussion[]>(\"get_ranked_posts\", options);\n  }\n\n  /**\n   * Fetches posts authored or surfaced by a specific account.\n   *\n   * @param options - Account, pagination, observer, and limit settings.\n   * @returns Discussion records from the account's post feed.\n   *\n   * @throws RPCError\n   * Thrown when bridge rejects the account-post query.\n   *\n   * @example\n   * ```ts\n   * const posts = await client.hivemind.getAccountPosts({\n   *   account: 'srbde',\n   *   sort: 'posts',\n   *   limit: 10\n   * })\n   * ```\n   */\n  public getAccountPosts(options: AccountPostsQuery): Promise<Discussion[]> {\n    return this.call<Discussion[]>(\"get_account_posts\", options);\n  }\n\n  /**\n   * Fetches community metadata from Hivemind.\n   *\n   * @param options - Community name and observer account.\n   * @returns Community detail records including roles, subscribers, and\n   * display metadata.\n   *\n   * @throws RPCError\n   * Thrown when the community cannot be read.\n   *\n   * @example\n   * ```ts\n   * const [community] = await client.hivemind.getCommunity({\n   *   name: 'hive-139531',\n   *   observer: 'srbde'\n   * })\n   *\n   * console.log(community.title)\n   * ```\n   */\n  public getCommunity(options: CommunityQuery): Promise<CommunityDetail[]> {\n    return this.call<CommunityDetail[]>(\"get_community\", options);\n  }\n\n  /**\n   * Lists communities followed by an account.\n   *\n   * @param account - Account name or bridge-compatible account parameter.\n   * @returns Subscription records containing community and role information.\n   *\n   * @throws RPCError\n   * Thrown when bridge rejects the subscription lookup.\n   *\n   * @example\n   * ```ts\n   * const subscriptions = await client.hivemind.listAllSubscriptions('srbde')\n   * console.log(subscriptions)\n   * ```\n   */\n  public listAllSubscriptions(account: Account[\"name\"] | object): Promise<Discussion[]> {\n    return this.call<Discussion[]>(\"list_all_subscriptions\", account);\n  }\n\n  /**\n   * Fetches an account's Hivemind notification feed.\n   *\n   * @param options - Account, limit, and optional notification type filter.\n   * @returns Notification records for the account.\n   *\n   * @throws RPCError\n   * Thrown when bridge rejects the notification query.\n   *\n   * @example\n   * ```ts\n   * const notifications = await client.hivemind.getAccountNotifications({\n   *   account: 'srbde',\n   *   limit: 25\n   * })\n   * ```\n   */\n  public getAccountNotifications(options?: AccountNotifsQuery): Promise<Notifications[]> {\n    return this.call<Notifications[]>(\"account_notifications\", options);\n  }\n\n  /**\n   * Lists communities known to Hivemind.\n   *\n   * @param options - Pagination, limit, query, and observer settings.\n   * @returns Community detail records.\n   *\n   * @throws RPCError\n   * Thrown when bridge rejects the community list query.\n   *\n   * @example\n   * ```ts\n   * const communities = await client.hivemind.listCommunities({\n   *   limit: 20,\n   *   observer: 'srbde'\n   * })\n   * ```\n   */\n  public listCommunities(options: ListCommunitiesQuery): Promise<CommunityDetail[]> {\n    return this.call<CommunityDetail[]>(\"list_communities\", options);\n  }\n}\n", "/**\n * @file Account by key API helpers.\n * @author Bart\u0142omiej (@engrave) G\u00F3rnicki\n */\n\nimport { PublicKey } from \"../crypto.js\";\nimport { Client } from \"./../client.js\";\n\nexport interface AccountsByKey {\n  /**\n   * Account names grouped by the queried public key order.\n   *\n   * @remarks\n   * Each inner array contains the accounts that reference the corresponding\n   * public key in owner or active authorities.\n   */\n  accounts: string[][];\n}\n\n/**\n * Helper for resolving Hive accounts by authority public key.\n *\n * @remarks\n * The `account_by_key_api` plugin is useful for wallet recovery, ownership\n * audits, and account discovery from a known owner or active public key.\n *\n * @example\n * ```ts\n * const references = await client.keys.getKeyReferences([publicKey])\n * console.log(references.accounts[0])\n * ```\n */\nexport class AccountByKeyAPI {\n  /**\n   * Creates an account-by-key helper bound to a client.\n   *\n   * @param client - Client used to call `account_by_key_api`.\n   */\n  constructor(readonly client: Client) {}\n\n  /**\n   * Sends a raw `account_by_key_api` call.\n   *\n   * @param method - API method name.\n   * @param params - Method-specific parameter object.\n   * @returns The decoded RPC result.\n   *\n   * @throws RPCError\n   * Thrown when the node does not expose the plugin or rejects the request.\n   *\n   * @example\n   * ```ts\n   * const result = await client.keys.call('get_key_references', {\n   *   keys: [publicKey.toString()]\n   * })\n   * ```\n   */\n  public call<T = unknown>(method: string, params?: unknown) {\n    return this.client.call<T>(\"account_by_key_api\", method, params);\n  }\n\n  /**\n   * Fetches accounts that reference the supplied public keys.\n   *\n   * @param keys - Public keys or public-key strings to search.\n   * @returns Account-name groups aligned to the input key order.\n   *\n   * @remarks\n   * Hive returns accounts whose owner or active authorities include each key.\n   * The helper stringifies {@link PublicKey} instances before sending the RPC\n   * payload.\n   *\n   * @throws RPCError\n   * Thrown when account-by-key lookup is unavailable or the node rejects a key.\n   *\n   * @example\n   * ```ts\n   * const references = await client.keys.getKeyReferences([\n   *   'STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA'\n   * ])\n   *\n   * console.log(references.accounts[0])\n   * ```\n   */\n  public async getKeyReferences(keys: (PublicKey | string)[]): Promise<AccountsByKey> {\n    return this.call<AccountsByKey>(\"get_key_references\", {\n      keys: keys.map((key) => key.toString()),\n    });\n  }\n}\n", "/**\n * @file Market History API helper.\n */\n\nimport { Client } from \"../client.js\";\n\n// \u2500\u2500 NAI constants \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport const HBD_NAI = \"@@000000013\";\nexport const HIVE_NAI = \"@@000000021\";\n\n// \u2500\u2500 Shared primitives \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Hive asset as returned by market_history_api responses.\n * `amount` is an integer string of thousandths \u2014 divide by 1000 for display.\n */\nexport interface HiveAsset {\n  amount: string;\n  precision: number;\n  nai: string;\n}\n\n// \u2500\u2500 get_recent_trades / get_trade_history \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface Trade {\n  /** ISO-8601 without trailing Z \u2014 append 'Z' before passing to new Date(). */\n  date: string;\n  current_pays: HiveAsset;\n  open_pays: HiveAsset;\n  maker: string;\n  taker: string;\n}\n\nexport interface GetRecentTradesParams {\n  /** Maximum 1000. */\n  limit: number;\n}\n\nexport interface GetRecentTradesResponse {\n  trades: Trade[];\n}\n\nexport interface GetTradeHistoryParams {\n  /** ISO-8601 datetime without Z. */\n  start: string;\n  /** ISO-8601 datetime without Z. */\n  end: string;\n  /** Maximum 1000. To paginate, advance start by 1 ms past the last returned date. */\n  limit: number;\n}\n\nexport interface GetTradeHistoryResponse {\n  trades: Trade[];\n}\n\n// \u2500\u2500 get_ticker \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface GetTickerResponse {\n  /** Last trade price as HIVE/HBD ratio string. */\n  latest: string;\n  lowest_ask: string;\n  highest_bid: string;\n  /** Signed decimal string, e.g. \"-1.856...\". */\n  percent_change: string;\n  /** 24-hour HIVE volume. */\n  hive_volume: HiveAsset;\n  /** 24-hour HBD volume. */\n  hbd_volume: HiveAsset;\n}\n\n// \u2500\u2500 get_volume \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface GetVolumeResponse {\n  hive_volume: HiveAsset;\n  hbd_volume: HiveAsset;\n}\n\n// \u2500\u2500 get_order_book \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface OrderBookEntry {\n  order_price: {\n    base: HiveAsset;\n    quote: HiveAsset;\n  };\n  /** Decimal string, e.g. \"0.04928000000000000\". */\n  real_price: string;\n  /** HIVE in the order (millis). */\n  hive: number;\n  /** HBD in the order (millis). */\n  hbd: number;\n  /** ISO-8601 without trailing Z. */\n  created: string;\n}\n\nexport interface GetOrderBookParams {\n  /**\n   * Entries per side. Maximum 500 \u2014 requests above this return 0 results\n   * (silent truncation, not an error). No offset/pagination is available.\n   */\n  limit: number;\n}\n\nexport interface GetOrderBookResponse {\n  /** Buy orders sorted highest\u2192lowest price. */\n  bids: OrderBookEntry[];\n  /** Sell orders sorted lowest\u2192highest price. */\n  asks: OrderBookEntry[];\n}\n\n// \u2500\u2500 get_market_history_buckets \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface GetMarketHistoryBucketsResponse {\n  /** Available bucket sizes in seconds, e.g. [15, 60, 300, 3600, 86400]. */\n  bucket_sizes: number[];\n}\n\n// \u2500\u2500 get_market_history (OHLCV) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface OHLCVSide {\n  high: number;\n  low: number;\n  open: number;\n  close: number;\n  volume: number;\n}\n\nexport interface MarketBucket {\n  id: number;\n  /** ISO-8601 bucket start without trailing Z. */\n  open: string;\n  seconds: number;\n  /** OHLCV in HIVE units (millis). */\n  hive: OHLCVSide;\n  /** OHLCV in HBD units (millis). */\n  non_hive: OHLCVSide;\n}\n\nexport interface GetMarketHistoryParams {\n  /** Must be one of the values returned by getMarketHistoryBuckets(). */\n  bucket_seconds: number;\n  /** ISO-8601 datetime without Z. */\n  start: string;\n  /** ISO-8601 datetime without Z. */\n  end: string;\n}\n\nexport interface GetMarketHistoryResponse {\n  buckets: MarketBucket[];\n}\n\n// \u2500\u2500 Helper class \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Typed wrapper for the Hive `market_history_api`.\n *\n * @remarks\n * Accessible as `client.market`. All date strings returned by this API lack a\n * trailing `Z` \u2014 append it before constructing a `Date`: `new Date(date + 'Z')`.\n * All `HiveAsset.amount` values are integer millis strings; divide by 1000 for\n * display values.\n *\n * @example\n * ```ts\n * import { Client } from '@srbde/pollen'\n *\n * const client = new Client('https://api.hive.blog')\n * const ticker = await client.market.getTicker()\n * console.log(`HIVE/HBD: ${ticker.latest}`)\n * ```\n */\nexport class MarketHistoryAPI {\n  constructor(readonly client: Client) {}\n\n  public call<T = unknown>(method: string, params?: unknown) {\n    return this.client.call<T>(\"market_history_api\", method, params);\n  }\n\n  /**\n   * Returns the most recent trades on the internal market.\n   *\n   * @param params - `limit` up to 1000.\n   *\n   * @example\n   * ```ts\n   * const { trades } = await client.market.getRecentTrades({ limit: 100 })\n   * ```\n   */\n  public getRecentTrades(params: GetRecentTradesParams): Promise<GetRecentTradesResponse> {\n    return this.call<GetRecentTradesResponse>(\"get_recent_trades\", params);\n  }\n\n  /**\n   * Returns trades between two timestamps.\n   *\n   * @param params - `start`, `end` as ISO-8601 strings without Z, `limit` up to 1000.\n   * @remarks\n   * To paginate, take the maximum `date` from the last batch, append 1 ms, and\n   * re-query. Loop until batch size < limit or cursor >= end.\n   *\n   * @example\n   * ```ts\n   * const { trades } = await client.market.getTradeHistory({\n   *   start: '2024-01-01T00:00:00',\n   *   end:   '2024-01-02T00:00:00',\n   *   limit: 1000\n   * })\n   * ```\n   */\n  public getTradeHistory(params: GetTradeHistoryParams): Promise<GetTradeHistoryResponse> {\n    return this.call<GetTradeHistoryResponse>(\"get_trade_history\", params);\n  }\n\n  /**\n   * Returns current ticker data for the HIVE/HBD internal market.\n   *\n   * @example\n   * ```ts\n   * const ticker = await client.market.getTicker()\n   * console.log(ticker.latest, ticker.percent_change)\n   * ```\n   */\n  public getTicker(): Promise<GetTickerResponse> {\n    return this.call<GetTickerResponse>(\"get_ticker\", {});\n  }\n\n  /**\n   * Returns 24-hour HIVE and HBD trading volume.\n   *\n   * @example\n   * ```ts\n   * const { hive_volume, hbd_volume } = await client.market.getVolume()\n   * ```\n   */\n  public getVolume(): Promise<GetVolumeResponse> {\n    return this.call<GetVolumeResponse>(\"get_volume\", {});\n  }\n\n  /**\n   * Returns the current order book up to `limit` entries per side.\n   *\n   * @param params - `limit` per side, maximum 500. Requests above 500 return\n   * 0 results (silent truncation). There is no pagination beyond 500/side.\n   *\n   * @example\n   * ```ts\n   * const { bids, asks } = await client.market.getOrderBook({ limit: 500 })\n   * const spread = Number(asks[0].real_price) - Number(bids[0].real_price)\n   * ```\n   */\n  public getOrderBook(params: GetOrderBookParams): Promise<GetOrderBookResponse> {\n    return this.call<GetOrderBookResponse>(\"get_order_book\", params);\n  }\n\n  /**\n   * Returns the available OHLCV bucket sizes supported by this node.\n   *\n   * @example\n   * ```ts\n   * const { bucket_sizes } = await client.market.getMarketHistoryBuckets()\n   * // [15, 60, 300, 3600, 86400]\n   * ```\n   */\n  public getMarketHistoryBuckets(): Promise<GetMarketHistoryBucketsResponse> {\n    return this.call<GetMarketHistoryBucketsResponse>(\"get_market_history_buckets\", {});\n  }\n\n  /**\n   * Returns OHLCV candles for a time range at a given bucket size.\n   *\n   * @param params - `bucket_seconds` must be one of the values from\n   * {@link getMarketHistoryBuckets}. `start` and `end` are ISO-8601 without Z.\n   * @remarks\n   * Close price in HBD-per-HIVE: `bucket.hive.close / bucket.non_hive.close`.\n   * Volume values are millis \u2014 divide by 1000.\n   *\n   * @example\n   * ```ts\n   * const { buckets } = await client.market.getMarketHistory({\n   *   bucket_seconds: 3600,\n   *   start: '2024-01-01T00:00:00',\n   *   end:   '2024-01-02T00:00:00'\n   * })\n   * ```\n   */\n  public getMarketHistory(params: GetMarketHistoryParams): Promise<GetMarketHistoryResponse> {\n    return this.call<GetMarketHistoryResponse>(\"get_market_history\", params);\n  }\n}\n", "/**\n * @file Misc hive type definitions.\n * @author Johan Nordberg <code@johan-nordberg.com>\n * @license\n * Copyright (c) 2017 Johan Nordberg. All Rights Reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n *  1. Redistribution of source code must retain the above copyright notice, this\n *     list of conditions and the following disclaimer.\n *\n *  2. Redistribution in binary form must reproduce the above copyright notice,\n *     this list of conditions and the following disclaimer in the documentation\n *     and/or other materials provided with the distribution.\n *\n *  3. Neither the name of the copyright holder nor the names of its contributors\n *     may be used to endorse or promote products derived from this software without\n *     specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * You acknowledge that this software is not designed, licensed or intended for use\n * in the design, construction, operation or maintenance of any military facility.\n */\nimport { Account } from \"./account.js\";\nimport { Asset, Price } from \"./asset.js\";\n\nimport { fromHex, toHex } from \"../utils.js\";\n\n/**\n * Large integer returned as a string to avoid JavaScript precision loss.\n *\n * @example\n * ```ts\n * const value: Bignum = props.max_virtual_bandwidth\n * ```\n */\nexport type Bignum = string;\n\n/**\n * Byte wrapper that serializes to a hex-encoded string.\n *\n * @remarks\n * Hive APIs frequently represent binary values as hex strings. `HexBuffer`\n * now stores a native `Uint8Array`, keeping protocol bytes available for\n * serializers without reintroducing Node `Buffer` as a core byte container.\n *\n * @example\n * ```ts\n * const bytes = HexBuffer.from('deadbeef')\n * console.log(bytes.toJSON())\n * ```\n */\nexport class HexBuffer {\n  /**\n   * Creates a hex-buffer wrapper around native bytes.\n   *\n   * @param buffer - Raw binary data as a `Uint8Array`.\n   */\n  constructor(public buffer: Uint8Array) {}\n\n  /**\n   * Normalizes hex, bytes, or an existing wrapper into a {@link HexBuffer}.\n   *\n   * @param value - `Uint8Array`, existing wrapper, byte array, or hex string.\n   * @returns A hex-buffer wrapper.\n   *\n   * @example\n   * ```ts\n   * const buffer = HexBuffer.from([0xde, 0xad, 0xbe, 0xef])\n   * ```\n   */\n  public static from(value: Uint8Array | HexBuffer | number[] | string) {\n    if (value instanceof HexBuffer) {\n      return value;\n    } else if (value instanceof Uint8Array) {\n      return new HexBuffer(value);\n    } else if (typeof value === \"string\") {\n      return new HexBuffer(fromHex(value));\n    } else {\n      return new HexBuffer(new Uint8Array(value));\n    }\n  }\n\n  public toString(encoding = \"hex\") {\n    if (encoding !== \"hex\") {\n      throw new Error(\"Only hex encoding is supported\");\n    }\n    return toHex(this.buffer);\n  }\n\n  public toJSON() {\n    return this.toString();\n  }\n}\n\n/**\n * Chain properties voted on by Hive witnesses.\n *\n * @remarks\n * Witnesses publish these values and the chain uses the median active-witness\n * values for account creation fee, block capacity, and HBD interest.\n *\n * @example\n * ```ts\n * const props = await client.database.getChainProperties()\n * console.log(props.account_creation_fee)\n * ```\n */\nexport interface ChainProperties {\n  /**\n   * This fee, paid in HIVE, is converted into VESTING SHARES for the new account. Accounts\n   * without vesting shares cannot earn usage rations and therefore are powerless. This minimum\n   * fee requires all accounts to have some kind of commitment to the network that includes the\n   * ability to vote and make transactions.\n   *\n   * @remarks\n   * This has to be multiplied by STEEMIT ? `CREATE_ACCOUNT_WITH_HIVE_MODIFIER`\n   * (defined as 30 on the main chain) to get the minimum fee needed to create an account.\n   *\n   */\n  account_creation_fee: string | Asset;\n  /**\n   * This witnesses vote for the maximum_block_size which is used by the network\n   * to tune rate limiting and capacity.\n   */\n  maximum_block_size: number; // uint32_t\n  /**\n   * The HBD interest percentage rate decided by witnesses, expressed 0 to 10000.\n   */\n  hbd_interest_rate: number; // uint16_t\n}\n\n/**\n * Vesting-share delegation from one account to another.\n *\n * @remarks\n * Delegated VESTS remain owned by the delegator but transfer voting influence\n * and RC capacity to the delegatee until removed and cooled down.\n *\n * @example\n * ```ts\n * const delegations = await client.database.getVestingDelegations('srbde')\n * console.log(delegations[0]?.delegatee)\n * ```\n */\nexport interface VestingDelegation {\n  /**\n   * Delegation id.\n   */\n  id: number; // id_type\n  /**\n   * Account that is delegating vests to delegatee.\n   */\n  delegator: string; // account_name_type\n  /**\n   * Account that is receiving vests from delegator.\n   */\n  delegatee: string; // account_name_type\n  /**\n   * Amount of VESTS delegated.\n   */\n  vesting_shares: Asset | string;\n  /**\n   * Earliest date delegation can be removed.\n   */\n  min_delegation_time: string; // time_point_sec\n}\n\n/**\n * Dynamic global chain state reported by a Hive RPC node.\n *\n * @remarks\n * These values drive transaction TAPOS fields, stream cursors, supply displays,\n * voting-power calculations, witness participation dashboards, and bandwidth\n * estimates.\n *\n * @example\n * ```ts\n * const props = await client.database.getDynamicGlobalProperties()\n * console.log(props.head_block_number, props.last_irreversible_block_num)\n * ```\n */\nexport interface DynamicGlobalProperties {\n  id: number;\n  /**\n   * Current block height.\n   */\n  head_block_number: number;\n  head_block_id: string;\n  /**\n   * UTC Server time, e.g. 2020-01-15T00:42:00\n   */\n  time: string;\n  /**\n   * Currently elected witness.\n   */\n  current_witness: string;\n  /**\n   * The total POW accumulated, aka the sum of num_pow_witness at the time\n   * new POW is added.\n   */\n  total_pow: number;\n  /**\n   * The current count of how many pending POW witnesses there are, determines\n   * the difficulty of doing pow.\n   */\n  num_pow_witnesses: number;\n  virtual_supply: Asset | string;\n  current_supply: Asset | string;\n  /**\n   * Total asset held in confidential balances.\n   */\n  confidential_supply: Asset | string;\n  current_hbd_supply: Asset | string;\n  /**\n   * Total asset held in confidential balances.\n   */\n  confidential_hbd_supply: Asset | string;\n  total_vesting_fund_hive: Asset | string;\n  total_vesting_shares: Asset | string;\n  total_reward_fund_hive: Asset | string;\n  /**\n   * The running total of REWARD^2.\n   */\n  total_reward_shares2: string;\n  pending_rewarded_vesting_shares: Asset | string;\n  pending_rewarded_vesting_hive: Asset | string;\n  /**\n   * This property defines the interest rate that HBD deposits receive.\n   */\n  hbd_interest_rate: number;\n  hbd_print_rate: number;\n  /**\n   *  Average block size is updated every block to be:\n   *\n   *     average_block_size = (99 * average_block_size + new_block_size) / 100\n   *\n   *  This property is used to update the current_reserve_ratio to maintain\n   *  approximately 50% or less utilization of network capacity.\n   */\n  average_block_size: number;\n  /**\n   * Maximum block size is decided by the set of active witnesses which change every round.\n   * Each witness posts what they think the maximum size should be as part of their witness\n   * properties, the median size is chosen to be the maximum block size for the round.\n   *\n   * @remarks\n   * The minimum value for maximum_block_size is defined by the protocol to prevent the\n   * network from getting stuck by witnesses attempting to set this too low.\n   */\n  maximum_block_size: number;\n  /**\n   * The current absolute slot number. Equal to the total\n   * number of slots since genesis. Also equal to the total\n   * number of missed slots plus head_block_number.\n   */\n  current_aslot: number;\n  /**\n   * Used to compute witness participation.\n   */\n  recent_slots_filled: Bignum;\n  participation_count: number;\n  last_irreversible_block_num: number;\n  /**\n   * The maximum bandwidth the blockchain can support is:\n   *\n   *    max_bandwidth = maximum_block_size * BANDWIDTH_AVERAGE_WINDOW_SECONDS / BLOCK_INTERVAL\n   *\n   * The maximum virtual bandwidth is:\n   *\n   *    max_bandwidth * current_reserve_ratio\n   */\n  max_virtual_bandwidth: Bignum;\n  /**\n   * Any time average_block_size <= 50% maximum_block_size this value grows by 1 until it\n   * reaches MAX_RESERVE_RATIO.  Any time average_block_size is greater than\n   * 50% it falls by 1%.  Upward adjustments happen once per round, downward adjustments\n   * happen every block.\n   */\n  current_reserve_ratio: number;\n  /**\n   * The number of votes regenerated per day.  Any user voting slower than this rate will be\n   * \"wasting\" voting power through spillover; any user voting faster than this rate will have\n   * their votes reduced.\n   */\n  vote_power_reserve_rate: number;\n}\n\n/**\n * Calculates the HIVE/VESTS conversion price from global properties.\n *\n * @param props - Dynamic global properties containing total vesting fund and\n * total vesting shares.\n * @returns A price that converts between VESTS and HIVE.\n *\n * @remarks\n * Hive expresses influence in VESTS while users often reason about powered-up\n * HIVE. If either side of the vesting pool is zero, Pollen returns a neutral\n * 1:1 fallback price to keep downstream math defined.\n *\n * @example\n * ```ts\n * const props = await client.database.getDynamicGlobalProperties()\n * const vestingPrice = getVestingSharePrice(props)\n * ```\n */\nexport function getVestingSharePrice(props: DynamicGlobalProperties): Price {\n  // empty string is needed to skip the type check error\n  const totalVestingFund = Asset.from(props.total_vesting_fund_hive);\n  const totalVestingShares = Asset.from(props.total_vesting_shares);\n  if (totalVestingFund.amount === 0 || totalVestingShares.amount === 0) {\n    return new Price(new Asset(1, \"VESTS\"), new Asset(1, \"HIVE\"));\n  }\n  return new Price(totalVestingShares, totalVestingFund);\n}\n\n/**\n * Calculates an account's effective vesting shares.\n *\n * @param account - Account containing vesting, delegation, and withdrawal\n * fields.\n * @param subtract_delegated - Whether outgoing delegations should reduce the\n * result.\n * @param add_received - Whether incoming delegations should increase the\n * result.\n * @returns Effective VESTS amount as a number.\n *\n * @remarks\n * The calculation subtracts pending power-down withdrawals, then optionally\n * adjusts for delegated and received vesting shares. RC and voting mana helpers\n * use this to derive maximum voting mana.\n *\n * @example\n * ```ts\n * const [account] = await client.database.getAccounts(['srbde'])\n * const effectiveVests = getVests(account)\n * ```\n */\nexport function getVests(account: Account, subtract_delegated = true, add_received = true) {\n  let vests: Asset = Asset.from(account.vesting_shares);\n  const vests_delegated: Asset = Asset.from(account.delegated_vesting_shares);\n  const vests_received: Asset = Asset.from(account.received_vesting_shares);\n  const withdraw_rate: Asset = Asset.from(account.vesting_withdraw_rate);\n  const already_withdrawn = (Number(account.to_withdraw) - Number(account.withdrawn)) / 1000000;\n  const withdraw_vests = Math.min(withdraw_rate.amount, already_withdrawn);\n  vests = vests.subtract(withdraw_vests);\n\n  if (subtract_delegated) {\n    vests = vests.subtract(vests_delegated);\n  }\n  if (add_received) {\n    vests = vests.add(vests_received);\n  }\n\n  return vests.amount;\n}\n", "/* tslint:disable:no-string-literal */\n\nimport { Account } from \"../chain/account.js\";\nimport { getVests } from \"../chain/misc.js\";\nimport { Manabar, RCAccount, RCParams, RCPool } from \"../chain/rc.js\";\nimport { Client } from \"./../client.js\";\n\n/**\n * Helper for Hive Resource Credit and voting mana calculations.\n *\n * @remarks\n * `RCAPI` reads `rc_api` data and converts Hive manabar state into current\n * mana and percentage values. RC mana controls transaction capacity, while\n * voting mana controls curation influence; both regenerate over Hive's\n * five-day manabar window.\n *\n * @example\n * ```ts\n * const rc = await client.rc.getRCMana('srbde')\n * const vp = await client.rc.getVPMana('srbde')\n *\n * console.log(rc.percentage / 100, vp.percentage / 100)\n * ```\n */\nexport class RCAPI {\n  /**\n   * Creates an RC helper bound to a client.\n   *\n   * @param client - Client used to call `rc_api` and condenser account data.\n   */\n  constructor(readonly client: Client) {}\n\n  /**\n   * Sends a raw `rc_api` call through the parent client.\n   *\n   * @param method - RC API method name.\n   * @param params - Named parameter object accepted by the method.\n   * @returns The decoded RPC result.\n   *\n   * @throws RPCError\n   * Thrown when the active RPC node does not expose `rc_api` or rejects the\n   * request.\n   *\n   * @example\n   * ```ts\n   * const result = await client.rc.call('find_rc_accounts', {\n   *   accounts: ['srbde']\n   * })\n   * ```\n   */\n  public call<T = unknown>(method: string, params?: unknown) {\n    return this.client.call<T>(\"rc_api\", method, params);\n  }\n\n  /**\n   * Fetches RC account records for one or more usernames.\n   *\n   * @param usernames - Account names to inspect.\n   * @returns RC account records including max RC and current RC manabar state.\n   *\n   * @throws RPCError\n   * Thrown when the node cannot serve `find_rc_accounts`.\n   *\n   * @example\n   * ```ts\n   * const [rcAccount] = await client.rc.findRCAccounts(['srbde'])\n   * console.log(rcAccount.max_rc)\n   * ```\n   */\n  public async findRCAccounts(usernames: string[]): Promise<RCAccount[]> {\n    const res = await this.call<{ rc_accounts: RCAccount[] }>(\"find_rc_accounts\", {\n      accounts: usernames,\n    });\n    return res.rc_accounts;\n  }\n\n  /**\n   * Fetches global RC resource parameters.\n   *\n   * @returns Chain-wide coefficients used to price CPU, state bytes, history,\n   * execution time, and market bandwidth.\n   *\n   * @throws RPCError\n   * Thrown when the node cannot serve `get_resource_params`.\n   *\n   * @example\n   * ```ts\n   * const params = await client.rc.getResourceParams()\n   * console.log(params.resource_params)\n   * ```\n   */\n  public async getResourceParams(): Promise<RCParams> {\n    const res = await this.call<{ resource_params: RCParams }>(\"get_resource_params\", {});\n    return res.resource_params;\n  }\n\n  /**\n   * Fetches the current RC resource pool.\n   *\n   * @returns Current pool levels for the chain's RC resource classes.\n   *\n   * @throws RPCError\n   * Thrown when the node cannot serve `get_resource_pool`.\n   *\n   * @example\n   * ```ts\n   * const pool = await client.rc.getResourcePool()\n   * console.log(pool.resource_pool)\n   * ```\n   */\n  public async getResourcePool(): Promise<RCPool> {\n    const res = await this.call<{ resource_pool: RCPool }>(\"get_resource_pool\", {});\n    return res.resource_pool;\n  }\n\n  /**\n   * Fetches and calculates current RC mana for an account.\n   *\n   * @param username - Account name to inspect.\n   * @returns Manabar values with current mana, maximum mana, and percentage in\n   * hundredths of a percent.\n   *\n   * @remarks\n   * The calculation projects regeneration from the account's last RC manabar\n   * update to the current wall-clock time.\n   *\n   * @throws RPCError\n   * Thrown when RC account lookup fails.\n   *\n   * @example\n   * ```ts\n   * const mana = await client.rc.getRCMana('srbde')\n   * console.log(`${mana.percentage / 100}% RC`)\n   * ```\n   */\n  public async getRCMana(username: string): Promise<Manabar> {\n    const rc_account: RCAccount = (await this.findRCAccounts([username]))[0];\n    return this.calculateRCMana(rc_account);\n  }\n\n  /**\n   * Fetches and calculates current voting mana for an account.\n   *\n   * @param username - Account name to inspect.\n   * @returns Voting manabar values with current mana, maximum mana, and\n   * percentage in hundredths of a percent.\n   *\n   * @remarks\n   * Maximum voting mana is derived from vesting shares, then regenerated across\n   * Hive's five-day voting manabar window.\n   *\n   * @throws RPCError\n   * Thrown when account lookup fails.\n   *\n   * @example\n   * ```ts\n   * const mana = await client.rc.getVPMana('srbde')\n   * console.log(`${mana.percentage / 100}% voting mana`)\n   * ```\n   */\n  public async getVPMana(username: string): Promise<Manabar> {\n    const account: Account = (\n      await this.client.call<Account[]>(\"condenser_api\", \"get_accounts\", [[username]])\n    )[0];\n    return this.calculateVPMana(account);\n  }\n\n  /**\n   * Calculates current RC mana from an RC account record.\n   *\n   * @param rc_account - Account record returned by {@link findRCAccounts}.\n   * @returns Projected manabar state at the current wall-clock time.\n   *\n   * @example\n   * ```ts\n   * const [rcAccount] = await client.rc.findRCAccounts(['srbde'])\n   * const mana = client.rc.calculateRCMana(rcAccount)\n   * ```\n   */\n  public calculateRCMana(rc_account: RCAccount): Manabar {\n    return this._calculateManabar(Number(rc_account.max_rc), rc_account.rc_manabar);\n  }\n\n  /**\n   * Calculates current voting mana from a condenser account record.\n   *\n   * @param account - Account object containing vesting shares and voting\n   * manabar state.\n   * @returns Projected voting manabar state at the current wall-clock time.\n   *\n   * @example\n   * ```ts\n   * const [account] = await client.database.getAccounts(['srbde'])\n   * const mana = client.rc.calculateVPMana(account)\n   * ```\n   */\n  public calculateVPMana(account: Account): Manabar {\n    const max_mana: number = getVests(account) * Math.pow(10, 6);\n    return this._calculateManabar(max_mana, account.voting_manabar);\n  }\n\n  /**\n   * Internal convenience method to reduce redundant code\n   */\n  private _calculateManabar(\n    max_mana: number,\n    { current_mana, last_update_time }: { current_mana: any; last_update_time: any },\n  ): Manabar {\n    const delta: number = Date.now() / 1000 - last_update_time;\n    current_mana = Number(current_mana) + (delta * max_mana) / 432000;\n    let percentage: number = Math.round((current_mana / max_mana) * 10000);\n\n    if (!isFinite(percentage) || percentage < 0) {\n      percentage = 0;\n    } else if (percentage > 10000) {\n      percentage = 10000;\n    }\n\n    return { current_mana, max_mana, percentage };\n  }\n}\n", "/**\n * @file Transaction status API helpers.\n * @author Bart\u0142omiej (@engrave) G\u00F3rnicki\n */\n\nimport { Client } from \"./../client.js\";\n\n/**\n * Lifecycle state reported by Hive's transaction-status plugin.\n *\n * @remarks\n * `within_reversible_block` means the transaction is included but not final.\n * `within_irreversible_block` is the stable state most applications should wait\n * for before treating a transaction as final.\n *\n * @example\n * ```ts\n * const { status } = await client.transaction.findTransaction(txId)\n * const final = status === 'within_irreversible_block'\n * ```\n */\nexport type TransactionStatus =\n  | \"unknown\"\n  | \"within_mempool\"\n  | \"within_reversible_block\"\n  | \"within_irreversible_block\"\n  | \"expired_reversible\"\n  | \"expired_irreversible\"\n  | \"too_old\";\n\ninterface FindTransactionParams {\n  transaction_id: string;\n  expiration?: string;\n}\n/**\n * Helper for checking Hive transaction inclusion status.\n *\n * @remarks\n * The transaction status plugin reports whether a transaction is still unknown,\n * in the mempool, included in a reversible block, included irreversibly, or too\n * old to track. This is useful for user-facing broadcast confirmation flows.\n *\n * @example\n * ```ts\n * const { status } = await client.transaction.findTransaction(txId)\n * console.log(status)\n * ```\n */\nexport class TransactionStatusAPI {\n  /**\n   * Creates a transaction-status helper bound to a client.\n   *\n   * @param client - Client used to call `transaction_status_api`.\n   */\n  constructor(readonly client: Client) {}\n\n  /**\n   * Sends a raw `transaction_status_api` call.\n   *\n   * @param method - Transaction-status API method name.\n   * @param params - Method-specific parameter object.\n   * @returns The decoded RPC result.\n   *\n   * @throws RPCError\n   * Thrown when the active node does not expose the transaction-status plugin\n   * or rejects the request.\n   *\n   * @example\n   * ```ts\n   * const result = await client.transaction.call('find_transaction', {\n   *   transaction_id: txId\n   * })\n   * ```\n   */\n  public call<T = unknown>(method: string, params?: unknown) {\n    return this.client.call<T>(\"transaction_status_api\", method, params);\n  }\n\n  /**\n   * Finds the current lifecycle status of a transaction id.\n   *\n   * @param transaction_id - Hex transaction id to inspect.\n   * @param expiration - Optional transaction expiration timestamp, used by the\n   * plugin to distinguish expired transactions from unknown ones.\n   * @returns The transaction status reported by the node.\n   *\n   * @throws RPCError\n   * Thrown when the plugin is unavailable or the transaction id is malformed.\n   *\n   * @example\n   * ```ts\n   * const { status } = await client.transaction.findTransaction(\n   *   confirmation.id,\n   *   transaction.expiration\n   * )\n   *\n   * if (status === 'within_irreversible_block') {\n   *   console.log('Final')\n   * }\n   * ```\n   */\n  public async findTransaction(\n    transaction_id: string,\n    expiration?: string,\n  ): Promise<{ status: TransactionStatus }> {\n    const params: FindTransactionParams = {\n      transaction_id,\n    };\n    if (expiration) {\n      params.expiration = expiration;\n    }\n    return this.call<{ status: TransactionStatus }>(\"find_transaction\", params);\n  }\n}\n", "/**\n * @file Node health tracking for smart failover.\n * @license BSD-3-Clause-No-Military-License\n *\n * Tracks per-node, per-API health to enable intelligent failover decisions.\n * Nodes that fail for specific APIs are deprioritized for those APIs while\n * remaining available for others. Stale nodes (behind on head block) are\n * also deprioritized.\n */\n\ninterface ApiFailure {\n  count: number;\n  lastFailure: number;\n}\n/** Tracks rate-limit state for a node */\ninterface RateLimitState {\n  /** Timestamp (ms) when the rate limit expires \u2014 skip this node until then */\n  retryAfter: number;\n}\n\ninterface NodeState {\n  /** Per-API failure tracking (api name \u2192 failure info) */\n  apiFailures: Map<string, ApiFailure>;\n  /** Consecutive failures across all APIs */\n  consecutiveFailures: number;\n  /** Timestamp of last failure */\n  lastFailure: number;\n  /** Last known head block number from this node */\n  headBlock: number;\n  /** When headBlock was last updated */\n  headBlockUpdatedAt: number;\n  /** Rate-limit state \u2014 set when a 429 is received */\n  rateLimit?: RateLimitState;\n}\n\n/**\n * Tuning options for Pollen's RPC node health tracker.\n *\n * @remarks\n * These values shape how aggressively a client deprioritizes nodes after\n * failures, plugin-specific errors, stale head blocks, or HTTP 429 rate limits.\n *\n * @example\n * ```ts\n * const client = new Client(['https://api.hive.blog', 'https://api.openhive.network'], {\n *   healthTrackerOptions: {\n *     maxFailuresBeforeCooldown: 2,\n *     staleBlockThreshold: 15\n *   }\n * })\n * ```\n */\nexport interface HealthTrackerOptions {\n  /**\n   * How long (ms) to deprioritize a node after consecutive failures.\n   * Default: 30 seconds.\n   */\n  nodeCooldownMs?: number;\n  /**\n   * How long (ms) to deprioritize a node for a specific API after failures.\n   * Default: 60 seconds.\n   */\n  apiCooldownMs?: number;\n  /**\n   * Number of consecutive failures before a node enters cooldown.\n   * Default: 3.\n   */\n  maxFailuresBeforeCooldown?: number;\n  /**\n   * Number of API-specific failures before deprioritizing for that API.\n   * Default: 2.\n   */\n  maxApiFailuresBeforeCooldown?: number;\n  /**\n   * How many blocks behind the best known head block a node can be\n   * before being considered stale. Default: 30.\n   */\n  staleBlockThreshold?: number;\n  /**\n   * How long (ms) head block data remains valid for staleness checks.\n   * Default: 2 minutes.\n   */\n  headBlockTtlMs?: number;\n  /**\n   * Default duration (ms) to skip a node after receiving a 429 response,\n   * used when the server doesn't provide a Retry-After header.\n   * Default: 10 seconds.\n   */\n  defaultRateLimitMs?: number;\n}\n\n/**\n * Tracks per-node health for resilient Hive RPC failover.\n *\n * @remarks\n * `NodeHealthTracker` separates global node failures from API/plugin-specific\n * failures. A node missing `rc_api` can be deprioritized for RC calls while\n * remaining available for database reads. It also tracks rate-limit cooldowns\n * and stale head-block data so Pollen can prefer fresher nodes.\n *\n * @example\n * ```ts\n * const tracker = new NodeHealthTracker({ staleBlockThreshold: 20 })\n * tracker.recordSuccess('https://api.hive.blog', 'condenser_api')\n *\n * const ordered = tracker.getOrderedNodes([\n *   'https://api.hive.blog',\n *   'https://api.openhive.network'\n * ])\n * ```\n */\nexport class NodeHealthTracker {\n  private health: Map<string, NodeState> = new Map();\n  private bestKnownHeadBlock: number = 0;\n  private bestKnownHeadBlockTime: number = 0;\n\n  private readonly nodeCooldownMs: number;\n  private readonly apiCooldownMs: number;\n  private readonly maxFailuresBeforeCooldown: number;\n  private readonly maxApiFailuresBeforeCooldown: number;\n  private readonly staleBlockThreshold: number;\n  private readonly headBlockTtlMs: number;\n  private readonly defaultRateLimitMs: number;\n\n  /**\n   * Creates a health tracker with optional cooldown and freshness tuning.\n   *\n   * @param options - Health tracker thresholds and cooldown durations.\n   */\n  constructor(options: HealthTrackerOptions = {}) {\n    this.nodeCooldownMs = options.nodeCooldownMs ?? 30_000;\n    this.apiCooldownMs = options.apiCooldownMs ?? 60_000;\n    this.maxFailuresBeforeCooldown = options.maxFailuresBeforeCooldown ?? 3;\n    this.maxApiFailuresBeforeCooldown = options.maxApiFailuresBeforeCooldown ?? 2;\n    this.staleBlockThreshold = options.staleBlockThreshold ?? 30;\n    this.headBlockTtlMs = options.headBlockTtlMs ?? 120_000;\n    this.defaultRateLimitMs = options.defaultRateLimitMs ?? 10_000;\n  }\n\n  private getOrCreate(node: string): NodeState {\n    let state = this.health.get(node);\n    if (!state) {\n      state = {\n        apiFailures: new Map(),\n        consecutiveFailures: 0,\n        lastFailure: 0,\n        headBlock: 0,\n        headBlockUpdatedAt: 0,\n      };\n      this.health.set(node, state);\n    }\n    return state;\n  }\n\n  /**\n   * Records a successful call to a node for a specific API.\n   *\n   * @param node - RPC endpoint URL.\n   * @param api - API namespace that succeeded.\n   *\n   * @remarks\n   * Success clears the global consecutive failure counter and any API-specific\n   * failures for the namespace that just succeeded.\n   *\n   * @example\n   * ```ts\n   * tracker.recordSuccess('https://api.hive.blog', 'condenser_api')\n   * ```\n   */\n  recordSuccess(node: string, api: string): void {\n    const state = this.getOrCreate(node);\n    state.consecutiveFailures = 0;\n    state.apiFailures.delete(api);\n  }\n\n  /**\n   * Records a network-level failure for a node and API.\n   *\n   * @param node - RPC endpoint URL.\n   * @param api - API namespace that failed.\n   *\n   * @remarks\n   * Network failures increment both the global consecutive failure count and the\n   * API-specific failure count because they make the whole endpoint suspect.\n   *\n   * @example\n   * ```ts\n   * tracker.recordFailure('https://api.hive.blog', 'bridge')\n   * ```\n   */\n  recordFailure(node: string, api: string): void {\n    const state = this.getOrCreate(node);\n    state.consecutiveFailures++;\n    state.lastFailure = Date.now();\n\n    this.incrementApiFailure(state, api);\n  }\n\n  /**\n   * Records that a node returned HTTP 429.\n   *\n   * @param node - RPC endpoint URL.\n   * @param retryAfterSeconds - Optional `Retry-After` header value in seconds.\n   *\n   * @remarks\n   * Rate-limited nodes are skipped until their cooldown expires. If the server\n   * omits `Retry-After`, Pollen uses `defaultRateLimitMs`.\n   *\n   * @example\n   * ```ts\n   * tracker.recordRateLimit('https://api.hive.blog', 10)\n   * ```\n   */\n  recordRateLimit(node: string, retryAfterSeconds?: number): void {\n    const state = this.getOrCreate(node);\n    const delayMs = retryAfterSeconds != null ? retryAfterSeconds * 1000 : this.defaultRateLimitMs;\n    state.rateLimit = { retryAfter: Date.now() + delayMs };\n    state.consecutiveFailures++;\n    state.lastFailure = Date.now();\n  }\n\n  /**\n   * Checks whether a node is currently in a rate-limit cooldown.\n   *\n   * @param node - RPC endpoint URL.\n   * @returns True when a prior 429 cooldown has not expired.\n   *\n   * @example\n   * ```ts\n   * if (!tracker.isRateLimited(node)) {\n   *   // node can be attempted\n   * }\n   * ```\n   */\n  isRateLimited(node: string): boolean {\n    const state = this.health.get(node);\n    if (!state?.rateLimit) return false;\n    return Date.now() < state.rateLimit.retryAfter;\n  }\n\n  /**\n   * Records an API/plugin-specific failure.\n   *\n   * @param node - RPC endpoint URL.\n   * @param api - API namespace that failed.\n   *\n   * @remarks\n   * This does not increment the global node failure counter. It is designed for\n   * cases such as `method not found` where one plugin is disabled but other APIs\n   * on the same node may still be healthy.\n   *\n   * @example\n   * ```ts\n   * tracker.recordApiFailure('https://api.hive.blog', 'transaction_status_api')\n   * ```\n   */\n  recordApiFailure(node: string, api: string): void {\n    const state = this.getOrCreate(node);\n    this.incrementApiFailure(state, api);\n  }\n\n  private incrementApiFailure(state: NodeState, api: string): void {\n    const apiState = state.apiFailures.get(api) || { count: 0, lastFailure: 0 };\n    apiState.count++;\n    apiState.lastFailure = Date.now();\n    state.apiFailures.set(api, apiState);\n  }\n\n  /**\n   * Updates the last observed head block number for a node.\n   *\n   * @param node - RPC endpoint URL.\n   * @param headBlock - Head block number reported by the node.\n   *\n   * @remarks\n   * The client calls this passively when\n   * `get_dynamic_global_properties` responses are observed, allowing failover to\n   * prefer nodes that are not lagging behind the best known head.\n   *\n   * @example\n   * ```ts\n   * tracker.updateHeadBlock('https://api.hive.blog', 90_000_000)\n   * ```\n   */\n  updateHeadBlock(node: string, headBlock: number): void {\n    if (!headBlock || headBlock <= 0) return;\n    const state = this.getOrCreate(node);\n    state.headBlock = headBlock;\n    state.headBlockUpdatedAt = Date.now();\n    if (headBlock > this.bestKnownHeadBlock) {\n      this.bestKnownHeadBlock = headBlock;\n      this.bestKnownHeadBlockTime = Date.now();\n    }\n  }\n\n  /**\n   * Checks whether a node should be preferred for a given API.\n   *\n   * @param node - RPC endpoint URL.\n   * @param api - Optional API namespace for plugin-specific health.\n   * @returns True when the node is not cooling down, rate-limited, or stale.\n   *\n   * @example\n   * ```ts\n   * const healthy = tracker.isNodeHealthy('https://api.hive.blog', 'bridge')\n   * ```\n   */\n  isNodeHealthy(node: string, api?: string): boolean {\n    const state = this.health.get(node);\n    if (!state) return true; // Unknown nodes are assumed healthy\n\n    const now = Date.now();\n\n    // Check rate-limit cooldown (429 received)\n    if (state.rateLimit && now < state.rateLimit.retryAfter) {\n      return false;\n    }\n\n    // Check overall node health (consecutive failures)\n    if (state.consecutiveFailures >= this.maxFailuresBeforeCooldown) {\n      if (now - state.lastFailure < this.nodeCooldownMs) {\n        return false;\n      }\n    }\n\n    // Check API-specific health\n    if (api) {\n      const apiState = state.apiFailures.get(api);\n      if (apiState && apiState.count >= this.maxApiFailuresBeforeCooldown) {\n        if (now - apiState.lastFailure < this.apiCooldownMs) {\n          return false;\n        }\n      }\n    }\n\n    // Check head block staleness\n    if (\n      state.headBlock > 0 &&\n      this.bestKnownHeadBlock > 0 &&\n      now - state.headBlockUpdatedAt < this.headBlockTtlMs &&\n      now - this.bestKnownHeadBlockTime < this.headBlockTtlMs\n    ) {\n      if (this.bestKnownHeadBlock - state.headBlock > this.staleBlockThreshold) {\n        return false;\n      }\n    }\n\n    return true;\n  }\n\n  /**\n   * Orders endpoint URLs by current health for an API call.\n   *\n   * @param allNodes - Endpoints in caller-preferred order.\n   * @param api - Optional API namespace for plugin-specific health.\n   * @returns Healthy nodes first, preserving relative order, followed by\n   * unhealthy nodes as fallback.\n   *\n   * @example\n   * ```ts\n   * const ordered = tracker.getOrderedNodes(nodes, 'condenser_api')\n   * ```\n   */\n  getOrderedNodes(allNodes: string[], api?: string): string[] {\n    const healthy: string[] = [];\n    const unhealthy: string[] = [];\n\n    for (const node of allNodes) {\n      if (this.isNodeHealthy(node, api)) {\n        healthy.push(node);\n      } else {\n        unhealthy.push(node);\n      }\n    }\n\n    return [...healthy, ...unhealthy];\n  }\n\n  /**\n   * Clears all tracked health, rate-limit, and freshness data.\n   *\n   * @example\n   * ```ts\n   * tracker.reset()\n   * ```\n   */\n  reset(): void {\n    this.health.clear();\n    this.bestKnownHeadBlock = 0;\n    this.bestKnownHeadBlockTime = 0;\n  }\n\n  /**\n   * Returns a diagnostic snapshot of tracked node health.\n   *\n   * @returns A map keyed by node URL with failure counts, head block, API\n   * failure counts, and current health.\n   *\n   * @example\n   * ```ts\n   * for (const [node, health] of tracker.getHealthSnapshot()) {\n   *   console.log(node, health.healthy)\n   * }\n   * ```\n   */\n  getHealthSnapshot(): Map<\n    string,\n    {\n      consecutiveFailures: number;\n      headBlock: number;\n      apiFailures: Record<string, { count: number }>;\n      healthy: boolean;\n    }\n  > {\n    const snapshot = new Map<string, any>();\n    for (const [node, state] of this.health) {\n      const apiFailures: Record<string, { count: number }> = {};\n      for (const [api, failure] of state.apiFailures) {\n        apiFailures[api] = { count: failure.count };\n      }\n      snapshot.set(node, {\n        consecutiveFailures: state.consecutiveFailures,\n        headBlock: state.headBlock,\n        apiFailures,\n        healthy: this.isNodeHealthy(node),\n      });\n    }\n    return snapshot;\n  }\n}\n", "/**\n * @file Hive RPC client implementation.\n * @author Johan Nordberg <code@johan-nordberg.com>\n * @license\n * Copyright (c) 2017 Johan Nordberg. All Rights Reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n *  1. Redistribution of source code must retain the above copyright notice, this\n *     list of conditions and the following disclaimer.\n *\n *  2. Redistribution in binary form must reproduce the above copyright notice,\n *     this list of conditions and the following disclaimer in the documentation\n *     and/or other materials provided with the distribution.\n *\n *  3. Neither the name of the copyright holder nor the names of its contributors\n *     may be used to endorse or promote products derived from this software without\n *     specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * You acknowledge that this software is not designed, licensed or intended for use\n * in the design, construction, operation or maintenance of any military facility.\n */\n\nimport { RPCError } from \"./errors.js\";\nimport packageVersion from \"./version.js\";\n\nimport { Blockchain } from \"./helpers/blockchain.js\";\nimport { BroadcastAPI } from \"./helpers/broadcast.js\";\nimport { DatabaseAPI } from \"./helpers/database.js\";\nimport { HivemindAPI } from \"./helpers/hivemind.js\";\nimport { AccountByKeyAPI } from \"./helpers/key.js\";\nimport { MarketHistoryAPI } from \"./helpers/market.js\";\nimport { RCAPI } from \"./helpers/rc.js\";\nimport { TransactionStatusAPI } from \"./helpers/transaction.js\";\nimport { NodeHealthTracker, HealthTrackerOptions } from \"./health-tracker.js\";\nimport {\n  assert,\n  copy,\n  exponentialBackoffWithJitter,\n  retryingFetch,\n  fromHex,\n  toHex,\n} from \"./utils.js\";\n\n/**\n * Published Pollen package version.\n *\n * @remarks\n * This value is generated from `package.json` during the build and is also used\n * in Node request metadata so RPC operators can identify Pollen clients.\n *\n * @example\n * ```ts\n * import { VERSION } from '@srbde/pollen'\n *\n * console.log(`Running Pollen ${VERSION}`)\n * ```\n */\nexport const VERSION = packageVersion;\n\n/**\n * Main Hive network chain id as 32 raw bytes.\n *\n * @remarks\n * The chain id is mixed into transaction signatures. Keeping the default here\n * prevents signatures produced for Hive mainnet from being replayed on a\n * different chain.\n *\n * @example\n * ```ts\n * import { DEFAULT_CHAIN_ID } from '@srbde/pollen'\n *\n * console.log(toHex(DEFAULT_CHAIN_ID))\n * ```\n */\nexport const DEFAULT_CHAIN_ID = fromHex(\n  \"beeab0de00000000000000000000000000000000000000000000000000000000\",\n);\n\n/**\n * Main Hive network public-key address prefix.\n *\n * @remarks\n * Hive-compatible public keys are rendered with a network prefix. Mainnet uses\n * `STM`, and custom networks can override this through {@link ClientOptions}.\n */\nexport const DEFAULT_ADDRESS_PREFIX = \"STM\";\n\ninterface RPCRequest {\n  /**\n   * Request sequence number.\n   */\n  id: number | string;\n  /**\n   * RPC method.\n   */\n  method: string;\n  /**\n   * Array of parameters to pass to the method.\n   */\n  jsonrpc: \"2.0\";\n  params: unknown;\n}\n\ninterface RPCCall extends RPCRequest {\n  method: string;\n  /**\n   * 1. API to call, you can pass either the numerical id of the API you get\n   *    from calling 'get_api_by_name' or the name directly as a string.\n   * 2. Method to call on that API.\n   * 3. Arguments to pass to the method.\n   */\n  params: [number | string, string, unknown];\n}\n\ninterface RPCErrorData {\n  code: number;\n  message: string;\n  data?: unknown;\n}\n\ninterface RPCResponse {\n  /**\n   * Response sequence number, corresponding to request sequence number.\n   */\n  id: number;\n  error?: RPCErrorData;\n  result?: unknown;\n}\n\ninterface PendingRequest {\n  request: RPCRequest;\n  timer: NodeJS.Timer | undefined;\n  resolve: (response: RPCResponse) => void;\n  reject: (error: Error) => void;\n}\n\n/**\n * Configuration for a {@link Client} instance.\n *\n * @remarks\n * Options control both protocol identity, such as `chainId` and\n * `addressPrefix`, and resilience behavior, such as timeout, failover, and\n * jittered backoff. A single configured client owns the Nectar helpers for\n * database reads, broadcasting, RC, Hivemind, and transaction-status calls.\n *\n * @example\n * ```ts\n * import { Client } from '@srbde/pollen'\n *\n * const client = new Client(\n *   ['https://api.hive.blog', 'https://api.openhive.network'],\n *   {\n *     timeout: 45_000,\n *     failoverThreshold: 2,\n *     consoleOnFailover: true\n *   }\n * )\n * ```\n */\nexport interface ClientOptions {\n  /**\n   * Hive chain id. Defaults to main hive network:\n   * need the new id?\n   * `beeab0de00000000000000000000000000000000000000000000000000000000`\n   *\n   */\n  chainId?: string;\n  /**\n   * Hive address prefix. Defaults to main network:\n   * `STM`\n   */\n  addressPrefix?: string;\n  /**\n   * Send timeout, how long to wait in milliseconds before giving\n   * up on a rpc call. Note that this is not an exact timeout,\n   * no in-flight requests will be aborted, they will just not\n   * be retried any more past the timeout.\n   * Can be set to 0 to retry forever. Defaults to 60 * 1000 ms.\n   */\n  timeout?: number;\n\n  /**\n   * Specifies the amount of times the urls (RPC nodes) should be\n   * iterated and retried in case of timeout errors.\n   * (important) Requires url parameter to be an array (string[])!\n   * Can be set to 0 to iterate and retry forever. Defaults to 3 rounds.\n   */\n  failoverThreshold?: number;\n\n  /**\n   * Whether a console.log should be made when RPC failed over to another one\n   */\n  consoleOnFailover?: boolean;\n\n  /**\n   * Retry backoff function, returns milliseconds. Defaults to Pollen's\n   * jittered exponential backoff.\n   */\n  backoff?: (tries: number) => number;\n  /**\n   * Node.js http(s) agent, use if you want http keep-alive.\n   * Defaults to using https.globalAgent.\n   * @see https://nodejs.org/api/http.html#http_new_agent_options.\n   */\n  agent?: unknown; // https.Agent\n  /**\n   * Options for the node health tracker.\n   * Controls cooldown periods, stale block thresholds, etc.\n   */\n  healthTrackerOptions?: HealthTrackerOptions;\n}\n\n/**\n * High-level Hive RPC client used by every Pollen helper.\n *\n * @remarks\n * `Client` centralizes JSON-RPC transport, node failover, API health tracking,\n * network identity, and helper construction. It can run in Node.js or a browser\n * bundle and exposes purpose-built helpers such as {@link DatabaseAPI},\n * broadcasting, and {@link Blockchain} so application code rarely needs\n * to assemble raw RPC payloads.\n *\n * @example\n * ```ts\n * import { Client } from '@srbde/pollen'\n *\n * const client = new Client('https://api.hive.blog')\n * const props = await client.database.getDynamicGlobalProperties()\n *\n * console.log(`Hive head block: ${props.head_block_number}`)\n * ```\n *\n * @see {@link ClientOptions}\n * @see {@link RPCError}\n */\nexport class Client {\n  /**\n   * Client options, *read-only*.\n   */\n  public readonly options: ClientOptions;\n\n  /**\n   * Address to Hive RPC server.\n   * String or String[] *read-only*\n   */\n  public address: string | string[];\n\n  /**\n   * Database API helper.\n   */\n  public readonly database: DatabaseAPI;\n\n  /**\n   * RC API helper.\n   */\n  public readonly rc: RCAPI;\n\n  /**\n   * Broadcast API helper.\n   */\n  public readonly broadcast: BroadcastAPI;\n\n  /**\n   * Blockchain helper.\n   */\n  public readonly blockchain: Blockchain;\n\n  /**\n   * Market History API helper.\n   */\n  public readonly market: MarketHistoryAPI;\n\n  /**\n   * Hivemind helper.\n   */\n  public readonly hivemind: HivemindAPI;\n\n  /**\n   * Accounts by key API helper.\n   */\n  public readonly keys: AccountByKeyAPI;\n\n  /**\n   * Transaction status API helper.\n   */\n  public readonly transaction: TransactionStatusAPI;\n\n  /**\n   * Node health tracker for smart failover.\n   * Tracks per-node, per-API health and head block freshness.\n   */\n  public readonly healthTracker: NodeHealthTracker;\n\n  /**\n   * Chain ID for current network.\n   */\n  public readonly chainId: Uint8Array;\n\n  /**\n   * Address prefix for current network.\n   */\n  public readonly addressPrefix: string;\n\n  private timeout: number;\n  private backoff: typeof defaultBackoff;\n\n  private failoverThreshold: number;\n\n  private consoleOnFailover: boolean;\n\n  public currentAddress: string;\n\n  /**\n   * Creates a client for one or more Hive RPC endpoints.\n   *\n   * @param address - RPC endpoint URL or ordered failover list. For example,\n   * `https://api.hive.blog` or `['https://api.hive.blog', 'https://api.openhive.network']`.\n   * @param options - Network identity and resilience settings.\n   *\n   * @remarks\n   * The first endpoint becomes the active node. When calls fail, Pollen uses\n   * the configured backoff and health tracker to move across the endpoint\n   * list without requiring callers to recreate helper objects.\n   *\n   * @throws AssertionError\n   * Thrown when `options.chainId` is not exactly 32 bytes after hex decoding.\n   *\n   * @example\n   * ```ts\n   * import { Client } from '@srbde/pollen'\n   *\n   * const client = new Client(\n   *   ['https://api.hive.blog', 'https://api.deathwing.me'],\n   *   { timeout: 30_000, failoverThreshold: 2 }\n   * )\n   *\n   * const accounts = await client.database.getAccounts(['srbde'])\n   * console.log(accounts[0].balance)\n   * ```\n   */\n  constructor(address: string | string[], options: ClientOptions = {}) {\n    this.currentAddress = Array.isArray(address) ? address[0] : address;\n    this.address = address;\n    this.options = options;\n\n    this.chainId = options.chainId ? fromHex(options.chainId) : DEFAULT_CHAIN_ID;\n    assert(this.chainId.length === 32, \"invalid chain id\");\n    this.addressPrefix = options.addressPrefix || DEFAULT_ADDRESS_PREFIX;\n\n    this.timeout = options.timeout || 60 * 1000;\n    this.backoff = options.backoff || defaultBackoff;\n    this.failoverThreshold = options.failoverThreshold || 3;\n    this.consoleOnFailover = options.consoleOnFailover || false;\n\n    this.healthTracker = new NodeHealthTracker(options.healthTrackerOptions);\n    this.database = new DatabaseAPI(this);\n    this.broadcast = new BroadcastAPI(this);\n    this.market = new MarketHistoryAPI(this);\n    this.blockchain = new Blockchain(this);\n    this.rc = new RCAPI(this);\n    this.hivemind = new HivemindAPI(this);\n    this.keys = new AccountByKeyAPI(this);\n    this.transaction = new TransactionStatusAPI(this);\n  }\n\n  /**\n   * Creates a client preconfigured for the public Hive testnet.\n   *\n   * @param options - Optional client settings copied into the testnet\n   * configuration.\n   * @returns A {@link Client} targeting `https://api.fake.openhive.network`\n   * with the testnet chain id.\n   *\n   * @remarks\n   * This helper preserves transport options such as custom HTTP agents while\n   * replacing chain identity values so test transactions cannot be confused\n   * with mainnet signatures.\n   *\n   * @example\n   * ```ts\n   * import { Client } from '@srbde/pollen'\n   *\n   * const testnet = Client.testnet({ timeout: 20_000 })\n   * const props = await testnet.database.getDynamicGlobalProperties()\n   * console.log(props.head_block_number)\n   * ```\n   */\n  public static testnet(options?: ClientOptions) {\n    let opts: ClientOptions = {};\n    if (options) {\n      opts = copy(options);\n      opts.agent = options.agent;\n    }\n\n    opts.addressPrefix = \"STM\";\n    opts.chainId = \"4200000000000000000000000000000000000000000000000000000000000000\";\n    return new Client(\"https://api.fake.openhive.network\", opts);\n  }\n\n  /**\n   * Creates a Client instance initialized with healthy nodes fetched dynamically\n   * from nectarflower's on-chain metadata.\n   *\n   * @param options - Additional options for the client.\n   * @param bootstrapNodes - Optional list of bootstrap nodes to fetch metadata from.\n   * Defaults to mainnet public nodes.\n   *\n   * @example\n   * ```ts\n   * import { Client } from '@srbde/pollen'\n   *\n   * const client = await Client.fromNectarflower()\n   * const props = await client.database.getDynamicGlobalProperties()\n   * console.log(props.head_block_number)\n   * ```\n   */\n  public static async fromNectarflower(\n    options?: ClientOptions,\n    bootstrapNodes: string | string[] = [\"https://api.hive.blog\", \"https://api.syncad.com\"],\n  ): Promise<Client> {\n    const bootstrapClient = new Client(bootstrapNodes, options);\n    const accounts = await bootstrapClient.database.getAccounts([\"nectarflower\"]);\n    if (!accounts || accounts.length === 0) {\n      throw new Error(\"Failed to fetch nectarflower account metadata\");\n    }\n    const meta = JSON.parse(accounts[0].json_metadata);\n    if (!meta || !Array.isArray(meta.nodes) || meta.nodes.length === 0) {\n      throw new Error(\"Invalid nectarflower node metadata structure\");\n    }\n    return new Client(meta.nodes, options);\n  }\n\n  /**\n   * Sends a JSON-RPC request through the configured failover transport.\n   *\n   * @param api - API namespace to call, such as `condenser_api`.\n   * @param method - Method within the API namespace, such as\n   * `get_dynamic_global_properties`.\n   * @param params - Positional RPC parameters. Defaults to an empty array.\n   * @returns The decoded `result` member returned by the RPC node.\n   *\n   * @remarks\n   * The transport serializes `Uint8Array` values as Hive-compatible hex strings, applies\n   * jittered retry backoff, tracks API-specific node failures, and passively\n   * records head-block freshness from `get_dynamic_global_properties`\n   * responses. Broadcast calls skip the short per-fetch timeout because they\n   * must not be retried as aggressively as read-only calls.\n   *\n   * @throws RPCError\n   * Thrown when the node returns a JSON-RPC error. The `info` property carries\n   * the original error data when the node provides it.\n   * @throws AssertionError\n   * Thrown when the response id does not match the request id.\n   *\n   * @example\n   * ```ts\n   * import { Client } from '@srbde/pollen'\n   *\n   * const client = new Client('https://api.hive.blog')\n   * const config = await client.call('condenser_api', 'get_config')\n   *\n   * console.log(config.HIVE_BLOCK_INTERVAL)\n   * ```\n   *\n   * @see {@link retryingFetch}\n   * @see {@link NodeHealthTracker}\n   */\n  public async call<T = unknown>(api: string, method: string, params: unknown = []): Promise<T> {\n    const isBroadcast =\n      api === \"network_broadcast_api\" || method.startsWith(\"broadcast_transaction\");\n\n    const request: RPCRequest = {\n      id: 0,\n      jsonrpc: \"2.0\",\n      method: api + \".\" + method,\n      params,\n    };\n    const body = serializeRpcBody(request);\n    const opts: RequestInit & { agent?: unknown } = {\n      body,\n      cache: \"no-cache\",\n      headers: {\n        Accept: \"application/json, text/plain, */*\",\n        \"Content-Type\": \"application/json\",\n      },\n      method: \"POST\",\n      mode: \"cors\",\n    };\n\n    // Self is not defined within Node environments\n    // This check is needed because the user agent cannot be set in a browser\n    if (typeof self === undefined) {\n      opts.headers = {\n        \"User-Agent\": `pollen/${packageVersion}`,\n      };\n    }\n\n    if (this.options.agent) {\n      opts.agent = this.options.agent;\n    }\n    let fetchTimeout: ((tries: number) => number) | undefined;\n    if (!isBroadcast) {\n      // bit of a hack to work around some nodes high error rates\n      // only effective in node.js (until timeout spec lands in browsers)\n      fetchTimeout = (tries: number) => (tries + 1) * 500;\n    }\n\n    const { response, currentAddress }: { response: RPCResponse; currentAddress: string } =\n      await retryingFetch(\n        this.currentAddress,\n        this.address,\n        opts,\n        this.timeout,\n        this.failoverThreshold,\n        this.consoleOnFailover,\n        this.backoff,\n        fetchTimeout,\n        {\n          healthTracker: this.healthTracker,\n          api,\n          isBroadcast,\n          consoleOnFailover: this.consoleOnFailover,\n        },\n      );\n\n    // After failover, change the currently active address\n    if (currentAddress !== this.currentAddress) {\n      this.currentAddress = currentAddress;\n    }\n\n    // Passively track head block from get_dynamic_global_properties responses.\n    // This costs nothing \u2014 we just inspect data we already fetched.\n    if (\n      response.result &&\n      method === \"get_dynamic_global_properties\" &&\n      typeof response.result === \"object\" &&\n      \"head_block_number\" in response.result\n    ) {\n      this.healthTracker.updateHeadBlock(\n        currentAddress,\n        (response.result as any).head_block_number,\n      );\n    }\n\n    // Handle RPC-level errors.\n    // Unlike network errors, these mean the node responded but returned an error.\n    // We record it as an API-specific failure so the health tracker can\n    // deprioritize this node for this API in future calls.\n    if (response.error) {\n      const formatValue = (value: unknown): string => {\n        switch (typeof value) {\n          case \"object\":\n            return JSON.stringify(value);\n          default:\n            return String(value);\n        }\n      };\n      const data = response.error.data as\n        | {\n            stack?: {\n              data: Record<string, unknown>;\n              format: string;\n            }[];\n          }\n        | undefined;\n      let { message } = response.error;\n      if (data && data.stack && data.stack.length > 0) {\n        const top = data.stack[0];\n        const topData = copy(top.data);\n        let formatStr = top.format;\n        if (formatStr.length > 2000) {\n          formatStr = formatStr.slice(0, 2000);\n        }\n        let parsedMessage = \"\";\n        let lastIdx = 0;\n        while (true) {\n          const startIdx = formatStr.indexOf(\"${\", lastIdx);\n          if (startIdx === -1) {\n            parsedMessage += formatStr.slice(lastIdx);\n            break;\n          }\n          parsedMessage += formatStr.slice(lastIdx, startIdx);\n          const endIdx = formatStr.indexOf(\"}\", startIdx + 2);\n          if (endIdx === -1) {\n            parsedMessage += formatStr.slice(startIdx);\n            break;\n          }\n          const key = formatStr.slice(startIdx + 2, endIdx);\n          if (/^[a-z_]+$/i.test(key)) {\n            if (topData[key] !== undefined) {\n              parsedMessage += formatValue(topData[key]);\n              delete topData[key];\n            } else {\n              parsedMessage += \"${\" + key + \"}\";\n            }\n          } else {\n            parsedMessage += formatStr.slice(startIdx, endIdx + 1);\n          }\n          lastIdx = endIdx + 1;\n        }\n        message = parsedMessage;\n        const unformattedData = Object.keys(topData)\n          .map((key) => ({ key, value: formatValue(topData[key]) }))\n          .map((item) => `${item.key}=${item.value}`);\n        if (unformattedData.length > 0) {\n          message += \" \" + unformattedData.join(\" \");\n        }\n      }\n\n      // Track RPC errors that indicate node/plugin issues (not user errors).\n      // JSON-RPC error codes (response.error.code):\n      //   -32601 = Method not found (plugin not enabled on this node)\n      //   -32603 = Internal error (node issue)\n      //   -32003 = Hive assertion error (user error \u2014 bad params, invalid account)\n      //   -32003 is technically not a node failure, but we want failover for it in some cases.\n      const rpcCode = response.error.code;\n      if (rpcCode === -32601 || rpcCode === -32603) {\n        this.healthTracker.recordApiFailure(currentAddress, api);\n      }\n\n      throw new RPCError(message, response.error.data);\n    }\n    assert(response.id === request.id, \"got invalid response id\");\n    return response.result as T;\n  }\n}\n\n/**\n * Serializes an RPC request body to a JSON string with support for BigInt and Uint8Array.\n *\n * `JSON.stringify` cannot emit BigInt as a raw JSON integer \u2014 it either throws or, when coerced\n * to Number first, loses precision for values above 2^53. This is a real hazard for\n * `condenser_api.get_account_history` filter params (e.g. `fill_order` is bit 57 = 2^57).\n * A placeholder-and-replace approach is unsafe because arbitrary string params (memos,\n * custom_json) could collide with the placeholder pattern. This recursive serializer\n * handles both types natively and is correct by construction.\n */\nfunction serializeRpcBody(value: unknown): string {\n  if (value === null || value === undefined) return \"null\";\n  if (typeof value === \"bigint\") return value.toString();\n  if (typeof value === \"boolean\" || typeof value === \"number\") return JSON.stringify(value);\n  if (typeof value === \"string\") return JSON.stringify(value);\n  if (value instanceof Uint8Array) return JSON.stringify(toHex(value));\n  if (Array.isArray(value)) return \"[\" + value.map(serializeRpcBody).join(\",\") + \"]\";\n  if (typeof value === \"object\") {\n    const pairs = Object.entries(value)\n      .filter(([, v]) => v !== undefined)\n      .map(([k, v]) => `${JSON.stringify(k)}:${serializeRpcBody(v)}`);\n    return \"{\" + pairs.join(\",\") + \"}\";\n  }\n  return \"null\";\n}\n\n/**\n * Returns Pollen's default retry delay for a failed RPC attempt.\n *\n * @param tries - Number of attempts already made.\n * @returns A jittered exponential delay in milliseconds.\n *\n * @remarks\n * Jitter prevents multiple clients from retrying in lockstep against the same\n * RPC node, reducing thundering-herd behavior during transient outages.\n *\n * @example\n * ```ts\n * const delayMs = defaultBackoff(3)\n * ```\n */\nconst defaultBackoff = (tries: number): number => exponentialBackoffWithJitter(tries);\n", "/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n/** Transforms values between two representations. */\nexport interface Coder<F, T> {\n  /**\n   * Converts a value from the input representation to the output representation.\n   * @param from - Value in the source representation.\n   * @returns Converted value.\n   */\n  encode(from: F): T;\n  /**\n   * Converts a value from the output representation back to the input representation.\n   * @param to - Value in the target representation.\n   * @returns Converted value.\n   */\n  decode(to: T): F;\n}\n\n/** Coder that works with byte arrays and strings. */\nexport interface BytesCoder extends Coder<Uint8Array, string> {\n  /**\n   * Encodes bytes into a string representation.\n   * @param data - Bytes to encode.\n   * @returns Encoded string.\n   */\n  encode: (data: Uint8Array) => string;\n  /**\n   * Decodes a string representation into raw bytes.\n   * @param str - Encoded string.\n   * @returns Decoded bytes.\n   */\n  decode: (str: string) => Uint8Array;\n}\n\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg<T> = T extends BigInt64Array\n  ? BigInt64Array\n  : T extends BigUint64Array\n    ? BigUint64Array\n    : T extends Float32Array\n      ? Float32Array\n      : T extends Float64Array\n        ? Float64Array\n        : T extends Int16Array\n          ? Int16Array\n          : T extends Int32Array\n            ? Int32Array\n            : T extends Int8Array\n              ? Int8Array\n              : T extends Uint16Array\n                ? Uint16Array\n                : T extends Uint32Array\n                  ? Uint32Array\n                  : T extends Uint8ClampedArray\n                    ? Uint8ClampedArray\n                    : T extends Uint8Array\n                      ? Uint8Array\n                      : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet<T> = T extends BigInt64Array\n  ? ReturnType<typeof BigInt64Array.of>\n  : T extends BigUint64Array\n    ? ReturnType<typeof BigUint64Array.of>\n    : T extends Float32Array\n      ? ReturnType<typeof Float32Array.of>\n      : T extends Float64Array\n        ? ReturnType<typeof Float64Array.of>\n        : T extends Int16Array\n          ? ReturnType<typeof Int16Array.of>\n          : T extends Int32Array\n            ? ReturnType<typeof Int32Array.of>\n            : T extends Int8Array\n              ? ReturnType<typeof Int8Array.of>\n              : T extends Uint16Array\n                ? ReturnType<typeof Uint16Array.of>\n                : T extends Uint32Array\n                  ? ReturnType<typeof Uint32Array.of>\n                  : T extends Uint8ClampedArray\n                    ? ReturnType<typeof Uint8ClampedArray.of>\n                    : T extends Uint8Array\n                      ? ReturnType<typeof Uint8Array.of>\n                      : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg<T> =\n  | T\n  | ([TypedArg<T>] extends [never]\n      ? T extends (...args: infer A) => infer R\n        ? ((...args: { [K in keyof A]: TRet<A[K]> }) => TArg<R>) & {\n            [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;\n          }\n        : T extends [infer A, ...infer R]\n          ? [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n          : T extends readonly [infer A, ...infer R]\n            ? readonly [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n            : T extends (infer A)[]\n              ? TArg<A>[]\n              : T extends readonly (infer A)[]\n                ? readonly TArg<A>[]\n                : T extends Promise<infer A>\n                  ? Promise<TArg<A>>\n                  : T extends object\n                    ? { [K in keyof T]: TArg<T[K]> }\n                    : T\n      : TypedArg<T>);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet<T> = T extends unknown\n  ? T &\n      ([TypedRet<T>] extends [never]\n        ? T extends (...args: infer A) => infer R\n          ? ((...args: { [K in keyof A]: TArg<A[K]> }) => TRet<R>) & {\n              [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;\n            }\n          : T extends [infer A, ...infer R]\n            ? [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n            : T extends readonly [infer A, ...infer R]\n              ? readonly [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n              : T extends (infer A)[]\n                ? TRet<A>[]\n                : T extends readonly (infer A)[]\n                  ? readonly TRet<A>[]\n                  : T extends Promise<infer A>\n                    ? Promise<TRet<A>>\n                    : T extends object\n                      ? { [K in keyof T]: TRet<T[K]> }\n                      : T\n        : TypedRet<T>)\n  : never;\n\nfunction isBytes(a: unknown): a is Uint8Array {\n  // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases. The\n  // fallback still requires a real ArrayBuffer view, so plain JSON-deserialized\n  // `{ constructor: ... }` spoofing is rejected. `BYTES_PER_ELEMENT === 1` keeps the\n  // fallback on byte-oriented views.\n  return (\n    a instanceof Uint8Array ||\n    (ArrayBuffer.isView(a) &&\n      a.constructor.name === 'Uint8Array' &&\n      'BYTES_PER_ELEMENT' in a &&\n      a.BYTES_PER_ELEMENT === 1)\n  );\n}\n/** Asserts something is Uint8Array. */\nfunction abytes(b: TArg<Uint8Array | undefined>): void {\n  if (!isBytes(b)) throw new TypeError('Uint8Array expected');\n}\n\nfunction isArrayOf(isString: boolean, arr: any[]) {\n  if (!Array.isArray(arr)) return false;\n  if (arr.length === 0) return true;\n  if (isString) {\n    return arr.every((item) => typeof item === 'string');\n  } else {\n    return arr.every((item) => Number.isSafeInteger(item));\n  }\n}\n\nfunction afn(input: Function): input is Function {\n  if (typeof input !== 'function') throw new TypeError('function expected');\n  return true;\n}\n\nfunction astr(label: string, input: unknown): input is string {\n  if (typeof input !== 'string') throw new TypeError(`${label}: string expected`);\n  return true;\n}\n\nfunction anumber(n: number): void {\n  if (typeof n !== 'number') throw new TypeError(`number expected, got ${typeof n}`);\n  if (!Number.isSafeInteger(n)) throw new RangeError(`invalid integer: ${n}`);\n}\n\nfunction aArr(input: any[]) {\n  if (!Array.isArray(input)) throw new TypeError('array expected');\n}\nfunction astrArr(label: string, input: string[]) {\n  if (!isArrayOf(true, input)) throw new TypeError(`${label}: array of strings expected`);\n}\nfunction anumArr(label: string, input: number[]) {\n  if (!isArrayOf(false, input)) throw new TypeError(`${label}: array of numbers expected`);\n}\n\n// TODO: some recusive type inference so it would check correct order of input/output inside rest?\n// like <string, number>, <number, bytes>, <bytes, float>\ntype Chain = [Coder<any, any>, ...Coder<any, any>[]];\n// Extract info from Coder type\ntype Input<F> = F extends Coder<infer T, any> ? T : never;\ntype Output<F> = F extends Coder<any, infer T> ? T : never;\n// Generic function for arrays\ntype First<T> = T extends [infer U, ...any[]] ? U : never;\ntype Last<T> = T extends [...any[], infer U] ? U : never;\ntype Tail<T> = T extends [any, ...infer U] ? U : never;\n\ntype AsChain<C extends Chain, Rest = Tail<C>> = {\n  // C[K] = Coder<Input<C[K]>, Input<Rest[k]>>\n  [K in keyof C]: Coder<Input<C[K]>, Input<K extends keyof Rest ? Rest[K] : any>>;\n};\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction chain<T extends Chain & AsChain<T>>(...args: T): Coder<Input<First<T>>, Output<Last<T>>> {\n  const id = (a: any) => a;\n  // Wrap call in closure so JIT can inline calls\n  const wrap = (a: any, b: any) => (c: any) => a(b(c));\n  // Construct chain of args[-1].encode(args[-2].encode([...]))\n  const encode = args.map((x) => x.encode).reduceRight(wrap, id);\n  // Construct chain of args[0].decode(args[1].decode(...))\n  const decode = args.map((x) => x.decode).reduce(wrap, id);\n  return { encode, decode };\n}\n\n/**\n * Encodes integer radix representation to array of strings using alphabet and back.\n * Could also be array of strings.\n * @__NO_SIDE_EFFECTS__\n */\nfunction alphabet(letters: string | string[]): Coder<number[], string[]> {\n  // mapping 1 to \"b\"\n  const lettersA = typeof letters === 'string' ? letters.split('') : letters;\n  const len = lettersA.length;\n  astrArr('alphabet', lettersA);\n\n  // mapping \"b\" to 1\n  const indexes = new Map(lettersA.map((l, i) => [l, i]));\n  return {\n    encode: (digits: number[]) => {\n      aArr(digits);\n      return digits.map((i) => {\n        if (!Number.isSafeInteger(i) || i < 0 || i >= len)\n          throw new Error(\n            `alphabet.encode: digit index outside alphabet \"${i}\". Allowed: ${letters}`\n          );\n        return lettersA[i]!;\n      });\n    },\n    decode: (input: string[]): number[] => {\n      aArr(input);\n      return input.map((letter) => {\n        astr('alphabet.decode', letter);\n        const i = indexes.get(letter);\n        if (i === undefined) throw new Error(`Unknown letter: \"${letter}\". Allowed: ${letters}`);\n        return i;\n      });\n    },\n  };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction join(separator = ''): Coder<string[], string> {\n  astr('join', separator);\n  // join('') is only lossless when each chunk is already unambiguous, such as single-symbol alphabets.\n  // Multi-character tokens need a separator that cannot appear inside the chunks.\n  return {\n    encode: (from) => {\n      astrArr('join.decode', from);\n      return from.join(separator);\n    },\n    decode: (to) => {\n      astr('join.decode', to);\n      return to.split(separator);\n    },\n  };\n}\n\n/**\n * Pad strings array so it has integer number of bits\n * @__NO_SIDE_EFFECTS__\n */\nfunction padding(bits: number, chr = '='): Coder<string[], string[]> {\n  anumber(bits);\n  astr('padding', chr);\n  return {\n    encode(data: string[]): string[] {\n      astrArr('padding.encode', data);\n      // Mutates the intermediate token array in place while appending pad chars.\n      // utils.padding callers that need to preserve their input should pass a copy.\n      while ((data.length * bits) % 8) data.push(chr);\n      return data;\n    },\n    decode(input: string[]): string[] {\n      astrArr('padding.decode', input);\n      let end = input.length;\n      if ((end * bits) % 8)\n        throw new Error('padding: invalid, string should have whole number of bytes');\n      for (; end > 0 && input[end - 1] === chr; end--) {\n        const last = end - 1;\n        const byte = last * bits;\n        if (byte % 8 === 0) throw new Error('padding: invalid, string has too much padding');\n      }\n      return input.slice(0, end);\n    },\n  };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction normalize<T>(fn: (val: T) => T): Coder<T, T> {\n  afn(fn);\n  return { encode: (from: T) => from, decode: (to: T) => fn(to) };\n}\n\n/**\n * Slow: O(n^2) time complexity\n */\nfunction convertRadix(data: number[], from: number, to: number): number[] {\n  // base 1 is impossible\n  if (from < 2)\n    throw new RangeError(`convertRadix: invalid from=${from}, base cannot be less than 2`);\n  if (to < 2) throw new RangeError(`convertRadix: invalid to=${to}, base cannot be less than 2`);\n  aArr(data);\n  if (!data.length) return [];\n  let pos = 0;\n  const res = [];\n  const digits = Array.from(data, (d) => {\n    anumber(d);\n    if (d < 0 || d >= from) throw new Error(`invalid integer: ${d}`);\n    return d;\n  });\n  const dlen = digits.length;\n  while (true) {\n    let carry = 0;\n    let done = true;\n    for (let i = pos; i < dlen; i++) {\n      const digit = digits[i]!;\n      const fromCarry = from * carry;\n      const digitBase = fromCarry + digit;\n      if (\n        !Number.isSafeInteger(digitBase) ||\n        fromCarry / from !== carry ||\n        digitBase - digit !== fromCarry\n      ) {\n        throw new Error('convertRadix: carry overflow');\n      }\n      const div = digitBase / to;\n      carry = digitBase % to;\n      const rounded = Math.floor(div);\n      digits[i] = rounded;\n      if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)\n        throw new Error('convertRadix: carry overflow');\n      if (!done) continue;\n      else if (!rounded) pos = i;\n      else done = false;\n    }\n    res.push(carry);\n    if (done) break;\n  }\n  // Preserve explicit leading zero digits so callers like base58 keep zero-prefix semantics.\n  for (let i = 0; i < data.length - 1 && data[i] === 0; i++) res.push(0);\n  return res.reverse();\n}\n\nconst gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));\n// Maximum carry width before the `pos` cycle repeats.\n// Residues advance in gcd(from, to) steps, so the largest pre-drain width is from + (to - gcd).\nconst radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from: number, to: number) =>\n  from + (to - gcd(from, to));\nconst powers: number[] = /* @__PURE__ */ (() => {\n  let res = [];\n  for (let i = 0; i < 40; i++) res.push(2 ** i);\n  return res;\n})();\n/**\n * Implemented with numbers, because BigInt is 5x slower\n */\nfunction convertRadix2(data: number[], from: number, to: number, padding: boolean): number[] {\n  aArr(data);\n  if (from <= 0 || from > 32) throw new RangeError(`convertRadix2: wrong from=${from}`);\n  if (to <= 0 || to > 32) throw new RangeError(`convertRadix2: wrong to=${to}`);\n  if (radix2carry(from, to) > 32) {\n    throw new Error(\n      `convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`\n    );\n  }\n  let carry = 0;\n  let pos = 0; // bitwise position in current element\n  const max = powers[from]!;\n  const mask = powers[to]! - 1;\n  const res: number[] = [];\n  for (const n of data) {\n    anumber(n);\n    if (n >= max) throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);\n    carry = (carry << from) | n;\n    if (pos + from > 32) throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);\n    pos += from;\n    for (; pos >= to; pos -= to) res.push(((carry >> (pos - to)) & mask) >>> 0);\n    const pow = powers[pos];\n    if (pow === undefined) throw new Error('invalid carry');\n    carry &= pow - 1; // clean carry, otherwise it will cause overflow\n  }\n  carry = (carry << (to - pos)) & mask;\n  // Canonical decode paths reject leftover whole input words and non-zero pad bits.\n  // For Bech32 5->8 regrouping, this is the \"4 bits or less, all zeroes\" tail rule.\n  if (!padding && pos >= from) throw new Error('Excess padding');\n  if (!padding && carry > 0) throw new Error(`Non-zero padding: ${carry}`);\n  if (padding && pos > 0) res.push(carry >>> 0);\n  return res;\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix(num: number): TRet<Coder<Uint8Array, number[]>> {\n  anumber(num);\n  const _256 = 2 ** 8;\n  // Base-range and carry-overflow checks live in convertRadix so encode/decode reject unsupported bases symmetrically.\n  return {\n    encode: (bytes: TArg<Uint8Array>) => {\n      if (!isBytes(bytes)) throw new TypeError('radix.encode input should be Uint8Array');\n      return convertRadix(Array.from(bytes), _256, num);\n    },\n    decode: (digits: number[]) => {\n      anumArr('radix.decode', digits);\n      return Uint8Array.from(convertRadix(digits, num, _256));\n    },\n  };\n}\n\n/**\n * If both bases are power of same number (like `2**8 <-> 2**64`),\n * there is a linear algorithm. For now we have implementation for power-of-two bases only.\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix2(bits: number, revPadding = false): TRet<Coder<Uint8Array, number[]>> {\n  anumber(bits);\n  if (bits <= 0 || bits > 32) throw new RangeError('radix2: bits should be in (0..32]');\n  if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)\n    throw new RangeError('radix2: carry overflow');\n  // revPadding flips which direction allows a partial zero tail.\n  // Default pads 8->bits and rejects extra bits on bits->8; `true` does the opposite.\n  return {\n    encode: (bytes: TArg<Uint8Array>) => {\n      if (!isBytes(bytes)) throw new TypeError('radix2.encode input should be Uint8Array');\n      return convertRadix2(Array.from(bytes), 8, bits, !revPadding);\n    },\n    decode: (digits: number[]) => {\n      anumArr('radix2.decode', digits);\n      return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));\n    },\n  };\n}\n\ntype ArgumentTypes<F extends Function> = F extends (...args: infer A) => any ? A : never;\ntype BytesFn = (data: TArg<Uint8Array>) => TRet<Uint8Array>;\nfunction unsafeWrapper<T extends (...args: any) => any>(fn: T) {\n  afn(fn);\n  return function (...args: ArgumentTypes<T>): ReturnType<T> | void {\n    // Only for *Unsafe APIs that intentionally collapse validation failures to `undefined`.\n    // Do not wrap code that needs to preserve exception details.\n    try {\n      return fn.apply(null, args);\n    } catch (e) {}\n  };\n}\n\nfunction checksum(len: number, fn: TArg<BytesFn>): TRet<Coder<Uint8Array, Uint8Array>> {\n  anumber(len);\n  // Reject degenerate zero-byte checksums up front so callers don't accidentally\n  // build a no-op checksum stage.\n  if (len <= 0) throw new RangeError(`checksum length must be positive: ${len}`);\n  afn(fn);\n  const _fn = fn as BytesFn;\n  // Uses the first `len` bytes of fn(data) in both directions.\n  // Current call sites rely on `len > 0` and checksum functions that return at least that many bytes.\n  return {\n    encode(data: TArg<Uint8Array>) {\n      if (!isBytes(data)) throw new TypeError('checksum.encode: input should be Uint8Array');\n      const sum = _fn(data).slice(0, len);\n      const res = new Uint8Array(data.length + len);\n      res.set(data);\n      res.set(sum, data.length);\n      return res;\n    },\n    decode(data: TArg<Uint8Array>) {\n      if (!isBytes(data)) throw new TypeError('checksum.decode: input should be Uint8Array');\n      const payload = data.slice(0, -len);\n      const oldChecksum = data.slice(-len);\n      const newChecksum = _fn(payload).slice(0, len);\n      for (let i = 0; i < len; i++)\n        if (newChecksum[i] !== oldChecksum[i]) throw new Error('Invalid checksum');\n      return payload;\n    },\n  };\n}\n\n// prettier-ignore\n/**\n * Low-level building blocks used by the exported codecs.\n * @example\n * Build a radix-32 coder from the low-level helpers.\n * ```ts\n * import { utils } from '@scure/base';\n * utils.radix2(5).encode(Uint8Array.from([1, 2, 3]));\n * ```\n */\nexport const utils: { alphabet: typeof alphabet; chain: typeof chain; checksum: typeof checksum; convertRadix: typeof convertRadix; convertRadix2: typeof convertRadix2; radix: typeof radix; radix2: typeof radix2; join: typeof join; padding: typeof padding; } = /* @__PURE__ */ Object.freeze({\n  alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,\n});\n\n// RFC 4648 aka RFC 3548\n// ---------------------\n\n/**\n * base16 encoding from RFC 4648.\n * This codec uses RFC 4648 Table 5's uppercase alphabet directly.\n * RFC 4648 \u00A78 calls base16 \"case-insensitive hex encoding\", but we intentionally do not case-fold decode input here.\n * Use `hex` for case-insensitive hex decoding.\n * @example\n * ```js\n * base16.encode(Uint8Array.from([0x12, 0xab]));\n * // => '12AB'\n * ```\n */\nexport const base16: BytesCoder = /* @__PURE__ */ Object.freeze(\n  chain(radix2(4), alphabet('0123456789ABCDEF'), join(''))\n);\n\n/**\n * base32 encoding from RFC 4648. Has padding.\n * RFC 4648 \u00A76 Table 3 uses uppercase letters, and RFC 4648 \u00A73.4 allows applications to choose\n * upper- or lowercase alphabets. We keep the published uppercase table and do not case-fold decode input.\n * Use `base32nopad` for unpadded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ===='\n * base32.decode('CKVQ====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32: BytesCoder = /* @__PURE__ */ Object.freeze(\n  chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join(''))\n);\n\n/**\n * base32 encoding from RFC 4648. No padding.\n * This variant inherits RFC 4648 base32's uppercase table and intentionally does not case-fold decode input.\n * Use `base32` for padded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ'\n * base32nopad.decode('CKVQ');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32nopad: BytesCoder = /* @__PURE__ */ Object.freeze(\n  chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), join(''))\n);\n/**\n * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.\n * RFC 4648 \u00A77 Table 4 uses uppercase letters, and we intentionally keep that table without case-folding decode input.\n * Use `base32hexnopad` for unpadded version.\n * @example\n * ```js\n * base32hex.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG===='\n * base32hex.decode('2ALG====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hex: BytesCoder = /* @__PURE__ */ Object.freeze(\n  chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join(''))\n);\n\n/**\n * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.\n * This variant inherits RFC 4648 base32hex's uppercase table and intentionally does not case-fold decode input.\n * Use `base32hex` for padded version.\n * @example\n * ```js\n * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG'\n * base32hexnopad.decode('2ALG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hexnopad: BytesCoder = /* @__PURE__ */ Object.freeze(\n  chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), join(''))\n);\n/**\n * base32 encoding from RFC 4648. Doug Crockford's version.\n * See {@link https://www.crockford.com/base32.html | Douglas Crockford's Base32}.\n * @example\n * ```js\n * base32crockford.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ANG'\n * base32crockford.decode('2ANG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32crockford: BytesCoder = /* @__PURE__ */ Object.freeze(\n  chain(\n    radix2(5),\n    alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'),\n    join(''),\n    normalize((s: string) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))\n  )\n);\n\n// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64\n// Require both directions before taking the native fast path, so base64/base64url don't mix native and JS behavior.\n// prettier-ignore\nconst hasBase64Builtin: boolean = /* @__PURE__ */ (() =>\n  typeof (Uint8Array as any).from([]).toBase64 === 'function' &&\n  typeof (Uint8Array as any).fromBase64 === 'function')();\n\n// Native `Uint8Array.fromBase64()` accepts these ASCII whitespace chars.\n// Reject them first so the native base64 path still follows RFC 4648 \u00A73.3.\n// ASCII whitespace is U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020 SPACE\nconst ASCII_WHITESPACE = /[\\t\\n\\f\\r ]/;\n\nconst decodeBase64Builtin = (s: string, isUrl: boolean) => {\n  astr('base64', s);\n  const alphabet = isUrl ? 'base64url' : 'base64';\n  // Per spec, .fromBase64 already throws on any other non-alphabet symbols except ASCII whitespace\n  // And checking just for whitespace makes decoding about 3x faster than a full range check.\n  // lastChunkHandling: 'strict' rejects loose tails and non-zero pad bits so native decoding stays canonical.\n  if (s.length > 0 && ASCII_WHITESPACE.test(s)) throw new Error('invalid base64');\n  return (Uint8Array as any).fromBase64(s, { alphabet, lastChunkHandling: 'strict' });\n};\n\n/**\n * base64 from RFC 4648. Padded.\n * Use `base64nopad` for unpadded version.\n * Also check out `base64url`, `base64urlnopad`.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64: BytesCoder = /* @__PURE__ */ Object.freeze(hasBase64Builtin ? {\n  encode(b) { abytes(b); return (b as any).toBase64(); },\n  decode(s) { return decodeBase64Builtin(s, false); },\n} : chain(\n  radix2(6),\n  alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n  padding(6),\n  join('')\n));\n/**\n * base64 from RFC 4648. No padding.\n * Use `base64` for padded version.\n * @example\n * ```js\n * base64nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64nopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64nopad: BytesCoder = /* @__PURE__ */ Object.freeze(\n  chain(\n    radix2(6),\n    alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n    join('')\n  )\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. Padded.\n * Use `base64urlnopad` for unpadded version.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64url.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64url.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64url: BytesCoder = /* @__PURE__ */ Object.freeze(hasBase64Builtin ? {\n  encode(b) { abytes(b); return (b as any).toBase64({ alphabet: 'base64url' }); },\n  decode(s) { return decodeBase64Builtin(s, true); },\n} : chain(\n  radix2(6),\n  alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n  padding(6),\n  join('')\n));\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. No padding.\n * Use `base64url` for padded version.\n * @example\n * ```js\n * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64urlnopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64urlnopad: BytesCoder = /* @__PURE__ */ Object.freeze(\n  chain(\n    radix2(6),\n    alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n    join('')\n  )\n);\n\n// base58 code\n// -----------\nconst genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc: string) =>\n  chain(radix(58), alphabet(abc), join(''));\n\n/**\n * base58: base64 without ambigous characters +, /, 0, O, I, l.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * const text = base58.encode(Uint8Array.from([0, 1, 2]));\n * base58.decode(text);\n * // => Uint8Array.from([0, 1, 2])\n * ```\n */\nexport const base58: BytesCoder = /* @__PURE__ */ Object.freeze(\n  genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz')\n);\n/**\n * base58: flickr version. Check out `base58`.\n * @example\n * Round-trip bytes with the Flickr alphabet.\n * ```ts\n * const text = base58flickr.encode(Uint8Array.from([0, 1, 2]));\n * base58flickr.decode(text);\n * ```\n */\nexport const base58flickr: BytesCoder = /* @__PURE__ */ Object.freeze(\n  genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ')\n);\n/**\n * base58: XRP version. Check out `base58`.\n * @example\n * Round-trip bytes with the XRP alphabet.\n * ```ts\n * const text = base58xrp.encode(Uint8Array.from([0, 1, 2]));\n * base58xrp.decode(text);\n * ```\n */\nexport const base58xrp: BytesCoder = /* @__PURE__ */ Object.freeze(\n  genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz')\n);\n\n// Data len (index) -> encoded block len.\n// Monero pads each 1..8-byte block to this fixed base58 width so decode can recover the tail length.\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\n\n/**\n * base58: XMR version. Check out `base58`.\n * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.\n * Block encoding significantly reduces quadratic complexity of base58.\n * @example\n * Round-trip bytes with the Monero block codec.\n * ```ts\n * const text = base58xmr.encode(Uint8Array.from([0, 1, 2]));\n * base58xmr.decode(text);\n * ```\n */\nexport const base58xmr: BytesCoder = /* @__PURE__ */ Object.freeze({\n  encode(data: TArg<Uint8Array>) {\n    abytes(data);\n    let res = '';\n    for (let i = 0; i < data.length; i += 8) {\n      const block = data.subarray(i, i + 8);\n      res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length]!, '1');\n    }\n    return res;\n  },\n  decode(str: string) {\n    astr('base58xmr.decode', str);\n    let res: number[] = [];\n    for (let i = 0; i < str.length; i += 11) {\n      const slice = str.slice(i, i + 11);\n      const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);\n      const block = base58.decode(slice);\n      for (let j = 0; j < block.length - blockLen; j++) {\n        if (block[j] !== 0) throw new Error('base58xmr: wrong padding');\n      }\n      res = res.concat(Array.from(block.slice(block.length - blockLen)));\n    }\n    return Uint8Array.from(res);\n  },\n});\n\n/**\n * Method, which creates base58check encoder.\n * Requires function, calculating sha256.\n * Callers must include any version bytes in `data`; this helper only applies the\n * 4-byte double-SHA256 checksum used by Bitcoin Base58Check.\n * @param sha256 - Function used to calculate the checksum hash.\n * @returns base58check codec using 4 checksum bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Create a base58check codec from a SHA-256 implementation.\n * ```ts\n * import { createBase58check } from '@scure/base';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const coder = createBase58check(sha256);\n * coder.encode(Uint8Array.from([1, 2, 3]));\n * ```\n */\nexport const createBase58check = (sha256: TArg<BytesFn>): BytesCoder => {\n  // Validate the hash function at construction time so wrong inputs fail before returning a coder.\n  afn(sha256);\n  const _sha256 = sha256 as BytesFn;\n  return chain(\n    checksum(4, (data: TArg<Uint8Array>) => _sha256(_sha256(data))),\n    base58\n  );\n};\n\n/**\n * Use `createBase58check` instead.\n * @deprecated Use {@link createBase58check} instead.\n * Callers must include any version bytes in `data`; this alias keeps the same\n * 4-byte double-SHA256 checksum behavior as `createBase58check`.\n * @param sha256 - Function used to calculate the checksum hash.\n * @returns base58check codec using 4 checksum bytes.\n * @example\n * Create a base58check codec with the deprecated alias.\n * ```ts\n * import { base58check } from '@scure/base';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const coder = base58check(sha256);\n * coder.encode(Uint8Array.from([1, 2, 3]));\n * ```\n */\nexport const base58check: (sha256: TArg<BytesFn>) => BytesCoder = createBase58check;\n\n// Bech32 code\n// -----------\n/** Result of bech32 decoding. */\nexport interface Bech32Decoded<Prefix extends string = string> {\n  /** Human-readable bech32 prefix. */\n  prefix: Prefix;\n  /** Decoded 5-bit word payload. */\n  words: number[];\n}\n/** Result of bech32 decoding with original bytes attached. */\nexport interface Bech32DecodedWithArray<Prefix extends string = string> {\n  /** Human-readable bech32 prefix. */\n  prefix: Prefix;\n  /** Decoded 5-bit word payload. */\n  words: number[];\n  /** Decoded payload converted back into raw bytes. */\n  bytes: Uint8Array;\n}\n\n// BIP 173 character table: data values 0..31 map to `qpzry9x8gf2tvdw0s3jn54khce6mua7l`.\nconst BECH_ALPHABET: Coder<number[], string> = chain(\n  alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'),\n  join('')\n);\n\n// BIP 173 `bech32_polymod` GEN coefficients.\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\n// BIP 173 step split: this applies the polymod state transition before callers xor in the next 5-bit value.\nfunction bech32Polymod(pre: number): number {\n  const b = pre >> 25;\n  let chk = (pre & 0x1ffffff) << 5;\n  for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n    if (((b >> i) & 1) === 1) chk ^= POLYMOD_GENERATORS[i]!;\n  }\n  return chk;\n}\n\nfunction bechChecksum(prefix: string, words: number[], encodingConst = 1): string {\n  const len = prefix.length;\n  let chk = 1;\n  for (let i = 0; i < len; i++) {\n    const c = prefix.charCodeAt(i);\n    if (c < 33 || c > 126) throw new Error(`Invalid prefix (${prefix})`);\n    chk = bech32Polymod(chk) ^ (c >> 5);\n  }\n  chk = bech32Polymod(chk);\n  for (let i = 0; i < len; i++) chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n  for (let v of words) chk = bech32Polymod(chk) ^ v;\n  for (let i = 0; i < 6; i++) chk = bech32Polymod(chk);\n  // BIP 173/BIP 350: xor the final checksum constant, then emit the 30-bit state as six 5-bit symbols.\n  chk ^= encodingConst;\n  return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]!], 30, 5, false));\n}\n\n/** bech32 codec surface. */\nexport interface Bech32 {\n  /**\n   * Encodes a human-readable prefix and 5-bit words into a bech32 string.\n   * @param prefix - Human-readable prefix.\n   * @param words - 5-bit words or raw bytes.\n   * @param limit - Maximum accepted output length, or `false` to disable the limit.\n   * @returns Encoded bech32 string.\n   */\n  encode<Prefix extends string>(\n    prefix: Prefix,\n    words: number[] | Uint8Array,\n    limit?: number | false\n  ): `${Lowercase<Prefix>}1${string}`;\n  /**\n   * Decodes a bech32 string into prefix and words.\n   * @param str - Encoded bech32 string.\n   * @param limit - Maximum accepted input length, or `false` to disable the limit.\n   * @returns Decoded prefix and 5-bit words.\n   */\n  decode<Prefix extends string>(\n    str: `${Prefix}1${string}`,\n    limit?: number | false\n  ): Bech32Decoded<Prefix>;\n  decode(str: string, limit?: number | false): Bech32Decoded;\n  /**\n   * Encodes raw bytes by first converting them to 5-bit words.\n   * @param prefix - Human-readable prefix.\n   * @param bytes - Raw bytes to encode.\n   * @returns Encoded bech32 string.\n   */\n  encodeFromBytes(prefix: string, bytes: Uint8Array): string;\n  /**\n   * Decodes a bech32 string and converts the payload back into bytes.\n   * @param str - Encoded bech32 string.\n   * @returns Decoded prefix, words, and bytes.\n   */\n  decodeToBytes(str: string): Bech32DecodedWithArray;\n  /**\n   * Decodes a bech32 string, returning `undefined` instead of throwing on invalid input.\n   * @param str - Encoded bech32 string.\n   * @param limit - Maximum accepted input length, or `false` to disable the limit.\n   * @returns Decoded prefix and words, or `undefined` for invalid input.\n   */\n  decodeUnsafe(str: string, limit?: number | false): void | Bech32Decoded<string>;\n  /**\n   * Converts 5-bit words back into raw bytes.\n   * @param to - 5-bit words to decode.\n   * @returns Decoded bytes.\n   */\n  fromWords(to: number[]): Uint8Array;\n  /**\n   * Converts 5-bit words back into raw bytes, returning `undefined` instead of throwing.\n   * @param to - 5-bit words to decode.\n   * @returns Decoded bytes, or `undefined` for invalid input.\n   */\n  fromWordsUnsafe(to: number[]): void | Uint8Array;\n  /**\n   * Converts raw bytes into 5-bit words for bech32 encoding.\n   * @param from - Raw bytes to convert.\n   * @returns 5-bit words.\n   */\n  toWords(from: Uint8Array): number[];\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction genBech32(encoding: 'bech32' | 'bech32m'): TRet<Bech32> {\n  // BIP 173 uses final xor constant 1; BIP 350 swaps in 0x2bc830a3 for Bech32m.\n  const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n  const _words = radix2(5);\n  const fromWords = _words.decode;\n  const toWords = _words.encode;\n  const fromWordsUnsafe = unsafeWrapper(fromWords);\n\n  function encode<Prefix extends string>(\n    prefix: Prefix,\n    words: TArg<number[] | Uint8Array>,\n    limit: number | false = 90\n  ): `${Lowercase<Prefix>}1${string}` {\n    astr('bech32.encode prefix', prefix);\n    if (isBytes(words)) words = Array.from(words);\n    anumArr('bech32.encode', words);\n    const plen = prefix.length;\n    if (plen === 0) throw new TypeError(`Invalid prefix length ${plen}`);\n    // Total output is hrp + `1` separator + payload words + 6 checksum chars.\n    const actualLength = plen + 7 + words.length;\n    if (limit !== false && actualLength > limit)\n      throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n    const lowered = prefix.toLowerCase();\n    const sum = bechChecksum(lowered, words, ENCODING_CONST);\n    return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}` as `${Lowercase<Prefix>}1${string}`;\n  }\n\n  function decode<Prefix extends string>(\n    str: `${Prefix}1${string}`,\n    limit?: number | false\n  ): Bech32Decoded<Prefix>;\n  function decode(str: string, limit?: number | false): Bech32Decoded;\n  function decode(str: string, limit: number | false = 90): Bech32Decoded {\n    astr('bech32.decode input', str);\n    const slen = str.length;\n    // Minimum length is 1-char hrp + `1` separator + 6-char checksum.\n    if (slen < 8 || (limit !== false && slen > limit))\n      throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);\n    // don't allow mixed case\n    const lowered = str.toLowerCase();\n    if (str !== lowered && str !== str.toUpperCase())\n      throw new Error(`String must be lowercase or uppercase`);\n    const sepIndex = lowered.lastIndexOf('1');\n    if (sepIndex === 0 || sepIndex === -1)\n      throw new Error(`Letter \"1\" must be present between prefix and data only`);\n    const prefix = lowered.slice(0, sepIndex);\n    const data = lowered.slice(sepIndex + 1);\n    if (data.length < 6) throw new Error('Data must be at least 6 characters long');\n    const words = BECH_ALPHABET.decode(data).slice(0, -6);\n    const sum = bechChecksum(prefix, words, ENCODING_CONST);\n    if (!data.endsWith(sum)) throw new Error(`Invalid checksum in ${str}: expected \"${sum}\"`);\n    return { prefix, words };\n  }\n\n  const decodeUnsafe = unsafeWrapper(decode);\n\n  function decodeToBytes(str: string): TRet<Bech32DecodedWithArray> {\n    // Keep the byte helper unbounded; callers that need the default BIP 173 length cap should use decode(str).\n    const { prefix, words } = decode(str, false);\n    return {\n      prefix,\n      words,\n      bytes: fromWords(words) as TRet<Uint8Array>,\n    } as TRet<Bech32DecodedWithArray>;\n  }\n\n  function encodeFromBytes(prefix: string, bytes: TArg<Uint8Array>) {\n    // Keep the convenience wrapper on encode()'s default 90-char cap; custom limits should call encode(prefix, toWords(bytes), limit).\n    return encode(prefix, toWords(bytes));\n  }\n\n  return {\n    encode,\n    decode,\n    encodeFromBytes,\n    decodeToBytes,\n    decodeUnsafe,\n    fromWords,\n    fromWordsUnsafe,\n    toWords,\n  };\n}\n\n/**\n * bech32 from BIP 173. Operates on words.\n * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}.\n * @example\n * Convert bytes to words, encode them, then decode back.\n * ```ts\n * const words = bech32.toWords(Uint8Array.from([1, 2, 3]));\n * const text = bech32.encode('bc', words);\n * bech32.decode(text);\n * ```\n */\nexport const bech32: TRet<Bech32> = /* @__PURE__ */ Object.freeze(genBech32('bech32'));\n\n/**\n * bech32m from BIP 350. Operates on words.\n * It was to mitigate `bech32` weaknesses.\n * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}.\n * @example\n * Convert bytes to words, encode them with bech32m, then decode back.\n * ```ts\n * const words = bech32m.toWords(Uint8Array.from([1, 2, 3]));\n * const text = bech32m.encode('bc', words);\n * bech32m.decode(text);\n * ```\n */\nexport const bech32m: TRet<Bech32> = /* @__PURE__ */ Object.freeze(genBech32('bech32m'));\n\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * ASCII-to-byte decoder. Rejects non-ASCII text and bytes instead of doing UTF-8 replacement.\n * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and `decode(string)` returns bytes.\n * @example\n * ```js\n * const b = ascii.decode(\"ABC\"); // => new Uint8Array([ 65, 66, 67 ])\n * const str = ascii.encode(b); // \"ABC\"\n * ```\n */\nexport const ascii: TRet<BytesCoder> = /* @__PURE__ */ Object.freeze({\n  encode(data: TArg<Uint8Array>) {\n    abytes(data);\n    let res = '';\n    for (let i = 0; i < data.length; i++) {\n      const byte = data[i]!;\n      // ASCII is 7-bit; reject bytes outside 0x00..0x7f instead of silently widening to\n      // Latin-1/UTF-8.\n      if (byte > 127) throw new RangeError(`bytes contain non-ASCII byte ${byte} at position ${i}`);\n      res += String.fromCharCode(byte);\n    }\n    return res;\n  },\n  decode(str: string) {\n    if (typeof str !== 'string') throw new TypeError('ascii string expected, got ' + typeof str);\n    const res = new Uint8Array(str.length);\n    for (let i = 0; i < str.length; i++) {\n      // Indexed access is much faster than Uint8Array.from(str, mapFn) here and keeps\n      // exact error positions.\n      const charCode = str.charCodeAt(i);\n      if (charCode > 127) {\n        throw new RangeError(\n          `string contains non-ASCII character \"${str[i]}\" with code ${charCode} at position ${i}`\n        );\n      }\n      res[i] = charCode;\n    }\n    return res;\n  },\n});\n\nconst _isWellFormedShim = (str: string): boolean => {\n  // encodeURI rejects malformed UTF-16, giving a compact fallback that matches native\n  // isWellFormed on our tests/fuzz corpus.\n  try {\n    return encodeURI(str) !== null;\n  } catch {\n    return false;\n  }\n};\nconst _isWellFormed: (str: string) => boolean = /* @__PURE__ */ (() =>\n  // Pick the native check once so utf8.decode doesn't re-probe String.prototype on every call.\n  typeof ('' as any).isWellFormed === 'function'\n    ? (str) => (str as any).isWellFormed()\n    : _isWellFormedShim)();\n// This fallback stays small because strict UTF-8 only needs fatal decoding plus well-formed\n// UTF-16 checks, not the replacement, streaming, or legacy-encoding behavior of full platform\n// text codecs.\nconst utf8Fallback: BytesCoder = /* @__PURE__ */ Object.freeze({\n  encode(data: TArg<Uint8Array>) {\n    abytes(data);\n    let res = '';\n    for (let i = 0; i < data.length; ) {\n      const a = data[i++]!;\n      if (a < 0b1000_0000) {\n        res += String.fromCharCode(a);\n        continue;\n      }\n      if (a < 0b1100_0010 || i >= data.length) throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n      const b = data[i++]!;\n      if ((b & 0b1100_0000) !== 0b1000_0000) throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n      let cp = ((a & 0b0001_1111) << 6) | (b & 0b0011_1111);\n      if (a >= 0b1110_0000) {\n        if (i >= data.length) throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n        const c = data[i++]!;\n        if (\n          (c & 0b1100_0000) !== 0b1000_0000 ||\n          (a === 0b1110_0000 && b < 0b1010_0000) ||\n          (a === 0xed && b >= 0b1010_0000)\n        )\n          throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n        cp = ((a & 0b0000_1111) << 12) | ((b & 0b0011_1111) << 6) | (c & 0b0011_1111);\n        if (a >= 0b1111_0000) {\n          if (i >= data.length) throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n          const d = data[i++]!;\n          if (\n            a > 0b1111_0100 ||\n            (d & 0b1100_0000) !== 0b1000_0000 ||\n            (a === 0b1111_0000 && b < 0b1001_0000) ||\n            (a === 0b1111_0100 && b >= 0b1001_0000)\n          )\n            throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n          cp =\n            ((a & 7) << 18) |\n            ((b & 0b0011_1111) << 12) |\n            ((c & 0b0011_1111) << 6) |\n            (d & 0b0011_1111);\n        }\n      }\n      if (cp < 0x10000) res += String.fromCharCode(cp);\n      else {\n        cp -= 0x10000;\n        res += String.fromCharCode((cp >> 10) + 0xd800, (cp & 0x3ff) + 0xdc00);\n      }\n    }\n    return res;\n  },\n  decode(str: string) {\n    astr('utf8', str);\n    if (!_isWellFormed(str)) throw new TypeError('utf8 expected well-formed string');\n    // Direct Uint8Array writes are much faster than number[] + Uint8Array.from on Hermes and\n    // large Node inputs.\n    const res = new Uint8Array(str.length * 3);\n    let pos = 0;\n    for (let i = 0; i < str.length; i++) {\n      let c = str.charCodeAt(i);\n      if (c < 0b1000_0000) {\n        res[pos++] = c;\n        continue;\n      }\n      if (c >= 0xd800 && c <= 0xdfff) {\n        const d = str.charCodeAt(++i);\n        c = 0x10000 + ((c - 0xd800) << 10) + d - 0xdc00;\n      }\n      if (c >= 0x10000) {\n        res[pos++] = (c >> 18) | 0b1111_0000;\n        res[pos++] = ((c >> 12) & 0b0011_1111) | 0b1000_0000;\n      } else if (c >= 0x800) res[pos++] = (c >> 12) | 0b1110_0000;\n      else res[pos++] = (c >> 6) | 0b1100_0000;\n      if (c >= 0x800) res[pos++] = ((c >> 6) & 0b0011_1111) | 0b1000_0000;\n      res[pos++] = (c & 0b0011_1111) | 0b1000_0000;\n    }\n    return res.subarray(0, pos);\n  },\n});\n\n/**\n * Strict UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder when available.\n * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and\n * `decode(string)` returns bytes.\n * `encode(bytes)` requires Uint8Array input, preserves an explicit leading BOM, and\n *   throws on invalid UTF-8 bytes.\n * `decode(string)` requires a primitive string and throws on malformed UTF-16 strings with\n *   lone surrogates.\n * @example\n * ```js\n * const b = utf8.decode(\"hey\"); // => new Uint8Array([ 104, 101, 121 ])\n * const str = utf8.encode(b); // \"hey\"\n * ```\n */\nexport const utf8: BytesCoder = /* @__PURE__ */ (() => {\n  let _utf8Encoder: any;\n  let _utf8Decoder: any;\n  const utf8Builtin: BytesCoder = {\n    // ignoreBOM preserves an explicit leading U+FEFF;\n    // fatal rejects invalid UTF-8 bytes instead of replacing them.\n    encode(data) {\n      abytes(data);\n      return (\n        _utf8Decoder || (_utf8Decoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }))\n      ).decode(data);\n    },\n    decode(str) {\n      astr('utf8', str);\n      if (!_isWellFormed(str)) throw new TypeError('utf8 expected well-formed string');\n      return (_utf8Encoder || (_utf8Encoder = new TextEncoder())).encode(str);\n    },\n  };\n  return Object.freeze({\n    // Select each direction once at module init, since\n    // TextEncoder and TextDecoder can exist independently.\n    encode: typeof TextDecoder === 'function' ? utf8Builtin.encode : utf8Fallback.encode,\n    decode: typeof TextEncoder === 'function' ? utf8Builtin.decode : utf8Fallback.decode,\n  });\n})();\n// Keep fallback parity probes behind a test-only export until runtime fallback behavior is decided.\nexport const __TESTS: {\n  utf8Fallback: BytesCoder;\n  _isWellFormedShim: (str: string) => boolean;\n} = /* @__PURE__ */ Object.freeze({\n  utf8Fallback: utf8Fallback,\n  _isWellFormedShim: _isWellFormedShim,\n});\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\n// prettier-ignore\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n  // Require both directions before enabling the native hex path so encode/decode stay symmetric.\n  typeof (Uint8Array as any).from([]).toHex === 'function' &&\n  typeof (Uint8Array as any).fromHex === 'function')();\n// prettier-ignore\nconst hexBuiltin: BytesCoder = {\n  // Keep local type guards so the native path preserves library-level input errors.\n  // Native toHex emits lowercase hex, matching the fallback alphabet and Node's hex strings.\n  encode(data) { abytes(data); return (data as any).toHex(); },\n  // Native fromHex accepts either hex case and rejects odd-length / non-hex syntax.\n  decode(s) { astr('hex', s); return (Uint8Array as any).fromHex(s); },\n};\n/**\n * hex string decoder. Uses built-in function, when available.\n * Lowercase codec; unlike `base16`, this variant accepts either hex case and emits lowercase.\n * @example\n * ```js\n * const b = hex.decode(\"0102ff\"); // => new Uint8Array([ 1, 2, 255 ])\n * const str = hex.encode(b); // \"0102ff\"\n * ```\n */\nexport const hex: BytesCoder = /* @__PURE__ */ Object.freeze(\n  hasHexBuiltin\n    ? hexBuiltin\n    : chain(\n        radix2(4),\n        alphabet('0123456789abcdef'),\n        join(''),\n        normalize((s: string) => {\n          if (typeof s !== 'string' || s.length % 2 !== 0)\n            throw new TypeError(\n              `hex.decode: expected string, got ${typeof s} with length ${s.length}`\n            );\n          return s.toLowerCase();\n        })\n      )\n);\n\n/** Built-in codecs exposed through the deprecated string conversion helpers. */\nexport type SomeCoders = {\n  /** UTF-8 string codec. */\n  utf8: BytesCoder;\n  /** Hex codec. */\n  hex: BytesCoder;\n  /** Uppercase RFC 4648 base16 codec. */\n  base16: BytesCoder;\n  /** RFC 4648 base32 codec with padding. */\n  base32: BytesCoder;\n  /** RFC 4648 base64 codec with padding. */\n  base64: BytesCoder;\n  /** URL-safe base64 codec without `+` or `/`. */\n  base64url: BytesCoder;\n  /** Bitcoin-style base58 codec. */\n  base58: BytesCoder;\n  /** Monero-style base58 codec. */\n  base58xmr: BytesCoder;\n};\n// prettier-ignore\n// Keep this registry aligned with CoderType/coderTypeError; only byte<->string codecs belong here.\nconst CODERS: SomeCoders = {\n  utf8, hex, base16, base32, base64, base64url, base58, base58xmr\n};\ntype CoderType = keyof SomeCoders;\nconst coderTypeError =\n  'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';\n\n/**\n * Encodes bytes with one of the built-in codecs.\n * @deprecated Use the codec directly, for example `hex.encode(bytes)`.\n * @param type - Codec name.\n * @param bytes - Bytes to encode.\n * @returns Encoded string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * ```ts\n * bytesToString('hex', Uint8Array.from([1, 2, 255]));\n * ```\n */\nexport const bytesToString = (type: CoderType, bytes: TArg<Uint8Array>): string => {\n  if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n  if (!isBytes(bytes)) throw new TypeError('bytesToString() expects Uint8Array');\n  return CODERS[type].encode(bytes);\n};\n\n/**\n * Alias for `bytesToString`.\n * @deprecated Use {@link bytesToString} or the codec directly instead.\n * @param type - Codec name.\n * @param bytes - Bytes to encode.\n * @returns Encoded string.\n * @example\n * ```ts\n * str('hex', Uint8Array.from([1, 2, 255]));\n * ```\n */\nexport const str: (type: CoderType, bytes: TArg<Uint8Array>) => string = bytesToString; // as in python, but for bytes only\n\n/**\n * Decodes a string with one of the built-in codecs.\n * @deprecated Use the codec directly, for example `hex.decode(text)`.\n * @param type - Codec name.\n * @param str - Encoded string.\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * ```ts\n * stringToBytes('hex', '0102ff');\n * ```\n */\nexport const stringToBytes = (type: CoderType, str: string): TRet<Uint8Array> => {\n  // Match bytesToString's selector validation so hostile `toString()` coercions can't leak custom errors.\n  if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n  if (typeof str !== 'string') throw new TypeError('stringToBytes() expects string');\n  return CODERS[type].decode(str) as TRet<Uint8Array>;\n};\n/**\n * Alias for `stringToBytes`.\n * @deprecated Use {@link stringToBytes} or the codec directly instead.\n * @param type - Codec name.\n * @param str - Encoded string.\n * @returns Decoded bytes.\n * @example\n * ```ts\n * bytes('hex', '0102ff');\n * ```\n */\nexport const bytes: (type: CoderType, str: string) => TRet<Uint8Array> = stringToBytes;\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg<T> = T extends BigInt64Array\n  ? BigInt64Array\n  : T extends BigUint64Array\n    ? BigUint64Array\n    : T extends Float32Array\n      ? Float32Array\n      : T extends Float64Array\n        ? Float64Array\n        : T extends Int16Array\n          ? Int16Array\n          : T extends Int32Array\n            ? Int32Array\n            : T extends Int8Array\n              ? Int8Array\n              : T extends Uint16Array\n                ? Uint16Array\n                : T extends Uint32Array\n                  ? Uint32Array\n                  : T extends Uint8ClampedArray\n                    ? Uint8ClampedArray\n                    : T extends Uint8Array\n                      ? Uint8Array\n                      : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet<T> = T extends BigInt64Array\n  ? ReturnType<typeof BigInt64Array.of>\n  : T extends BigUint64Array\n    ? ReturnType<typeof BigUint64Array.of>\n    : T extends Float32Array\n      ? ReturnType<typeof Float32Array.of>\n      : T extends Float64Array\n        ? ReturnType<typeof Float64Array.of>\n        : T extends Int16Array\n          ? ReturnType<typeof Int16Array.of>\n          : T extends Int32Array\n            ? ReturnType<typeof Int32Array.of>\n            : T extends Int8Array\n              ? ReturnType<typeof Int8Array.of>\n              : T extends Uint16Array\n                ? ReturnType<typeof Uint16Array.of>\n                : T extends Uint32Array\n                  ? ReturnType<typeof Uint32Array.of>\n                  : T extends Uint8ClampedArray\n                    ? ReturnType<typeof Uint8ClampedArray.of>\n                    : T extends Uint8Array\n                      ? ReturnType<typeof Uint8Array.of>\n                      : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg<T> =\n  | T\n  | ([TypedArg<T>] extends [never]\n      ? T extends (...args: infer A) => infer R\n        ? ((...args: { [K in keyof A]: TRet<A[K]> }) => TArg<R>) & {\n            [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;\n          }\n        : T extends [infer A, ...infer R]\n          ? [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n          : T extends readonly [infer A, ...infer R]\n            ? readonly [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n            : T extends (infer A)[]\n              ? TArg<A>[]\n              : T extends readonly (infer A)[]\n                ? readonly TArg<A>[]\n                : T extends Promise<infer A>\n                  ? Promise<TArg<A>>\n                  : T extends object\n                    ? { [K in keyof T]: TArg<T[K]> }\n                    : T\n      : TypedArg<T>);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet<T> = T extends unknown\n  ? T &\n      ([TypedRet<T>] extends [never]\n        ? T extends (...args: infer A) => infer R\n          ? ((...args: { [K in keyof A]: TArg<A[K]> }) => TRet<R>) & {\n              [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;\n            }\n          : T extends [infer A, ...infer R]\n            ? [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n            : T extends readonly [infer A, ...infer R]\n              ? readonly [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n              : T extends (infer A)[]\n                ? TRet<A>[]\n                : T extends readonly (infer A)[]\n                  ? readonly TRet<A>[]\n                  : T extends Promise<infer A>\n                    ? Promise<TRet<A>>\n                    : T extends object\n                      ? { [K in keyof T]: TRet<T[K]> }\n                      : T\n        : TypedRet<T>)\n  : never;\n/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a: unknown): a is Uint8Array {\n  // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n  // The fallback still requires a real ArrayBuffer view, so plain\n  // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n  // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n  return (\n    a instanceof Uint8Array ||\n    (ArrayBuffer.isView(a) &&\n      a.constructor.name === 'Uint8Array' &&\n      'BYTES_PER_ELEMENT' in a &&\n      a.BYTES_PER_ELEMENT === 1)\n  );\n}\n\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n: number, title: string = ''): void {\n  if (typeof n !== 'number') {\n    const prefix = title && `\"${title}\" `;\n    throw new TypeError(`${prefix}expected number, got ${typeof n}`);\n  }\n  if (!Number.isSafeInteger(n) || n < 0) {\n    const prefix = title && `\"${title}\" `;\n    throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);\n  }\n}\n\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(\n  value: TArg<Uint8Array>,\n  length?: number,\n  title: string = ''\n): TRet<Uint8Array> {\n  const bytes = isBytes(value);\n  const len = value?.length;\n  const needsLen = length !== undefined;\n  if (!bytes || (needsLen && len !== length)) {\n    const prefix = title && `\"${title}\" `;\n    const ofLen = needsLen ? ` of length ${length}` : '';\n    const got = bytes ? `length=${len}` : `type=${typeof value}`;\n    const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;\n    if (!bytes) throw new TypeError(message);\n    throw new RangeError(message);\n  }\n  return value as TRet<Uint8Array>;\n}\n\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array> {\n  // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n  // because callers use it at byte-validation boundaries before mutating the detached copy.\n  return Uint8Array.from(abytes(bytes)) as TRet<Uint8Array>;\n}\n\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h: TArg<CHash>): void {\n  if (typeof h !== 'function' || typeof h.create !== 'function')\n    throw new TypeError('Hash must wrapped by utils.createHasher');\n  anumber(h.outputLen);\n  anumber(h.blockLen);\n  // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n  // validation and can produce empty outputs instead of failing fast.\n  if (h.outputLen < 1) throw new Error('\"outputLen\" must be >= 1');\n  if (h.blockLen < 1) throw new Error('\"blockLen\" must be >= 1');\n}\n\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance: any, checkFinished = true): void {\n  if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n  if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out: any, instance: any): void {\n  abytes(out, undefined, 'digestInto() output');\n  const min = instance.outputLen;\n  if (out.length < min) {\n    throw new RangeError('\"digestInto() output\" expected to be of length >=' + min);\n  }\n}\n\n/** Generic type encompassing 8/16/32-byte array views, but not 64-bit variants. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n  Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr: TArg<TypedArray>): TRet<Uint8Array> {\n  return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength) as TRet<Uint8Array>;\n}\n\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr: TArg<TypedArray>): TRet<Uint32Array> {\n  return new Uint32Array(\n    arr.buffer,\n    arr.byteOffset,\n    Math.floor(arr.byteLength / 4)\n  ) as TRet<Uint32Array>;\n}\n\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays: TArg<TypedArray[]>): void {\n  for (let i = 0; i < arrays.length; i++) {\n    arrays[i].fill(0);\n  }\n}\n\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr: TArg<TypedArray>): DataView {\n  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word: number, shift: number): number {\n  return (word << (32 - shift)) | (word >>> shift);\n}\n\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word: number, shift: number): number {\n  return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Whether the current platform is little-endian. */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n  new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word: number): number {\n  return (\n    ((word << 24) & 0xff000000) |\n    ((word << 8) & 0xff0000) |\n    ((word >>> 8) & 0xff00) |\n    ((word >>> 24) & 0xff)\n  );\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE: (n: number) => number = isLE\n  ? (n: number) => n\n  : (n: number) => byteSwap(n) >>> 0;\n\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr: TArg<Uint32Array>): TRet<Uint32Array> {\n  for (let i = 0; i < arr.length; i++) {\n    arr[i] = byteSwap(arr[i]);\n  }\n  return arr as TRet<Uint32Array>;\n}\n\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n *   On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE: (u: TArg<Uint32Array>) => TRet<Uint32Array> = isLE\n  ? (u: TArg<Uint32Array>) => u as TRet<Uint32Array>\n  : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n  // @ts-ignore\n  typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n  i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes: TArg<Uint8Array>): string {\n  abytes(bytes);\n  // @ts-ignore\n  if (hasHexBuiltin) return bytes.toHex();\n  // pre-caching improves the speed 6x\n  let hex = '';\n  for (let i = 0; i < bytes.length; i++) {\n    hex += hexes[bytes[i]];\n  }\n  return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n  if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n  if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n  if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n  return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex: string): TRet<Uint8Array> {\n  if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n  if (hasHexBuiltin) {\n    try {\n      return (Uint8Array as any).fromHex(hex);\n    } catch (error) {\n      if (error instanceof SyntaxError) throw new RangeError(error.message);\n      throw error;\n    }\n  }\n  const hl = hex.length;\n  const al = hl / 2;\n  if (hl % 2) throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n  const array = new Uint8Array(al);\n  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n    const n1 = asciiToBase16(hex.charCodeAt(hi));\n    const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n    if (n1 === undefined || n2 === undefined) {\n      const char = hex[hi] + hex[hi + 1];\n      throw new RangeError(\n        'hex string expected, got non-hex character \"' + char + '\" at index ' + hi\n      );\n    }\n    array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n  }\n  return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * This yields to the Promise/microtask scheduler queue, not to timers or the\n * full macrotask event loop.\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/**\n * Returns control to the Promise/microtask scheduler every `tick`\n * milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(\n  iters: number,\n  tick: number,\n  cb: (i: number) => void\n): Promise<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, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str: string): TRet<Uint8Array> {\n  if (typeof str !== 'string') throw new TypeError('string expected');\n  return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data: TArg<KDFInput>, errorTitle = ''): TRet<Uint8Array> {\n  if (typeof data === 'string') return utf8ToBytes(data);\n  return abytes(data, undefined, errorTitle);\n}\n\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays: TArg<Uint8Array[]>): TRet<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 = {};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @returns Merged option object. The merge mutates `defaults` in place.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n  defaults: T1,\n  opts?: T2\n): T1 & T2 {\n  if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n    throw new TypeError('options must be object or undefined');\n  const merged = Object.assign(defaults, opts);\n  return merged as T1 & T2;\n}\n\n/** Common interface for all hash instances. */\nexport interface Hash<T> {\n  /** Bytes processed per compression block. */\n  blockLen: number;\n  /** Bytes produced by `digest()`. */\n  outputLen: number;\n  /** Whether the instance supports XOF-style variable-length output via `xof()` / `xofInto()`. */\n  canXOF: boolean;\n  /**\n   * Absorbs more message bytes into the running hash state.\n   * @param buf - message chunk to absorb\n   * @returns The same hash instance for chaining.\n   */\n  update(buf: TArg<Uint8Array>): this;\n  /**\n   * Finalizes the hash into a caller-provided buffer.\n   * @param buf - destination buffer\n   * @returns Nothing. Implementations write into `buf` in place.\n   */\n  digestInto(buf: TArg<Uint8Array>): void;\n  /**\n   * Finalizes the hash and returns a freshly allocated digest.\n   * @returns Digest bytes.\n   */\n  digest(): TRet<Uint8Array>;\n  /** Wipes internal state and makes the instance unusable. */\n  destroy(): void;\n  /**\n   * Copies the current hash state into an existing or new instance.\n   * @param to - Optional destination instance to reuse.\n   * @returns Cloned hash state.\n   */\n  _cloneInto(to?: T): T;\n  /**\n   * Creates an independent copy of the current hash state.\n   * @returns Cloned hash instance.\n   */\n  clone(): T;\n}\n\n/** Pseudorandom generator interface. */\nexport interface PRG {\n  /**\n   * Mixes more entropy into the generator state.\n   * @param seed - fresh entropy bytes\n   * @returns Nothing. Implementations update internal state in place.\n   */\n  addEntropy(seed: TArg<Uint8Array>): void;\n  /**\n   * Generates pseudorandom output bytes.\n   * @param length - number of bytes to generate\n   * @returns Generated pseudorandom bytes.\n   */\n  randomBytes(length: number): TRet<Uint8Array>;\n  /** Wipes generator state and makes the instance unusable. */\n  clean(): void;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n  /**\n   * Reads more bytes from the XOF stream.\n   * @param bytes - number of bytes to read\n   * @returns Requested digest bytes.\n   */\n  xof(bytes: number): TRet<Uint8Array>;\n  /**\n   * Reads more bytes from the XOF stream into a caller-provided buffer.\n   * @param buf - destination buffer\n   * @returns Filled output buffer.\n   */\n  xofInto(buf: TArg<Uint8Array>): TRet<Uint8Array>;\n};\n\n/** Hash constructor or factory type. */\nexport type HasherCons<T, Opts = undefined> = Opts extends undefined ? () => T : (opts?: Opts) => T;\n/** Optional hash metadata. */\nexport type HashInfo = {\n  /** DER-encoded object identifier bytes for the hash algorithm. */\n  oid?: TRet<Uint8Array>;\n};\n/** Callable hash function type. */\nexport type CHash<T extends Hash<T> = Hash<any>, Opts = undefined> = {\n  /** Digest size in bytes. */\n  outputLen: number;\n  /** Input block size in bytes. */\n  blockLen: number;\n  /** Whether `.create()` returns a hash instance that can be used as an XOF stream. */\n  canXOF: boolean;\n} & HashInfo &\n  (Opts extends undefined\n    ? {\n        (msg: TArg<Uint8Array>): TRet<Uint8Array>;\n        create(): T;\n      }\n    : {\n        (msg: TArg<Uint8Array>, opts?: TArg<Opts>): TRet<Uint8Array>;\n        create(opts?: Opts): T;\n      });\n/** Callable extendable-output hash function type. */\nexport type CHashXOF<T extends HashXOF<T> = HashXOF<any>, Opts = undefined> = CHash<T, Opts>;\n\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n *   Wrapper construction eagerly calls `hashCons(undefined)` once to read\n *   `outputLen` / `blockLen`, so constructor side effects happen at module\n *   init time.\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher<T extends Hash<T>, Opts = undefined>(\n  hashCons: HasherCons<T, Opts>,\n  info: TArg<HashInfo> = {}\n): TRet<CHash<T, Opts>> {\n  const hashC: any = (msg: TArg<Uint8Array>, opts?: TArg<Opts>) =>\n    hashCons(opts as Opts)\n      .update(msg)\n      .digest();\n  const tmp = hashCons(undefined);\n  hashC.outputLen = tmp.outputLen;\n  hashC.blockLen = tmp.blockLen;\n  hashC.canXOF = tmp.canXOF;\n  hashC.create = (opts?: Opts) => hashCons(opts);\n  Object.assign(hashC, info);\n  return Object.freeze(hashC) as TRet<CHash<T, Opts>>;\n}\n\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32): TRet<Uint8Array> {\n  // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n  anumber(bytesLength, 'bytesLength');\n  const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n  if (typeof cr?.getRandomValues !== 'function')\n    throw new Error('crypto.getRandomValues must be defined');\n  // Web Cryptography API Level 2 \u00A710.1.1:\n  // if `byteLength > 65536`, throw `QuotaExceededError`.\n  // Keep the guard explicit so callers can see the quota in code\n  // instead of discovering it by reading the spec or host errors.\n  // This wrapper surfaces the same quota as a stable library RangeError.\n  if (bytesLength > 65536)\n    throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n  return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n *   The helper accepts any byte even though only the documented NIST hash\n *   suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix: number): TRet<Required<HashInfo>> => ({\n  // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n  // Larger suffix values would need base-128 OID encoding and a different length byte.\n  oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport {\n  abytes,\n  aexists,\n  aoutput,\n  clean,\n  createView,\n  type Hash,\n  type TArg,\n  type TRet,\n} from './utils.ts';\n\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a: number, b: number, c: number): number {\n  return (a & b) ^ (~a & c);\n}\n\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a: number, b: number, c: number): number {\n  return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport abstract class HashMD<T extends HashMD<T>> implements Hash<T> {\n  // Subclasses must treat `buf` as read-only: `update()` may pass a direct view over caller input\n  // when it can process whole blocks without buffering first.\n  protected abstract process(buf: DataView, offset: number): void;\n  protected abstract get(): number[];\n  protected abstract set(...args: number[]): void;\n  abstract destroy(): void;\n  protected abstract roundClean(): void;\n\n  readonly blockLen: number;\n  readonly outputLen: number;\n  readonly canXOF = false;\n  readonly padOffset: number;\n  readonly isLE: boolean;\n\n  // For partial updates less than block size\n  protected buffer: Uint8Array;\n  protected view: DataView;\n  protected finished = false;\n  protected length = 0;\n  protected pos = 0;\n  protected destroyed = false;\n\n  constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n    this.blockLen = blockLen;\n    this.outputLen = outputLen;\n    this.padOffset = padOffset;\n    this.isLE = isLE;\n    this.buffer = new Uint8Array(blockLen);\n    this.view = createView(this.buffer);\n  }\n  update(data: TArg<Uint8Array>): this {\n    aexists(this);\n    abytes(data);\n    const { view, buffer, blockLen } = this;\n    const len = data.length;\n    for (let pos = 0; pos < len; ) {\n      const take = Math.min(blockLen - this.pos, len - pos);\n      // Fast path only when there is no buffered partial block: `take === blockLen` implies\n      // `this.pos === 0`, so we can process full blocks directly from the input view.\n      if (take === blockLen) {\n        const dataView = createView(data);\n        for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n        continue;\n      }\n      buffer.set(data.subarray(pos, pos + take), this.pos);\n      this.pos += take;\n      pos += take;\n      if (this.pos === blockLen) {\n        this.process(view, 0);\n        this.pos = 0;\n      }\n    }\n    this.length += data.length;\n    this.roundClean();\n    return this;\n  }\n  digestInto(out: TArg<Uint8Array>): void {\n    aexists(this);\n    aoutput(out, this);\n    this.finished = true;\n    // Padding\n    // We can avoid allocation of buffer for padding completely if it\n    // was previously not allocated here. But it won't change performance.\n    const { buffer, view, blockLen, isLE } = this;\n    let { pos } = this;\n    // append the bit '1' to the message\n    buffer[pos++] = 0b10000000;\n    clean(this.buffer.subarray(pos));\n    // we have less than padOffset left in buffer, so we cannot put length in\n    // current block, need process it and pad again\n    if (this.padOffset > blockLen - pos) {\n      this.process(view, 0);\n      pos = 0;\n    }\n    // Pad until full block byte with zeros\n    for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n    // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n    // the padding fill above, and JS will overflow before user input can make that half non-zero.\n    // So we only need to write the low 64 bits here.\n    view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);\n    this.process(view, 0);\n    const oview = createView(out);\n    const len = this.outputLen;\n    // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n    if (len % 4) throw new Error('_sha2: outputLen must be aligned to 32bit');\n    const outLen = len / 4;\n    const state = this.get();\n    if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n    for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n  }\n  digest(): TRet<Uint8Array> {\n    const { buffer, outputLen } = this;\n    this.digestInto(buffer);\n    // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n    // fresh bytes to the caller.\n    const res = buffer.slice(0, outputLen);\n    this.destroy();\n    return res as TRet<Uint8Array>;\n  }\n  _cloneInto(to?: T): T {\n    to ||= new (this.constructor as any)() as T;\n    to.set(...this.get());\n    const { blockLen, buffer, length, finished, destroyed, pos } = this;\n    to.destroyed = destroyed;\n    to.finished = finished;\n    to.length = length;\n    to.pos = pos;\n    // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n    // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n    if (length % blockLen) to.buffer.set(buffer);\n    return to as unknown as any;\n  }\n  clone(): T {\n    return this._cloneInto();\n  }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state from RFC 6234 \u00A76.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([\n  0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state `H(0)` from RFC 6234 \u00A76.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([\n  0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state from RFC 6234 \u00A76.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([\n  0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n  0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state from RFC 6234 \u00A76.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([\n  0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n  0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n", "/**\n\nSHA1 (RFC 3174), MD5 (RFC 1321), and RIPEMD160 legacy, weak hash functions.\nRFC 2286 only covers HMAC-RIPEMD160 wrapper material and test vectors,\nnot the base RIPEMD-160 compression spec.\nDon't use them in a new protocol. What \"weak\" means:\n\n- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.\n- No practical pre-image attacks (only theoretical, 2^123.4)\n- HMAC seems kinda ok: https://www.rfc-editor.org/rfc/rfc6151\n * @module\n */\nimport { Chi, HashMD, Maj } from './_md.ts';\nimport { type CHash, clean, createHasher, rotl, type TRet } from './utils.ts';\n\n/** Initial SHA-1 state from RFC 3174 \u00A76.1. */\nconst SHA1_IV = /* @__PURE__ */ Uint32Array.from([\n  0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n\n// Reusable 80-word SHA-1 message schedule buffer.\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal SHA1 legacy hash class. */\nexport class _SHA1 extends HashMD<_SHA1> {\n  private A = SHA1_IV[0] | 0;\n  private B = SHA1_IV[1] | 0;\n  private C = SHA1_IV[2] | 0;\n  private D = SHA1_IV[3] | 0;\n  private E = SHA1_IV[4] | 0;\n\n  constructor() {\n    super(64, 20, 8, false);\n  }\n  protected get(): [number, number, number, number, number] {\n    const { A, B, C, D, E } = this;\n    return [A, B, C, D, E];\n  }\n  protected set(A: number, B: number, C: number, D: number, E: number): void {\n    this.A = A | 0;\n    this.B = B | 0;\n    this.C = C | 0;\n    this.D = D | 0;\n    this.E = E | 0;\n  }\n  protected process(view: DataView, offset: number): void {\n    for (let i = 0; i < 16; i++, offset += 4) SHA1_W[i] = view.getUint32(offset, false);\n    for (let i = 16; i < 80; i++)\n      SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n    // Compression function main loop, 80 rounds\n    let { A, B, C, D, E } = this;\n    for (let i = 0; i < 80; i++) {\n      let F, K;\n      if (i < 20) {\n        F = Chi(B, C, D);\n        K = 0x5a827999;\n      } else if (i < 40) {\n        F = B ^ C ^ D;\n        K = 0x6ed9eba1;\n      } else if (i < 60) {\n        F = Maj(B, C, D);\n        K = 0x8f1bbcdc;\n      } else {\n        F = B ^ C ^ D;\n        K = 0xca62c1d6;\n      }\n      const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n      E = D;\n      D = C;\n      C = rotl(B, 30);\n      B = A;\n      A = T;\n    }\n    // Add the compressed chunk to the current hash value\n    A = (A + this.A) | 0;\n    B = (B + this.B) | 0;\n    C = (C + this.C) | 0;\n    D = (D + this.D) | 0;\n    E = (E + this.E) | 0;\n    this.set(A, B, C, D, E);\n  }\n  protected roundClean(): void {\n    clean(SHA1_W);\n  }\n  destroy(): void {\n    // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n    // update()/digest() callable on reused instances.\n    this.destroyed = true;\n    this.set(0, 0, 0, 0, 0);\n    clean(this.buffer);\n  }\n}\n\n/**\n * SHA1 (RFC 3174) legacy hash function. It was cryptographically broken.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA1.\n * ```ts\n * sha1(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha1: TRet<CHash> = /* @__PURE__ */ createHasher(() => new _SHA1());\n\n/** RFC 1321 `T[i]` uses `floor(2^32 * abs(sin(i)))`; this is the shared `2^32` scale factor. */\nconst p32 = /* @__PURE__ */ Math.pow(2, 32);\n/** RFC 1321 `T[1..64]` table. */\nconst K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) =>\n  Math.floor(p32 * Math.abs(Math.sin(i + 1)))\n);\n\n/** MD5 initial state from RFC 1321, stored as 4 u32 words. */\nconst MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);\n\n// Reusable 16-word MD5 message block buffer.\nconst MD5_W = /* @__PURE__ */ new Uint32Array(16);\n/** Internal MD5 legacy hash class. */\nexport class _MD5 extends HashMD<_MD5> {\n  private A = MD5_IV[0] | 0;\n  private B = MD5_IV[1] | 0;\n  private C = MD5_IV[2] | 0;\n  private D = MD5_IV[3] | 0;\n\n  constructor() {\n    super(64, 16, 8, true);\n  }\n  protected get(): [number, number, number, number] {\n    const { A, B, C, D } = this;\n    return [A, B, C, D];\n  }\n  protected set(A: number, B: number, C: number, D: number): void {\n    this.A = A | 0;\n    this.B = B | 0;\n    this.C = C | 0;\n    this.D = D | 0;\n  }\n  protected process(view: DataView, offset: number): void {\n    for (let i = 0; i < 16; i++, offset += 4) MD5_W[i] = view.getUint32(offset, true);\n    // Compression function main loop, 64 rounds\n    let { A, B, C, D } = this;\n    for (let i = 0; i < 64; i++) {\n      let F, g, s;\n      if (i < 16) {\n        F = Chi(B, C, D);\n        g = i;\n        s = [7, 12, 17, 22];\n      } else if (i < 32) {\n        // RFC 1321 round 2 uses G(B,C,D) = (B & D) | (C & ~D), which is `Chi(D, B, C)`.\n        F = Chi(D, B, C);\n        g = (5 * i + 1) % 16;\n        s = [5, 9, 14, 20];\n      } else if (i < 48) {\n        F = B ^ C ^ D;\n        g = (3 * i + 5) % 16;\n        s = [4, 11, 16, 23];\n      } else {\n        F = C ^ (B | ~D);\n        g = (7 * i) % 16;\n        s = [6, 10, 15, 21];\n      }\n      F = F + A + K[i] + MD5_W[g];\n      A = D;\n      D = C;\n      C = B;\n      B = B + rotl(F, s[i % 4]);\n    }\n    // Add the compressed chunk to the current hash value\n    A = (A + this.A) | 0;\n    B = (B + this.B) | 0;\n    C = (C + this.C) | 0;\n    D = (D + this.D) | 0;\n    this.set(A, B, C, D);\n  }\n  protected roundClean(): void {\n    clean(MD5_W);\n  }\n  destroy(): void {\n    // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n    // update()/digest() callable on reused instances.\n    this.destroyed = true;\n    this.set(0, 0, 0, 0);\n    clean(this.buffer);\n  }\n}\n\n/**\n * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.\n * MD5 architecture is similar to SHA1, with some differences:\n * - Reduced output length: 16 bytes (128 bit) instead of 20\n * - 64 rounds, instead of 80\n * - Little-endian: could be faster, but will require more code\n * - Non-linear index selection: huge speed-up for unroll\n * - Per round constants: more memory accesses, additional speed-up for unroll\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with MD5.\n * ```ts\n * md5(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const md5: TRet<CHash> = /* @__PURE__ */ createHasher(() => new _MD5());\n\n// RIPEMD-160\n\n// Permutation repeatedly applied to derive the later RIPEMD-160 message-order tables.\nconst Rho160 = /* @__PURE__ */ Uint8Array.from([\n  7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n]);\nconst Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();\nconst Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();\n// Five left/right message-word orderings for the RIPEMD-160 dual-lane rounds.\nconst idxLR = /* @__PURE__ */ (() => {\n  const L = [Id160];\n  const R = [Pi160];\n  const res = [L, R];\n  for (let i = 0; i < 4; i++) for (let j of res) j.push(j[i].map((k) => Rho160[k]));\n  return res;\n})();\nconst idxL = /* @__PURE__ */ (() => idxLR[0])();\nconst idxR = /* @__PURE__ */ (() => idxLR[1])();\n// const [idxL, idxR] = idxLR;\n\n// Base per-group shift table before the left/right message-order permutations are applied.\nconst shifts160 = /* @__PURE__ */ [\n  [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n  [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n  [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n  [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n  [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => Uint8Array.from(i));\nconst shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));\n// Five left-lane additive constants for RIPEMD-160.\nconst Kl160 = /* @__PURE__ */ Uint32Array.from([\n  0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\n// Five right-lane additive constants for RIPEMD-160.\nconst Kr160 = /* @__PURE__ */ Uint32Array.from([\n  0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// Called `f()` in the spec; valid `group` values are 0..4, and out-of-range\n// inputs currently fall through to the group-4 branch.\nfunction ripemd_f(group: number, x: number, y: number, z: number): number {\n  if (group === 0) return x ^ y ^ z;\n  if (group === 1) return (x & y) | (~x & z);\n  if (group === 2) return (x | ~y) ^ z;\n  if (group === 3) return (x & z) | (y & ~z);\n  return x ^ (y | ~z);\n}\n// Reusable 16-word RIPEMD-160 message block buffer.\nconst BUF_160 = /* @__PURE__ */ new Uint32Array(16);\n/**\n * Internal RIPEMD-160 legacy hash class.\n * RFC 2286 only adds HMAC-RIPEMD160 material, not the core hash specification.\n */\nexport class _RIPEMD160 extends HashMD<_RIPEMD160> {\n  private h0 = 0x67452301 | 0;\n  private h1 = 0xefcdab89 | 0;\n  private h2 = 0x98badcfe | 0;\n  private h3 = 0x10325476 | 0;\n  private h4 = 0xc3d2e1f0 | 0;\n\n  constructor() {\n    super(64, 20, 8, true);\n  }\n  protected get(): [number, number, number, number, number] {\n    const { h0, h1, h2, h3, h4 } = this;\n    return [h0, h1, h2, h3, h4];\n  }\n  protected set(h0: number, h1: number, h2: number, h3: number, h4: number): void {\n    this.h0 = h0 | 0;\n    this.h1 = h1 | 0;\n    this.h2 = h2 | 0;\n    this.h3 = h3 | 0;\n    this.h4 = h4 | 0;\n  }\n  protected process(view: DataView, offset: number): void {\n    for (let i = 0; i < 16; i++, offset += 4) BUF_160[i] = view.getUint32(offset, true);\n    // prettier-ignore\n    let al = this.h0 | 0, ar = al,\n        bl = this.h1 | 0, br = bl,\n        cl = this.h2 | 0, cr = cl,\n        dl = this.h3 | 0, dr = dl,\n        el = this.h4 | 0, er = el;\n\n    // Instead of iterating 0 to 80, we split it into 5 groups\n    // And use the groups in constants, functions, etc. Much simpler\n    for (let group = 0; group < 5; group++) {\n      const rGroup = 4 - group;\n      const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore\n      const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n      const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore\n      for (let i = 0; i < 16; i++) {\n        const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;\n        al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n      }\n      // 2 loops are 10% faster\n      for (let i = 0; i < 16; i++) {\n        const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;\n        ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n      }\n    }\n    // Add the compressed chunk to the current hash value\n    // Final recombination cross-adds the left/right lane accumulators into the next h0..h4 order.\n    this.set(\n      (this.h1 + cl + dr) | 0,\n      (this.h2 + dl + er) | 0,\n      (this.h3 + el + ar) | 0,\n      (this.h4 + al + br) | 0,\n      (this.h0 + bl + cr) | 0\n    );\n  }\n  protected roundClean(): void {\n    clean(BUF_160);\n  }\n  destroy(): void {\n    this.destroyed = true;\n    clean(this.buffer);\n    this.set(0, 0, 0, 0, 0);\n  }\n}\n\n/**\n * RIPEMD-160 - a legacy hash function from 1990s.\n * RFC 2286 only covers HMAC-RIPEMD160 test material; the links below point\n * at the base RIPEMD-160 references.\n * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160.html}\n * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf}\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with RIPEMD-160.\n * ```ts\n * ripemd160(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const ripemd160: TRet<CHash> = /* @__PURE__ */ createHasher(() => new _RIPEMD160());\n", "/**\n * Internal helpers for u64.\n * BigUint64Array is too slow as per 2026, so we implement it using\n * Uint32Array.\n * @privateRemarks TODO: re-check {@link https://issues.chromium.org/issues/42212588}\n * @module\n */\nimport type { TRet } from './utils.ts';\n\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(\n  n: bigint,\n  le = false\n): {\n  h: number;\n  l: number;\n} {\n  if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n  return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\n// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst: bigint[], le = false): TRet<Uint32Array[]> {\n  const len = lst.length;\n  let Ah = new Uint32Array(len);\n  let Al = new Uint32Array(len);\n  for (let i = 0; i < len; i++) {\n    const { h, l } = fromBig(lst[i], le);\n    [Ah[i], Al[i]] = [h, l];\n  }\n  return [Ah, Al] as TRet<Uint32Array[]>;\n}\n\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h: number, l: number): number => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h: number, _l: number): number => h;\n// High 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\n// Low 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.\nconst rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));\n// High 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));\n// Low 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));\n\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(\n  Ah: number,\n  Al: number,\n  Bh: number,\n  Bl: number\n): {\n  h: number;\n  l: number;\n} {\n  const l = (Al >>> 0) + (Bl >>> 0);\n  return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n  (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n  (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n  (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number =>\n  (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number =>\n  (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n  add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// Canonical grouped namespace for callers that prefer one object.\n// Named exports stay for direct imports.\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\n  fromBig, split, toBig,\n  shrSH, shrSL,\n  rotrSH, rotrSL, rotrBH, rotrBL,\n  rotr32H, rotr32L,\n  rotlSH, rotlSL, rotlBH, rotlBL,\n  add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n// Default export mirrors named `u64` for compatibility with object-style imports.\nexport default u64;\n", "/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, oidNist, rotr, type TRet } from './utils.ts';\n\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 \u00A75.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n  0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n  0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n  0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n  0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 \u00A76.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 \u00A76.2. */\nabstract class SHA2_32B<T extends SHA2_32B<T>> extends HashMD<T> {\n  // We cannot use array here since array allows indexing by variable\n  // which means optimizer/compiler cannot use registers.\n  protected abstract A: number;\n  protected abstract B: number;\n  protected abstract C: number;\n  protected abstract D: number;\n  protected abstract E: number;\n  protected abstract F: number;\n  protected abstract G: number;\n  protected abstract H: number;\n\n  constructor(outputLen: number) {\n    super(64, outputLen, 8, false);\n  }\n  protected get(): [number, number, number, number, number, number, number, number] {\n    const { A, B, C, D, E, F, G, H } = this;\n    return [A, B, C, D, E, F, G, H];\n  }\n  // prettier-ignore\n  protected set(\n    A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n  ): void {\n    this.A = A | 0;\n    this.B = B | 0;\n    this.C = C | 0;\n    this.D = D | 0;\n    this.E = E | 0;\n    this.F = F | 0;\n    this.G = G | 0;\n    this.H = H | 0;\n  }\n  protected process(view: DataView, offset: number): void {\n    // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n    for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n    for (let i = 16; i < 64; i++) {\n      const W15 = SHA256_W[i - 15];\n      const W2 = SHA256_W[i - 2];\n      const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n      const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n      SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n    }\n    // Compression function main loop, 64 rounds\n    let { A, B, C, D, E, F, G, H } = this;\n    for (let i = 0; i < 64; i++) {\n      const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n      const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n      const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n      const T2 = (sigma0 + Maj(A, B, C)) | 0;\n      H = G;\n      G = F;\n      F = E;\n      E = (D + T1) | 0;\n      D = C;\n      C = B;\n      B = A;\n      A = (T1 + T2) | 0;\n    }\n    // Add the compressed chunk to the current hash value\n    A = (A + this.A) | 0;\n    B = (B + this.B) | 0;\n    C = (C + this.C) | 0;\n    D = (D + this.D) | 0;\n    E = (E + this.E) | 0;\n    F = (F + this.F) | 0;\n    G = (G + this.G) | 0;\n    H = (H + this.H) | 0;\n    this.set(A, B, C, D, E, F, G, H);\n  }\n  protected roundClean(): void {\n    clean(SHA256_W);\n  }\n  destroy(): void {\n    // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n    // update()/digest() callable on reused instances.\n    this.destroyed = true;\n    this.set(0, 0, 0, 0, 0, 0, 0, 0);\n    clean(this.buffer);\n  }\n}\n\n/** Internal SHA-256 hash class grounded in RFC 6234 \u00A76.2. */\nexport class _SHA256 extends SHA2_32B<_SHA256> {\n  // We cannot use array here since array allows indexing by variable\n  // which means optimizer/compiler cannot use registers.\n  protected A: number = SHA256_IV[0] | 0;\n  protected B: number = SHA256_IV[1] | 0;\n  protected C: number = SHA256_IV[2] | 0;\n  protected D: number = SHA256_IV[3] | 0;\n  protected E: number = SHA256_IV[4] | 0;\n  protected F: number = SHA256_IV[5] | 0;\n  protected G: number = SHA256_IV[6] | 0;\n  protected H: number = SHA256_IV[7] | 0;\n  constructor() {\n    super(32);\n  }\n}\n\n/** Internal SHA-224 hash class grounded in RFC 6234 \u00A76.2 and \u00A78.5. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\n  protected A: number = SHA224_IV[0] | 0;\n  protected B: number = SHA224_IV[1] | 0;\n  protected C: number = SHA224_IV[2] | 0;\n  protected D: number = SHA224_IV[3] | 0;\n  protected E: number = SHA224_IV[4] | 0;\n  protected F: number = SHA224_IV[5] | 0;\n  protected G: number = SHA224_IV[6] | 0;\n  protected H: number = SHA224_IV[7] | 0;\n  constructor() {\n    super(28);\n  }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// SHA-384 / SHA-512 round constants from RFC 6234 \u00A75.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n  '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n  '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n  '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n  '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n  '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n  '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n  '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n  '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n  '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n  '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n  '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n  '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n  '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n  '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n  '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n  '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n  '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n  '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n  '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n  '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable high-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 \u00A76.4. */\nabstract class SHA2_64B<T extends SHA2_64B<T>> extends HashMD<T> {\n  // We cannot use array here since array allows indexing by variable\n  // which means optimizer/compiler cannot use registers.\n  // h -- high 32 bits, l -- low 32 bits\n  protected abstract Ah: number;\n  protected abstract Al: number;\n  protected abstract Bh: number;\n  protected abstract Bl: number;\n  protected abstract Ch: number;\n  protected abstract Cl: number;\n  protected abstract Dh: number;\n  protected abstract Dl: number;\n  protected abstract Eh: number;\n  protected abstract El: number;\n  protected abstract Fh: number;\n  protected abstract Fl: number;\n  protected abstract Gh: number;\n  protected abstract Gl: number;\n  protected abstract Hh: number;\n  protected abstract Hl: number;\n\n  constructor(outputLen: number) {\n    super(128, outputLen, 16, false);\n  }\n  // prettier-ignore\n  protected get(): [\n    number, number, number, number, number, number, number, number,\n    number, number, number, number, number, number, number, number\n  ] {\n    const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n    return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n  }\n  // prettier-ignore\n  protected set(\n    Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n    Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n  ): void {\n    this.Ah = Ah | 0;\n    this.Al = Al | 0;\n    this.Bh = Bh | 0;\n    this.Bl = Bl | 0;\n    this.Ch = Ch | 0;\n    this.Cl = Cl | 0;\n    this.Dh = Dh | 0;\n    this.Dl = Dl | 0;\n    this.Eh = Eh | 0;\n    this.El = El | 0;\n    this.Fh = Fh | 0;\n    this.Fl = Fl | 0;\n    this.Gh = Gh | 0;\n    this.Gl = Gl | 0;\n    this.Hh = Hh | 0;\n    this.Hl = Hl | 0;\n  }\n  protected process(view: DataView, offset: number): void {\n    // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n    for (let i = 0; i < 16; i++, offset += 4) {\n      SHA512_W_H[i] = view.getUint32(offset);\n      SHA512_W_L[i] = view.getUint32((offset += 4));\n    }\n    for (let i = 16; i < 80; i++) {\n      // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n      const W15h = SHA512_W_H[i - 15] | 0;\n      const W15l = SHA512_W_L[i - 15] | 0;\n      const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n      const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n      // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n      const W2h = SHA512_W_H[i - 2] | 0;\n      const W2l = SHA512_W_L[i - 2] | 0;\n      const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n      const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n      // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n      const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n      const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n      SHA512_W_H[i] = SUMh | 0;\n      SHA512_W_L[i] = SUMl | 0;\n    }\n    let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n    // Compression function main loop, 80 rounds\n    for (let i = 0; i < 80; i++) {\n      // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n      const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n      const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n      //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n      const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n      const CHIl = (El & Fl) ^ (~El & Gl);\n      // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n      // prettier-ignore\n      const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n      const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n      const T1l = T1ll | 0;\n      // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n      const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n      const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n      const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n      const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n      Hh = Gh | 0;\n      Hl = Gl | 0;\n      Gh = Fh | 0;\n      Gl = Fl | 0;\n      Fh = Eh | 0;\n      Fl = El | 0;\n      ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n      Dh = Ch | 0;\n      Dl = Cl | 0;\n      Ch = Bh | 0;\n      Cl = Bl | 0;\n      Bh = Ah | 0;\n      Bl = Al | 0;\n      const All = u64.add3L(T1l, sigma0l, MAJl);\n      Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n      Al = All | 0;\n    }\n    // Add the compressed chunk to the current hash value\n    ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n    ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n    ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n    ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n    ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n    ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n    ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n    ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n    this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n  }\n  protected roundClean(): void {\n    clean(SHA512_W_H, SHA512_W_L);\n  }\n  destroy(): void {\n    // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n    // update()/digest() callable on reused instances.\n    this.destroyed = true;\n    clean(this.buffer);\n    this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n  }\n}\n\n/** Internal SHA-512 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\n  protected Ah: number = SHA512_IV[0] | 0;\n  protected Al: number = SHA512_IV[1] | 0;\n  protected Bh: number = SHA512_IV[2] | 0;\n  protected Bl: number = SHA512_IV[3] | 0;\n  protected Ch: number = SHA512_IV[4] | 0;\n  protected Cl: number = SHA512_IV[5] | 0;\n  protected Dh: number = SHA512_IV[6] | 0;\n  protected Dl: number = SHA512_IV[7] | 0;\n  protected Eh: number = SHA512_IV[8] | 0;\n  protected El: number = SHA512_IV[9] | 0;\n  protected Fh: number = SHA512_IV[10] | 0;\n  protected Fl: number = SHA512_IV[11] | 0;\n  protected Gh: number = SHA512_IV[12] | 0;\n  protected Gl: number = SHA512_IV[13] | 0;\n  protected Hh: number = SHA512_IV[14] | 0;\n  protected Hl: number = SHA512_IV[15] | 0;\n\n  constructor() {\n    super(64);\n  }\n}\n\n/** Internal SHA-384 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\n  protected Ah: number = SHA384_IV[0] | 0;\n  protected Al: number = SHA384_IV[1] | 0;\n  protected Bh: number = SHA384_IV[2] | 0;\n  protected Bl: number = SHA384_IV[3] | 0;\n  protected Ch: number = SHA384_IV[4] | 0;\n  protected Cl: number = SHA384_IV[5] | 0;\n  protected Dh: number = SHA384_IV[6] | 0;\n  protected Dl: number = SHA384_IV[7] | 0;\n  protected Eh: number = SHA384_IV[8] | 0;\n  protected El: number = SHA384_IV[9] | 0;\n  protected Fh: number = SHA384_IV[10] | 0;\n  protected Fl: number = SHA384_IV[11] | 0;\n  protected Gh: number = SHA384_IV[12] | 0;\n  protected Gl: number = SHA384_IV[13] | 0;\n  protected Hh: number = SHA384_IV[14] | 0;\n  protected Hl: number = SHA384_IV[15] | 0;\n\n  constructor() {\n    super(48);\n  }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n  0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n  0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n  0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n  0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B<_SHA512_224> {\n  protected Ah: number = T224_IV[0] | 0;\n  protected Al: number = T224_IV[1] | 0;\n  protected Bh: number = T224_IV[2] | 0;\n  protected Bl: number = T224_IV[3] | 0;\n  protected Ch: number = T224_IV[4] | 0;\n  protected Cl: number = T224_IV[5] | 0;\n  protected Dh: number = T224_IV[6] | 0;\n  protected Dl: number = T224_IV[7] | 0;\n  protected Eh: number = T224_IV[8] | 0;\n  protected El: number = T224_IV[9] | 0;\n  protected Fh: number = T224_IV[10] | 0;\n  protected Fl: number = T224_IV[11] | 0;\n  protected Gh: number = T224_IV[12] | 0;\n  protected Gl: number = T224_IV[13] | 0;\n  protected Hh: number = T224_IV[14] | 0;\n  protected Hl: number = T224_IV[15] | 0;\n\n  constructor() {\n    super(28);\n  }\n}\n\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B<_SHA512_256> {\n  protected Ah: number = T256_IV[0] | 0;\n  protected Al: number = T256_IV[1] | 0;\n  protected Bh: number = T256_IV[2] | 0;\n  protected Bl: number = T256_IV[3] | 0;\n  protected Ch: number = T256_IV[4] | 0;\n  protected Cl: number = T256_IV[5] | 0;\n  protected Dh: number = T256_IV[6] | 0;\n  protected Dl: number = T256_IV[7] | 0;\n  protected Eh: number = T256_IV[8] | 0;\n  protected El: number = T256_IV[9] | 0;\n  protected Fh: number = T256_IV[10] | 0;\n  protected Fl: number = T256_IV[11] | 0;\n  protected Gh: number = T256_IV[12] | 0;\n  protected Gl: number = T256_IV[13] | 0;\n  protected Hh: number = T256_IV[14] | 0;\n  protected Hl: number = T256_IV[15] | 0;\n\n  constructor() {\n    super(32);\n  }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256: TRet<CHash<_SHA256>> = /* @__PURE__ */ createHasher(\n  () => new _SHA256(),\n  /* @__PURE__ */ oidNist(0x01)\n);\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224: TRet<CHash<_SHA224>> = /* @__PURE__ */ createHasher(\n  () => new _SHA224(),\n  /* @__PURE__ */ oidNist(0x04)\n);\n\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512: TRet<CHash<_SHA512>> = /* @__PURE__ */ createHasher(\n  () => new _SHA512(),\n  /* @__PURE__ */ oidNist(0x03)\n);\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384: TRet<CHash<_SHA384>> = /* @__PURE__ */ createHasher(\n  () => new _SHA384(),\n  /* @__PURE__ */ oidNist(0x02)\n);\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256: TRet<CHash<_SHA512_256>> = /* @__PURE__ */ createHasher(\n  () => new _SHA512_256(),\n  /* @__PURE__ */ oidNist(0x06)\n);\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224: TRet<CHash<_SHA512_224>> = /* @__PURE__ */ createHasher(\n  () => new _SHA512_224(),\n  /* @__PURE__ */ oidNist(0x05)\n);\n", "/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n  abytes as abytes_,\n  anumber as anumber_,\n  bytesToHex as bytesToHex_,\n  concatBytes as concatBytes_,\n  hexToBytes as hexToBytes_,\n  isBytes as isBytes_,\n  randomBytes as randomBytes_,\n} from '@noble/hashes/utils.js';\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg<T> = T extends BigInt64Array\n  ? BigInt64Array\n  : T extends BigUint64Array\n    ? BigUint64Array\n    : T extends Float32Array\n      ? Float32Array\n      : T extends Float64Array\n        ? Float64Array\n        : T extends Int16Array\n          ? Int16Array\n          : T extends Int32Array\n            ? Int32Array\n            : T extends Int8Array\n              ? Int8Array\n              : T extends Uint16Array\n                ? Uint16Array\n                : T extends Uint32Array\n                  ? Uint32Array\n                  : T extends Uint8ClampedArray\n                    ? Uint8ClampedArray\n                    : T extends Uint8Array\n                      ? Uint8Array\n                      : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet<T> = T extends BigInt64Array\n  ? ReturnType<typeof BigInt64Array.of>\n  : T extends BigUint64Array\n    ? ReturnType<typeof BigUint64Array.of>\n    : T extends Float32Array\n      ? ReturnType<typeof Float32Array.of>\n      : T extends Float64Array\n        ? ReturnType<typeof Float64Array.of>\n        : T extends Int16Array\n          ? ReturnType<typeof Int16Array.of>\n          : T extends Int32Array\n            ? ReturnType<typeof Int32Array.of>\n            : T extends Int8Array\n              ? ReturnType<typeof Int8Array.of>\n              : T extends Uint16Array\n                ? ReturnType<typeof Uint16Array.of>\n                : T extends Uint32Array\n                  ? ReturnType<typeof Uint32Array.of>\n                  : T extends Uint8ClampedArray\n                    ? ReturnType<typeof Uint8ClampedArray.of>\n                    : T extends Uint8Array\n                      ? ReturnType<typeof Uint8Array.of>\n                      : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg<T> =\n  | T\n  | ([TypedArg<T>] extends [never]\n      ? T extends (...args: infer A) => infer R\n        ? ((...args: { [K in keyof A]: TRet<A[K]> }) => TArg<R>) & {\n            [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;\n          }\n        : T extends [infer A, ...infer R]\n          ? [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n          : T extends readonly [infer A, ...infer R]\n            ? readonly [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n            : T extends (infer A)[]\n              ? TArg<A>[]\n              : T extends readonly (infer A)[]\n                ? readonly TArg<A>[]\n                : T extends Promise<infer A>\n                  ? Promise<TArg<A>>\n                  : T extends object\n                    ? { [K in keyof T]: TArg<T[K]> }\n                    : T\n      : TypedArg<T>);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet<T> = T extends unknown\n  ? T &\n      ([TypedRet<T>] extends [never]\n        ? T extends (...args: infer A) => infer R\n          ? ((...args: { [K in keyof A]: TArg<A[K]> }) => TRet<R>) & {\n              [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;\n            }\n          : T extends [infer A, ...infer R]\n            ? [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n            : T extends readonly [infer A, ...infer R]\n              ? readonly [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n              : T extends (infer A)[]\n                ? TRet<A>[]\n                : T extends readonly (infer A)[]\n                  ? readonly TRet<A>[]\n                  : T extends Promise<infer A>\n                    ? Promise<TRet<A>>\n                    : T extends object\n                      ? { [K in keyof T]: TRet<T[K]> }\n                      : T\n        : TypedRet<T>)\n  : never;\n/**\n * Validates that a value is a byte array.\n * @param value - Value to validate.\n * @param length - Optional exact byte length.\n * @param title - Optional field name.\n * @returns Original byte array.\n * @example\n * Reject non-byte input before passing data into curve code.\n *\n * ```ts\n * abytes(new Uint8Array(1));\n * ```\n */\nexport const abytes = <T extends TArg<Uint8Array>>(value: T, length?: number, title?: string): T =>\n  abytes_(value, length, title) as T;\n/**\n * Validates that a value is a non-negative safe integer.\n * @param n - Value to validate.\n * @param title - Optional field name.\n * @example\n * Validate a numeric length before allocating buffers.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport const anumber: typeof anumber_ = anumber_;\n/**\n * Encodes bytes as lowercase hex.\n * @param bytes - Bytes to encode.\n * @returns Lowercase hex string.\n * @example\n * Serialize bytes as hex for logging or fixtures.\n *\n * ```ts\n * bytesToHex(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport const bytesToHex: typeof bytesToHex_ = bytesToHex_;\n/**\n * Concatenates byte arrays.\n * @param arrays - Byte arrays to join.\n * @returns Concatenated bytes.\n * @example\n * Join domain-separated chunks into one buffer.\n *\n * ```ts\n * concatBytes(Uint8Array.of(1), Uint8Array.of(2));\n * ```\n */\nexport const concatBytes = (...arrays: TArg<Uint8Array[]>): TRet<Uint8Array> =>\n  concatBytes_(...arrays) as TRet<Uint8Array>;\n/**\n * Decodes lowercase or uppercase hex into bytes.\n * @param hex - Hex string to decode.\n * @returns Decoded bytes.\n * @example\n * Parse fixture hex into bytes before hashing.\n *\n * ```ts\n * hexToBytes('0102');\n * ```\n */\nexport const hexToBytes = (hex: string): TRet<Uint8Array> => hexToBytes_(hex) as TRet<Uint8Array>;\n/**\n * Checks whether a value is a Uint8Array.\n * @param a - Value to inspect.\n * @returns `true` when `a` is a Uint8Array.\n * @example\n * Branch on byte input before decoding it.\n *\n * ```ts\n * isBytes(new Uint8Array(1));\n * ```\n */\nexport const isBytes: typeof isBytes_ = isBytes_;\n/**\n * Reads random bytes from the platform CSPRNG.\n * @param bytesLength - Number of random bytes to read.\n * @returns Fresh random bytes.\n * @example\n * Generate a random seed for a keypair.\n *\n * ```ts\n * randomBytes(2);\n * ```\n */\nexport const randomBytes = (bytesLength?: number): TRet<Uint8Array> =>\n  randomBytes_(bytesLength) as TRet<Uint8Array>;\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\n/** Callable hash interface with metadata and optional extendable output support. */\nexport type CHash = {\n  /**\n   * Hash one message.\n   * @param message - Message bytes to hash.\n   * @returns Digest bytes.\n   */\n  (message: TArg<Uint8Array>): TRet<Uint8Array>;\n  /** Hash block length in bytes. */\n  blockLen: number;\n  /** Default output length in bytes. */\n  outputLen: number;\n  /** Whether `.create()` can be used as an XOF stream. */\n  canXOF: boolean;\n  /**\n   * Create one stateful hash or XOF instance, for example SHAKE with a custom output length.\n   * @param opts - Optional extendable-output configuration:\n   *   - `dkLen` (optional): Optional output length for XOF-style hashes.\n   * @returns Hash instance.\n   */\n  create(opts?: { dkLen?: number }): any;\n};\n/** Plain callable hash interface. */\nexport type FHash = (message: TArg<Uint8Array>) => TRet<Uint8Array>;\n/** HMAC callback signature. */\nexport type HmacFn = (key: TArg<Uint8Array>, message: TArg<Uint8Array>) => TRet<Uint8Array>;\n/**\n * Validates that a flag is boolean.\n * @param value - Value to validate.\n * @param title - Optional field name.\n * @returns Original value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Reject non-boolean option flags early.\n *\n * ```ts\n * abool(true);\n * ```\n */\nexport function abool(value: boolean, title: string = ''): boolean {\n  if (typeof value !== 'boolean') {\n    const prefix = title && `\"${title}\" `;\n    throw new TypeError(prefix + 'expected boolean, got type=' + typeof value);\n  }\n  return value;\n}\n\n/**\n * Validates that a value is a non-negative bigint or safe integer.\n * @param n - Value to validate.\n * @returns The same validated value.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate one integer-like value before serializing it.\n *\n * ```ts\n * abignumber(1n);\n * ```\n */\nexport function abignumber<T extends number | bigint>(n: T): T {\n  if (typeof n === 'bigint') {\n    if (!isPosBig(n)) throw new RangeError('positive bigint expected, got ' + n);\n  } else anumber(n);\n  return n;\n}\n\n/**\n * Validates that a value is a safe integer.\n * @param value - Integer to validate.\n * @param title - Optional field name.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a window size before scalar arithmetic uses it.\n *\n * ```ts\n * asafenumber(1);\n * ```\n */\nexport function asafenumber(value: number, title: string = ''): void {\n  if (typeof value !== 'number') {\n    const prefix = title && `\"${title}\" `;\n    throw new TypeError(prefix + 'expected number, got type=' + typeof value);\n  }\n  if (!Number.isSafeInteger(value)) {\n    const prefix = title && `\"${title}\" `;\n    throw new RangeError(prefix + 'expected safe integer, got ' + value);\n  }\n}\n\n/**\n * Encodes a bigint into even-length big-endian hex.\n * The historical \"unpadded\" name only means \"no fixed-width field padding\"; odd-length hex still\n * gets one leading zero nibble so the result always represents whole bytes.\n * @param num - Number to encode.\n * @returns Big-endian hex string.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Encode a scalar into hex without a `0x` prefix.\n *\n * ```ts\n * numberToHexUnpadded(255n);\n * ```\n */\nexport function numberToHexUnpadded(num: number | bigint): string {\n  const hex = abignumber(num).toString(16);\n  return hex.length & 1 ? '0' + hex : hex;\n}\n\n/**\n * Parses a big-endian hex string into bigint.\n * Accepts odd-length hex through the native `BigInt('0x' + hex)` parser and currently surfaces the\n * same native `SyntaxError` for malformed hex instead of wrapping it in a library-specific error.\n * @param hex - Hex string without `0x`.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Parse a scalar from fixture hex.\n *\n * ```ts\n * hexToNumber('ff');\n * ```\n */\nexport function hexToNumber(hex: string): bigint {\n  if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n  return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// BE: Big Endian, LE: Little Endian\n/**\n * Parses big-endian bytes into bigint.\n * @param bytes - Bytes in big-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in network byte order.\n *\n * ```ts\n * bytesToNumberBE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberBE(bytes: TArg<Uint8Array>): bigint {\n  return hexToNumber(bytesToHex_(bytes));\n}\n/**\n * Parses little-endian bytes into bigint.\n * @param bytes - Bytes in little-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in little-endian form.\n *\n * ```ts\n * bytesToNumberLE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberLE(bytes: TArg<Uint8Array>): bigint {\n  return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\n\n/**\n * Encodes a bigint into fixed-length big-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes. Must be greater than zero.\n * @returns Big-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a scalar into a 32-byte field element.\n *\n * ```ts\n * numberToBytesBE(255n, 2);\n * ```\n */\nexport function numberToBytesBE(n: number | bigint, len: number): TRet<Uint8Array> {\n  anumber_(len);\n  if (len === 0) throw new RangeError('zero length');\n  n = abignumber(n);\n  const hex = n.toString(16);\n  // Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error.\n  if (hex.length > len * 2) throw new RangeError('number too large');\n  return hexToBytes_(hex.padStart(len * 2, '0')) as TRet<Uint8Array>;\n}\n/**\n * Encodes a bigint into fixed-length little-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes.\n * @returns Little-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a scalar for little-endian protocols.\n *\n * ```ts\n * numberToBytesLE(255n, 2);\n * ```\n */\nexport function numberToBytesLE(n: number | bigint, len: number): TRet<Uint8Array> {\n  return numberToBytesBE(n, len).reverse() as TRet<Uint8Array>;\n}\n// Unpadded, rarely used\n/**\n * Encodes a bigint into variable-length big-endian bytes.\n * @param n - Number to encode.\n * @returns Variable-length big-endian bytes.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a bigint without fixed-width padding.\n *\n * ```ts\n * numberToVarBytesBE(255n);\n * ```\n */\nexport function numberToVarBytesBE(n: number | bigint): TRet<Uint8Array> {\n  return hexToBytes_(numberToHexUnpadded(abignumber(n))) as TRet<Uint8Array>;\n}\n\n// Compares 2 u8a-s in kinda constant time\n/**\n * Compares two byte arrays in constant-ish time.\n * @param a - Left byte array.\n * @param b - Right byte array.\n * @returns `true` when bytes match.\n * @example\n * Compare two encoded points without early exit.\n *\n * ```ts\n * equalBytes(Uint8Array.of(1), Uint8Array.of(1));\n * ```\n */\nexport function equalBytes(a: TArg<Uint8Array>, b: TArg<Uint8Array>): boolean {\n  a = abytes(a);\n  b = abytes(b);\n  if (a.length !== b.length) return false;\n  let diff = 0;\n  for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n  return diff === 0;\n}\n\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n * @param bytes - Bytes to copy.\n * @returns Detached copy.\n * @example\n * Make an isolated copy before mutating serialized bytes.\n *\n * ```ts\n * copyBytes(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport function copyBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array> {\n  // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n  // because callers use it at byte-validation boundaries before mutating the detached copy.\n  return Uint8Array.from(abytes(bytes)) as TRet<Uint8Array>;\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n * @param ascii - ASCII input text.\n * @returns Encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode an ASCII domain-separation tag.\n *\n * ```ts\n * asciiToBytes('ABC');\n * ```\n */\nexport function asciiToBytes(ascii: string): TRet<Uint8Array> {\n  if (typeof ascii !== 'string') throw new TypeError('ascii string expected, got ' + typeof ascii);\n  return Uint8Array.from(ascii, (c, i) => {\n    const charCode = c.charCodeAt(0);\n    if (c.length !== 1 || charCode > 127) {\n      throw new RangeError(\n        `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n      );\n    }\n    return charCode;\n  }) as TRet<Uint8Array>;\n}\n\n// Historical name: this accepts non-negative bigints, including zero.\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\n/**\n * Checks whether a bigint lies inside a half-open range.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * @returns `true` when the value is inside the range.\n * @example\n * Check whether a candidate scalar fits the field order.\n *\n * ```ts\n * inRange(2n, 1n, 3n);\n * ```\n */\nexport function inRange(n: bigint, min: bigint, max: bigint): boolean {\n  return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts `min <= n < max`. NOTE: upper bound is exclusive.\n * @param title - Value label for error messages.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * Wrong-type inputs are not separated from out-of-range values here: they still flow through the\n * shared `RangeError` path because this is only a throwing wrapper around `inRange(...)`.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Assert that a bigint stays within one half-open range.\n *\n * ```ts\n * aInRange('x', 2n, 1n, 256n);\n * ```\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {\n  // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n  // consider P=256n, min=0n, max=P\n  // - a for min=0 would require -1:          `inRange('x', x, -1n, P)`\n  // - b would commonly require subtraction:  `inRange('x', x, 0n, P - 1n)`\n  // - our way is the cleanest:               `inRange('x', x, 0n, P)\n  if (!inRange(n, min, max))\n    throw new RangeError('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n * @param n - Value to inspect.\n * @returns Bit length.\n * @throws If the value is negative. {@link Error}\n * @example\n * Measure the bit length of a scalar before serialization.\n *\n * ```ts\n * bitLen(8n);\n * ```\n */\nexport function bitLen(n: bigint): number {\n  // Size callers in this repo only use non-negative orders / scalars, so negative inputs are a\n  // contract bug and must not silently collapse to zero bits.\n  if (n < _0n) throw new Error('expected non-negative bigint, got ' + n);\n  let len;\n  for (len = 0; n > _0n; n >>= _1n, len += 1);\n  return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw\n *   bigint shift semantics; because the mask is built as `1n << pos`,\n *   they currently collapse to `0n` and make the helper a no-op.\n * @returns Bit as bigint.\n * @example\n * Gets single bit at position.\n *\n * ```ts\n * bitGet(5n, 0);\n * ```\n */\nexport function bitGet(n: bigint, pos: number): bigint {\n  return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw bigint shift semantics,\n *   so they currently behave like left shifts.\n * @param value - Whether the bit should be set.\n * @returns Updated bigint.\n * @example\n * Sets single bit at position.\n *\n * ```ts\n * bitSet(0n, 1, true);\n * ```\n */\nexport function bitSet(n: bigint, pos: number, value: boolean): bigint {\n  const mask = _1n << BigInt(pos);\n  // Clearing needs AND-not here; OR with zero leaves an already-set bit untouched.\n  return value ? n | mask : n & ~mask;\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n * @param n - Number of bits. Negative widths are currently passed through to raw bigint shift\n *   semantics and therefore produce `-1n`.\n * @returns Bitmask value.\n * @example\n * Calculate mask for N bits.\n *\n * ```ts\n * bitMask(4);\n * ```\n */\nexport const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\ntype Pred<T> = (v: TArg<Uint8Array>) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @param hashLen - Hash output size in bytes. Callers are expected to pass a positive length; `0`\n *   is not rejected here and would make the internal generate loop non-progressing.\n * @param qByteLen - Requested output size in bytes. Callers are expected to pass a positive length.\n * @param hmacFn - HMAC implementation.\n * @returns Function that will call DRBG until the predicate returns anything\n *   other than `undefined`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Build a deterministic nonce generator for RFC6979-style signing.\n *\n * ```ts\n * import { createHmacDrbg } from '@noble/curves/utils.js';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const drbg = createHmacDrbg(32, 32, (key, msg) => hmac(sha256, key, msg));\n * const seed = new Uint8Array(32);\n * drbg(seed, (bytes) => bytes);\n * ```\n */\nexport function createHmacDrbg<T>(\n  hashLen: number,\n  qByteLen: number,\n  hmacFn: TArg<HmacFn>\n): TRet<(seed: Uint8Array, predicate: Pred<T>) => T> {\n  anumber_(hashLen, 'hashLen');\n  anumber_(qByteLen, 'qByteLen');\n  if (typeof hmacFn !== 'function') throw new TypeError('hmacFn must be a function');\n  // creates Uint8Array\n  const u8n = (len: number): TRet<Uint8Array> => new Uint8Array(len) as TRet<Uint8Array>;\n  const NULL = Uint8Array.of();\n  const byte0 = Uint8Array.of(0x00);\n  const byte1 = Uint8Array.of(0x01);\n  const _maxDrbgIters = 1000;\n\n  // Step B, Step C: set hashLen to 8*ceil(hlen/8).\n  // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 signatures.\n  let v: Uint8Array = u8n(hashLen);\n  // Steps B and C of RFC6979 3.2.\n  let k: Uint8Array = u8n(hashLen);\n  let i = 0; // Iterations counter, will throw when over 1000\n  const reset = () => {\n    v.fill(1);\n    k.fill(0);\n    i = 0;\n  };\n  // hmac(k)(v, ...values)\n  const h = (...msgs: TArg<Uint8Array[]>) => (hmacFn as HmacFn)(k, concatBytes(v, ...msgs));\n  const reseed = (seed: TArg<Uint8Array> = NULL) => {\n    // HMAC-DRBG reseed() function. Steps D-G\n    k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n    v = h(); // v = hmac(k || v)\n    if (seed.length === 0) return;\n    k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed)\n    v = h(); // v = hmac(k || v)\n  };\n  const gen = () => {\n    // HMAC-DRBG generate() function\n    if (i++ >= _maxDrbgIters) throw new Error('drbg: tried max amount of iterations');\n    let len = 0;\n    const out: Uint8Array[] = [];\n    while (len < qByteLen) {\n      v = h();\n      const sl = v.slice();\n      out.push(sl);\n      len += v.length;\n    }\n    return concatBytes(...out);\n  };\n  const genUntil = (seed: TArg<Uint8Array>, pred: TArg<Pred<T>>): T => {\n    reset();\n    reseed(seed); // Steps D-G\n    let res: T | undefined = undefined; // Step H: grind until the predicate accepts a candidate.\n    // Falsy values like 0 are valid outputs.\n    while ((res = (pred as Pred<T>)(gen())) === undefined) reseed();\n    reset();\n    return res;\n  };\n  return genUntil as TRet<(seed: Uint8Array, predicate: Pred<T>) => T>;\n}\n\n/**\n * Validates declared required and optional field types on a plain object.\n * Extra keys are intentionally ignored because many callers validate only the subset they use from\n * richer option bags or runtime objects.\n * @param object - Object to validate.\n * @param fields - Required field types.\n * @param optFields - Optional field types.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Check user options before building a curve helper.\n *\n * ```ts\n * validateObject({ flag: true }, { flag: 'boolean' });\n * ```\n */\nexport function validateObject(\n  object: Record<string, any>,\n  fields: Record<string, string> = {},\n  optFields: Record<string, string> = {}\n): void {\n  if (Object.prototype.toString.call(object) !== '[object Object]')\n    throw new TypeError('expected valid options object');\n  type Item = keyof typeof object;\n  function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n    // Config/data fields must be explicit own properties, but runtime objects such as Field\n    // instances intentionally satisfy required method slots via their shared prototype.\n    if (!isOpt && expectedType !== 'function' && !Object.hasOwn(object, fieldName))\n      throw new TypeError(`param \"${fieldName}\" is invalid: expected own property`);\n    const val = object[fieldName];\n    if (isOpt && val === undefined) return;\n    const current = typeof val;\n    if (current !== expectedType || val === null)\n      throw new TypeError(\n        `param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`\n      );\n  }\n  const iter = (f: typeof fields, isOpt: boolean) =>\n    Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n  iter(fields, false);\n  iter(optFields, true);\n}\n\n/**\n * Throws not implemented error.\n * @returns Never returns.\n * @throws If the unfinished code path is reached. {@link Error}\n * @example\n * Surface the placeholder error from an unfinished code path.\n *\n * ```ts\n * try {\n *   notImplemented();\n * } catch {}\n * ```\n */\nexport const notImplemented = (): never => {\n  throw new Error('not implemented');\n};\n\n/** Generic keygen/getPublicKey interface shared by curve helpers. */\nexport interface CryptoKeys {\n  /** Public byte lengths for keys and optional seeds. */\n  lengths: { seed?: number; public?: number; secret?: number };\n  /**\n   * Generate one secret/public keypair.\n   * @param seed - Optional seed bytes for deterministic key generation.\n   * @returns Fresh secret/public keypair.\n   */\n  keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n  /**\n   * Derive one public key from a secret key.\n   * @param secretKey - Secret key bytes.\n   * @returns Public key bytes.\n   */\n  getPublicKey: (secretKey: Uint8Array) => Uint8Array;\n}\n\n/** Generic interface for signatures. Has keygen, sign and verify. */\nexport interface Signer extends CryptoKeys {\n  // Interfaces are fun. We cannot just add new fields without copying old ones.\n  /** Public byte lengths for keys, signatures, and optional signing randomness. */\n  lengths: {\n    seed?: number;\n    public?: number;\n    secret?: number;\n    signRand?: number;\n    signature?: number;\n  };\n  /**\n   * Sign one message.\n   * @param msg - Message bytes to sign.\n   * @param secretKey - Secret key bytes.\n   * @returns Signature bytes.\n   */\n  sign: (msg: Uint8Array, secretKey: Uint8Array) => Uint8Array;\n  /**\n   * Verify one signature.\n   * @param sig - Signature bytes.\n   * @param msg - Signed message bytes.\n   * @param publicKey - Public key bytes.\n   * @returns `true` when the signature is valid.\n   */\n  verify: (sig: Uint8Array, msg: Uint8Array, publicKey: Uint8Array) => boolean;\n}\n", "/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n  abool,\n  abytes,\n  anumber,\n  asafenumber,\n  bitLen,\n  bytesToNumberBE,\n  bytesToNumberLE,\n  numberToBytesBE,\n  numberToBytesLE,\n  validateObject,\n  type TArg,\n  type TRet,\n} from '../utils.ts';\n\n// Numbers aren't used in x25519 / x448 builds\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);\n// prettier-ignore\nconst _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);\n// prettier-ignore\nconst _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);\nconst _16n = /* @__PURE__ */ BigInt(16);\n\n/**\n * @param a - Dividend value.\n * @param b - Positive modulus.\n * @returns Reduced value in `[0, b)` only when `b` is positive.\n * @throws If the modulus is not positive. {@link Error}\n * @example\n * Normalize a bigint into one field residue.\n *\n * ```ts\n * mod(-1n, 5n);\n * ```\n */\nexport function mod(a: bigint, b: bigint): bigint {\n  if (b <= _0n) throw new Error('mod: expected positive modulus, got ' + b);\n  const result = a % b;\n  return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to a power with modular reduction.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * Low-level helper: callers that need canonical residues must pass a valid `num` for the chosen\n * modulus instead of relying on the `power===0/1` fast paths to normalize it.\n * @param num - Base value.\n * @param power - Exponent value.\n * @param modulo - Reduction modulus.\n * @returns Modular exponentiation result.\n * @throws If the modulus or exponent is invalid. {@link Error}\n * @example\n * Raise one bigint to a modular power.\n *\n * ```ts\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n * ```\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n  return FpPow(Field(modulo), num, power);\n}\n\n/**\n * Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`.\n * Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen\n * modulus; the `power===0` fast path intentionally returns the input unchanged.\n * @param x - Base value.\n * @param power - Number of squarings.\n * @param modulo - Reduction modulus.\n * @returns Repeated-squaring result.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Apply repeated squaring inside one field.\n *\n * ```ts\n * pow2(3n, 2n, 11n);\n * ```\n */\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n  if (power < _0n) throw new Error('pow2: expected non-negative exponent, got ' + power);\n  let res = x;\n  while (power-- > _0n) {\n    res *= res;\n    res %= modulo;\n  }\n  return res;\n}\n\n/**\n * Inverses number over modulo.\n * Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}.\n * @param number - Value to invert.\n * @param modulo - Positive modulus.\n * @returns Multiplicative inverse.\n * @throws If the modulus is invalid or the inverse does not exist. {@link Error}\n * @example\n * Compute one modular inverse with the extended Euclidean algorithm.\n *\n * ```ts\n * invert(3n, 11n);\n * ```\n */\nexport function invert(number: bigint, modulo: bigint): bigint {\n  if (number === _0n) throw new Error('invert: expected non-zero number');\n  if (modulo <= _0n) throw new Error('invert: expected positive modulus, got ' + modulo);\n  // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n  let a = mod(number, modulo);\n  let b = modulo;\n  // prettier-ignore\n  let x = _0n, y = _1n, u = _1n, v = _0n;\n  while (a !== _0n) {\n    const q = b / a;\n    const r = b - a * q;\n    const m = x - u * q;\n    const n = y - v * q;\n    // prettier-ignore\n    b = a, a = r, x = u, y = v, u = m, v = n;\n  }\n  const gcd = b;\n  if (gcd !== _1n) throw new Error('invert: does not exist');\n  return mod(x, modulo);\n}\n\nfunction assertIsSquare<T>(Fp: TArg<IField<T>>, root: T, n: T): void {\n  const F = Fp as IField<T>;\n  if (!F.eql(F.sqr(root), n)) throw new Error('Cannot find square root');\n}\n\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4<T>(Fp: TArg<IField<T>>, n: T) {\n  const F = Fp as IField<T>;\n  const p1div4 = (F.ORDER + _1n) / _4n;\n  const root = F.pow(n, p1div4);\n  assertIsSquare(F, root, n);\n  return root;\n}\n\n// Equivalent `q = 5 (mod 8)` square-root formula (Atkin-style), not the RFC Appendix I.2 CMOV\n// pseudocode verbatim.\nfunction sqrt5mod8<T>(Fp: TArg<IField<T>>, n: T) {\n  const F = Fp as IField<T>;\n  const p5div8 = (F.ORDER - _5n) / _8n;\n  const n2 = F.mul(n, _2n);\n  const v = F.pow(n2, p5div8);\n  const nv = F.mul(n, v);\n  const i = F.mul(F.mul(nv, _2n), v);\n  const root = F.mul(nv, F.sub(i, F.ONE));\n  assertIsSquare(F, root, n);\n  return root;\n}\n\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P: bigint): TRet<<T>(Fp: IField<T>, n: T) => T> {\n  const Fp_ = Field(P);\n  const tn = tonelliShanks(P);\n  const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));//  1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n  const c2 = tn(Fp_, c1);              //  2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n  const c3 = tn(Fp_, Fp_.neg(c1));     //  3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n  const c4 = (P + _7n) / _16n;         //  4. c4 = (q + 7) / 16        # Integer arithmetic\n  return (<T>(Fp: TArg<IField<T>>, n: T): T => {\n    const F = Fp as IField<T>;\n    let tv1 = F.pow(n, c4);            //  1. tv1 = x^c4\n    let tv2 = F.mul(tv1, c1);          //  2. tv2 = c1 * tv1\n    const tv3 = F.mul(tv1, c2);        //  3. tv3 = c2 * tv1\n    const tv4 = F.mul(tv1, c3);        //  4. tv4 = c3 * tv1\n    const e1 = F.eql(F.sqr(tv2), n);   //  5.  e1 = (tv2^2) == x\n    const e2 = F.eql(F.sqr(tv3), n);   //  6.  e2 = (tv3^2) == x\n    tv1 = F.cmov(tv1, tv2, e1);        //  7. tv1 = CMOV(tv1, tv2, e1)  # Select tv2 if (tv2^2) == x\n    tv2 = F.cmov(tv4, tv3, e2);        //  8. tv2 = CMOV(tv4, tv3, e2)  # Select tv3 if (tv3^2) == x\n    const e3 = F.eql(F.sqr(tv2), n);   //  9.  e3 = (tv2^2) == x\n    const root = F.cmov(tv1, tv2, e3); // 10.  z = CMOV(tv1, tv2, e3)   # Select sqrt from tv1 & tv2\n    assertIsSquare(F, root, n);\n    return root;\n  }) as TRet<<T>(Fp: IField<T>, n: T) => T>;\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * This implementation is variable-time: it searches data-dependently for the first non-residue `Z`\n * and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape.\n * 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P - field order\n * @returns function that takes field Fp (created from P) and number n\n * @throws If the field is too small, non-prime, or the square root does not exist. {@link Error}\n * @example\n * Construct a square-root helper for primes that need Tonelli-Shanks.\n *\n * ```ts\n * import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = tonelliShanks(17n)(Fp, 4n);\n * ```\n */\nexport function tonelliShanks(P: bigint): TRet<<T>(Fp: IField<T>, n: T) => T> {\n  // Initialization (precomputation).\n  // Caching initialization could boost perf by 7%.\n  if (P < _3n) throw new Error('sqrt is not defined for small field');\n  // Factor P - 1 = Q * 2^S, where Q is odd\n  let Q = P - _1n;\n  let S = 0;\n  while (Q % _2n === _0n) {\n    Q /= _2n;\n    S++;\n  }\n\n  // Find the first quadratic non-residue Z >= 2\n  let Z = _2n;\n  const _Fp = Field(P);\n  while (FpLegendre(_Fp, Z) === 1) {\n    // Basic primality test for P. After x iterations, chance of\n    // not finding quadratic non-residue is 2^x, so 2^1000.\n    if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n  }\n  // Fast-path; usually done before Z, but we do \"primality test\".\n  if (S === 1) return sqrt3mod4 as TRet<<T>(Fp: IField<T>, n: T) => T>;\n\n  // Slow-path\n  // TODO: test on Fp2 and others\n  let cc = _Fp.pow(Z, Q); // c = z^Q\n  const Q1div2 = (Q + _1n) / _2n;\n  return function tonelliSlow<T>(Fp: TArg<IField<T>>, n: T): T {\n    const F = Fp as IField<T>;\n    if (F.is0(n)) return n;\n    // Check if n is a quadratic residue using Legendre symbol\n    if (FpLegendre(F, n) !== 1) throw new Error('Cannot find square root');\n\n    // Initialize variables for the main loop\n    let M = S;\n    let c = F.mul(F.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n    let t = F.pow(n, Q); // t = n^Q, first guess at the fudge factor\n    let R = F.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n    // Main loop\n    // while t != 1\n    while (!F.eql(t, F.ONE)) {\n      if (F.is0(t)) return F.ZERO; // if t=0 return R=0\n      let i = 1;\n\n      // Find the smallest i >= 1 such that t^(2^i) \u2261 1 (mod P)\n      let t_tmp = F.sqr(t); // t^(2^1)\n      while (!F.eql(t_tmp, F.ONE)) {\n        i++;\n        t_tmp = F.sqr(t_tmp); // t^(2^2)...\n        if (i === M) throw new Error('Cannot find square root');\n      }\n\n      // Calculate the exponent for b: 2^(M - i - 1)\n      const exponent = _1n << BigInt(M - i - 1); // bigint is important\n      const b = F.pow(c, exponent); // b = 2^(M - i - 1)\n\n      // Update variables\n      M = i;\n      c = F.sqr(b); // c = b^2\n      t = F.mul(t, c); // t = (t * b^2)\n      R = F.mul(R, b); // R = R*b\n    }\n    return R;\n  } as TRet<<T>(Fp: IField<T>, n: T) => T>;\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P \u2261 3 (mod 4)\n * 2. P \u2261 5 (mod 8)\n * 3. P \u2261 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choose a root by oddness\n * (used for hash-to-curve).\n * @param P - Field order.\n * @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time\n *   behavior and this selector assumes prime-field-style integer moduli.\n * @throws If the field is unsupported or the square root does not exist. {@link Error}\n * @example\n * Choose the square-root helper appropriate for one field modulus.\n *\n * ```ts\n * import { Field, FpSqrt } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = FpSqrt(17n)(Fp, 4n);\n * ```\n */\nexport function FpSqrt(P: bigint): TRet<<T>(Fp: IField<T>, n: T) => T> {\n  // P \u2261 3 (mod 4) => \u221An = n^((P+1)/4)\n  if (P % _4n === _3n) return sqrt3mod4 as TRet<<T>(Fp: IField<T>, n: T) => T>;\n  // P \u2261 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n  if (P % _8n === _5n) return sqrt5mod8 as TRet<<T>(Fp: IField<T>, n: T) => T>;\n  // P \u2261 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n  if (P % _16n === _9n) return sqrt9mod16(P);\n  // Tonelli-Shanks algorithm\n  return tonelliShanks(P);\n}\n\n/**\n * @param num - Value to inspect.\n * @param modulo - Field modulus.\n * @returns `true` when the least-significant little-endian bit is set.\n * @throws If the modulus is invalid for `mod(...)`. {@link Error}\n * @example\n * Inspect the low bit used by little-endian sign conventions.\n *\n * ```ts\n * isNegativeLE(3n, 11n);\n * ```\n */\nexport const isNegativeLE = (num: bigint, modulo: bigint): boolean =>\n  (mod(num, modulo) & _1n) === _1n;\n\n/** Generic field interface used by prime and extension fields alike.\n * Generic helpers treat field operations as pure functions: implementations MUST treat provided\n * values/byte buffers as read-only and return detached results instead of mutating arguments.\n */\nexport interface IField<T> {\n  /** Field order `q`, which may be prime or a prime power. */\n  ORDER: bigint;\n  /** Canonical encoded byte length. */\n  BYTES: number;\n  /** Canonical encoded bit length. */\n  BITS: number;\n  /** Whether encoded field elements use little-endian bytes. */\n  isLE: boolean;\n  /** Additive identity. */\n  ZERO: T;\n  /** Multiplicative identity. */\n  ONE: T;\n  // 1-arg\n  /**\n   * Normalize one value into the field.\n   * @param num - Input value.\n   * @returns Normalized field value.\n   */\n  create: (num: T) => T;\n  /**\n   * Check whether one value already belongs to the field.\n   * @param num - Input value.\n   * Implementations may throw `TypeError` on malformed input types instead of returning `false`.\n   * @returns Whether the value already belongs to the field.\n   */\n  isValid: (num: T) => boolean;\n  /**\n   * Check whether one value is zero.\n   * @param num - Input value.\n   * @returns Whether the value is zero.\n   */\n  is0: (num: T) => boolean;\n  /**\n   * Check whether one value is non-zero and belongs to the field.\n   * @param num - Input value.\n   * Implementations may throw `TypeError` on malformed input types instead of returning `false`.\n   * @returns Whether the value is non-zero and valid.\n   */\n  isValidNot0: (num: T) => boolean;\n  /**\n   * Negate one value.\n   * @param num - Input value.\n   * @returns Negated value.\n   */\n  neg(num: T): T;\n  /**\n   * Invert one value multiplicatively.\n   * @param num - Input value.\n   * @returns Multiplicative inverse.\n   */\n  inv(num: T): T;\n  /**\n   * Compute one square root when it exists.\n   * @param num - Input value.\n   * @returns Square root.\n   */\n  sqrt(num: T): T;\n  /**\n   * Square one value.\n   * @param num - Input value.\n   * @returns Squared value.\n   */\n  sqr(num: T): T;\n  // 2-args\n  /**\n   * Compare two field values.\n   * @param lhs - Left value.\n   * @param rhs - Right value.\n   * @returns Whether both values are equal.\n   */\n  eql(lhs: T, rhs: T): boolean;\n  /**\n   * Add two normalized field values.\n   * @param lhs - Left value.\n   * @param rhs - Right value.\n   * @returns Sum value.\n   */\n  add(lhs: T, rhs: T): T;\n  /**\n   * Subtract two normalized field values.\n   * @param lhs - Left value.\n   * @param rhs - Right value.\n   * @returns Difference value.\n   */\n  sub(lhs: T, rhs: T): T;\n  /**\n   * Multiply two field values.\n   * @param lhs - Left value.\n   * @param rhs - Right value or scalar.\n   * @returns Product value.\n   */\n  mul(lhs: T, rhs: T | bigint): T;\n  /**\n   * Raise one field value to a power.\n   * @param lhs - Base value.\n   * @param power - Exponent.\n   * @returns Power value.\n   */\n  pow(lhs: T, power: bigint): T;\n  /**\n   * Divide one field value by another.\n   * @param lhs - Dividend.\n   * @param rhs - Divisor or scalar.\n   * @returns Quotient value.\n   */\n  div(lhs: T, rhs: T | bigint): T;\n  // N for NonNormalized (for now)\n  /**\n   * Add two values without re-normalizing the result.\n   * @param lhs - Left value.\n   * @param rhs - Right value.\n   * @returns Non-normalized sum.\n   */\n  addN(lhs: T, rhs: T): T;\n  /**\n   * Subtract two values without re-normalizing the result.\n   * @param lhs - Left value.\n   * @param rhs - Right value.\n   * @returns Non-normalized difference.\n   */\n  subN(lhs: T, rhs: T): T;\n  /**\n   * Multiply two values without re-normalizing the result.\n   * @param lhs - Left value.\n   * @param rhs - Right value or scalar.\n   * @returns Non-normalized product.\n   */\n  mulN(lhs: T, rhs: T | bigint): T;\n  /**\n   * Square one value without re-normalizing the result.\n   * @param num - Input value.\n   * @returns Non-normalized square.\n   */\n  sqrN(num: T): T;\n\n  // Optional\n  // Should be same as sgn0 function in\n  // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n  // NOTE: sgn0 is \"negative in LE\", which is the same as odd.\n  // Negative in LE is a somewhat strange definition anyway.\n  /**\n   * Return the RFC 9380 `sgn0`-style oddness bit when supported.\n   * This uses oddness instead of evenness so extension fields like Fp2 can expose the same hook.\n   * Returns whether the value is odd under the field encoding.\n   */\n  isOdd?(num: T): boolean;\n  // legendre?(num: T): T;\n  /**\n   * Invert many field elements in one batch.\n   * @param lst - Values to invert.\n   * @returns Batch of inverses.\n   */\n  invertBatch: (lst: T[]) => T[];\n  /**\n   * Encode one field value into fixed-width bytes.\n   * Callers that need canonical encodings MUST supply a valid field element.\n   * Low-level protocols may also use this to serialize raw / non-canonical residues.\n   * @param num - Input value.\n   * @returns Fixed-width byte encoding.\n   */\n  toBytes(num: T): Uint8Array;\n  /**\n   * Decode one field value from fixed-width bytes.\n   * @param bytes - Fixed-width byte encoding.\n   * @param skipValidation - Whether to skip range validation.\n   * Implementations MUST treat `bytes` as read-only.\n   * @returns Decoded field value.\n   */\n  fromBytes(bytes: Uint8Array, skipValidation?: boolean): T;\n  // If c is False, CMOV returns a, otherwise it returns b.\n  /**\n   * Constant-time conditional move.\n   * @param a - Value used when the condition is false.\n   * @param b - Value used when the condition is true.\n   * @param c - Selection bit.\n   * @returns Selected value.\n   */\n  cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\n// Arithmetic-only subset checked by validateField(). This is intentionally not the full runtime\n// IField contract: helpers like `isValidNot0`, `invertBatch`, `toBytes`, `fromBytes`, `cmov`, and\n// field-specific extras like `isOdd` are left to the callers that actually need them.\nconst FIELD_FIELDS = [\n  'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n  'eql', 'add', 'sub', 'mul', 'pow', 'div',\n  'addN', 'subN', 'mulN', 'sqrN'\n] as const;\n/**\n * @param field - Field implementation.\n * @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it\n *   does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or\n *   field-specific extras beyond positive `BYTES` / `BITS`.\n * @throws If the field shape or numeric metadata are invalid. {@link Error}\n * @example\n * Check that a field implementation exposes the operations curve code expects.\n *\n * ```ts\n * import { Field, validateField } from '@noble/curves/abstract/modular.js';\n * const Fp = validateField(Field(17n));\n * ```\n */\nexport function validateField<T>(field: TArg<IField<T>>): TRet<IField<T>> {\n  const initial = {\n    ORDER: 'bigint',\n    BYTES: 'number',\n    BITS: 'number',\n  } as Record<string, string>;\n  const opts = FIELD_FIELDS.reduce((map, val: string) => {\n    map[val] = 'function';\n    return map;\n  }, initial);\n  validateObject(field, opts);\n  // Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN /\n  // infinite metadata leaks through validateObject(type='number') but breaks encoders and caches.\n  asafenumber(field.BYTES, 'BYTES');\n  asafenumber(field.BITS, 'BITS');\n  // Runtime field implementations must expose positive byte/bit sizes; zero leaks through the\n  // numeric shape checks above but still breaks encoding helpers and cached-length assumptions.\n  if (field.BYTES < 1 || field.BITS < 1) throw new Error('invalid field: expected BYTES/BITS > 0');\n  if (field.ORDER <= _1n) throw new Error('invalid field: expected ORDER > 1, got ' + field.ORDER);\n  return field as TRet<IField<T>>;\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @param Fp - Field implementation.\n * @param num - Base value.\n * @param power - Exponent value.\n * @returns Powered field element.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Raise one field element to a public exponent.\n *\n * ```ts\n * import { Field, FpPow } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpPow(Fp, 3n, 5n);\n * ```\n */\nexport function FpPow<T>(Fp: TArg<IField<T>>, num: T, power: bigint): T {\n  const F = Fp as IField<T>;\n  if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n  if (power === _0n) return F.ONE;\n  if (power === _1n) return num;\n  let p = F.ONE;\n  let d = num;\n  while (power > _0n) {\n    if (power & _1n) p = F.mul(p, d);\n    d = F.sqr(d);\n    power >>= _1n;\n  }\n  return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Zero-valued field elements stay `undefined` unless `passZero` is enabled.\n * @param Fp - Field implementation.\n * @param nums - Values to invert.\n * @param passZero - map 0 to 0 (instead of undefined)\n * @returns Inverted values.\n * @example\n * Invert several field elements with one shared inversion.\n *\n * ```ts\n * import { Field, FpInvertBatch } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const inv = FpInvertBatch(Fp, [1n, 2n, 4n]);\n * ```\n */\nexport function FpInvertBatch<T>(Fp: TArg<IField<T>>, nums: T[], passZero = false): T[] {\n  const F = Fp as IField<T>;\n  const inverted = new Array(nums.length).fill(passZero ? F.ZERO : undefined) as T[];\n  // Walk from first to last, multiply them by each other MOD p\n  const multipliedAcc = nums.reduce((acc, num, i) => {\n    if (F.is0(num)) return acc;\n    inverted[i] = acc;\n    return F.mul(acc, num);\n  }, F.ONE);\n  // Invert last element\n  const invertedAcc = F.inv(multipliedAcc);\n  // Walk from last to first, multiply them by inverted each other MOD p\n  nums.reduceRight((acc, num, i) => {\n    if (F.is0(num)) return acc;\n    inverted[i] = F.mul(acc, inverted[i]);\n    return F.mul(acc, num);\n  }, invertedAcc);\n  return inverted;\n}\n\n/**\n * @param Fp - Field implementation.\n * @param lhs - Dividend value.\n * @param rhs - Divisor value.\n * @returns Division result.\n * @throws If the divisor is non-invertible. {@link Error}\n * @example\n * Divide one field element by another.\n *\n * ```ts\n * import { Field, FpDiv } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpDiv(Fp, 6n, 3n);\n * ```\n */\nexport function FpDiv<T>(Fp: TArg<IField<T>>, lhs: T, rhs: T | bigint): T {\n  const F = Fp as IField<T>;\n  return F.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, F.ORDER) : F.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) \u2261 1    if a is a square (mod p), quadratic residue\n * * (a | p) \u2261 -1   if a is not a square (mod p), quadratic non residue\n * * (a | p) \u2261 0    if a \u2261 0 (mod p)\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns Legendre symbol.\n * @throws If the field returns an invalid Legendre symbol value. {@link Error}\n * @example\n * Compute the Legendre symbol of one field element.\n *\n * ```ts\n * import { Field, FpLegendre } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const symbol = FpLegendre(Fp, 4n);\n * ```\n */\nexport function FpLegendre<T>(Fp: TArg<IField<T>>, n: T): -1 | 0 | 1 {\n  const F = Fp as IField<T>;\n  // We can use 3rd argument as optional cache of this value\n  // but seems unneeded for now. The operation is very fast.\n  const p1mod2 = (F.ORDER - _1n) / _2n;\n  const powered = F.pow(n, p1mod2);\n  const yes = F.eql(powered, F.ONE);\n  const zero = F.eql(powered, F.ZERO);\n  const no = F.eql(powered, F.neg(F.ONE));\n  if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n  return yes ? 1 : zero ? 0 : -1;\n}\n\n/**\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns `true` when `Fp.sqrt(n)` exists. This includes `0`, even though strict \"quadratic\n *   residue\" terminology often reserves that name for the non-zero square class.\n * @throws If the field returns an invalid Legendre symbol value. {@link Error}\n * @example\n * Check whether one field element has a square root in the field.\n *\n * ```ts\n * import { Field, FpIsSquare } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const isSquare = FpIsSquare(Fp, 4n);\n * ```\n */\nexport function FpIsSquare<T>(Fp: TArg<IField<T>>, n: T): boolean {\n  const l = FpLegendre(Fp as IField<T>, n);\n  // Zero is a square too: 0 = 0^2, and Fp.sqrt(0) already returns 0.\n  return l !== -1;\n}\n\n/** Byte and bit lengths derived from one scalar order. */\nexport type NLength = {\n  /** Canonical byte length. */\n  nByteLength: number;\n  /** Canonical bit length. */\n  nBitLength: number;\n};\n/**\n * @param n - Curve order. Callers are expected to pass a positive order.\n * @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached\n *   value when overriding the derived bit length.\n * @returns Byte and bit lengths.\n * @throws If the order or cached bit length is invalid. {@link Error}\n * @example\n * Measure the encoding sizes needed for one modulus.\n *\n * ```ts\n * nLength(255n);\n * ```\n */\nexport function nLength(n: bigint, nBitLength?: number): NLength {\n  // Bit size, byte size of CURVE.n\n  if (nBitLength !== undefined) anumber(nBitLength);\n  if (n <= _0n) throw new Error('invalid n length: expected positive n, got ' + n);\n  if (nBitLength !== undefined && nBitLength < 1)\n    throw new Error('invalid n length: expected positive bit length, got ' + nBitLength);\n  const bits = bitLen(n);\n  // Cached bit lengths smaller than ORDER would truncate serialized scalars/elements and poison\n  // any math that relies on the derived field metadata.\n  if (nBitLength !== undefined && nBitLength < bits)\n    throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);\n  const _nBitLength = nBitLength !== undefined ? nBitLength : bits;\n  const nByteLength = Math.ceil(_nBitLength / 8);\n  return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;\ntype SqrtFn = (n: bigint) => bigint;\ntype FieldOpts = Partial<{\n  isLE: boolean;\n  BITS: number;\n  sqrt: SqrtFn;\n  allowedLengths?: readonly number[]; // for P521 (adds padding for smaller sizes); must stay > 0\n  modFromBytes: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n}>;\n// Keep the lazy sqrt cache off-instance so Field(...) can return a frozen object. Otherwise the\n// cached helper write would keep the field surface externally mutable.\nconst FIELD_SQRT = new WeakMap<object, ReturnType<typeof FpSqrt>>();\nclass _Field implements IField<bigint> {\n  readonly ORDER: bigint;\n  readonly BITS: number;\n  readonly BYTES: number;\n  readonly isLE: boolean;\n  readonly ZERO = _0n;\n  readonly ONE = _1n;\n  readonly _lengths?: readonly number[];\n  private readonly _mod?: boolean;\n  constructor(ORDER: bigint, opts: FieldOpts = {}) {\n    // ORDER <= 1 is degenerate: ONE would not be a valid field element and helpers like pow/inv\n    // would stop modeling field arithmetic.\n    if (ORDER <= _1n) throw new Error('invalid field: expected ORDER > 1, got ' + ORDER);\n    let _nbitLength: number | undefined = undefined;\n    this.isLE = false;\n    if (opts != null && typeof opts === 'object') {\n      // Cached bit lengths are trusted here and should already be positive / consistent with ORDER.\n      if (typeof opts.BITS === 'number') _nbitLength = opts.BITS;\n      if (typeof opts.sqrt === 'function')\n        // `_Field.prototype` is frozen below, so custom sqrt hooks must become own properties\n        // explicitly instead of relying on writable prototype shadowing via assignment.\n        Object.defineProperty(this, 'sqrt', { value: opts.sqrt, enumerable: true });\n      if (typeof opts.isLE === 'boolean') this.isLE = opts.isLE;\n      if (opts.allowedLengths) this._lengths = Object.freeze(opts.allowedLengths.slice());\n      if (typeof opts.modFromBytes === 'boolean') this._mod = opts.modFromBytes;\n    }\n    const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n    if (nByteLength > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n    this.ORDER = ORDER;\n    this.BITS = nBitLength;\n    this.BYTES = nByteLength;\n    Object.freeze(this);\n  }\n\n  create(num: bigint) {\n    return mod(num, this.ORDER);\n  }\n  isValid(num: bigint) {\n    if (typeof num !== 'bigint')\n      throw new TypeError('invalid field element: expected bigint, got ' + typeof num);\n    return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible\n  }\n  is0(num: bigint) {\n    return num === _0n;\n  }\n  // is valid and invertible\n  isValidNot0(num: bigint) {\n    return !this.is0(num) && this.isValid(num);\n  }\n  isOdd(num: bigint) {\n    return (num & _1n) === _1n;\n  }\n  neg(num: bigint) {\n    return mod(-num, this.ORDER);\n  }\n  eql(lhs: bigint, rhs: bigint) {\n    return lhs === rhs;\n  }\n\n  sqr(num: bigint) {\n    return mod(num * num, this.ORDER);\n  }\n  add(lhs: bigint, rhs: bigint) {\n    return mod(lhs + rhs, this.ORDER);\n  }\n  sub(lhs: bigint, rhs: bigint) {\n    return mod(lhs - rhs, this.ORDER);\n  }\n  mul(lhs: bigint, rhs: bigint) {\n    return mod(lhs * rhs, this.ORDER);\n  }\n  pow(num: bigint, power: bigint): bigint {\n    return FpPow(this, num, power);\n  }\n  div(lhs: bigint, rhs: bigint) {\n    return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n  }\n\n  // Same as above, but doesn't normalize\n  sqrN(num: bigint) {\n    return num * num;\n  }\n  addN(lhs: bigint, rhs: bigint) {\n    return lhs + rhs;\n  }\n  subN(lhs: bigint, rhs: bigint) {\n    return lhs - rhs;\n  }\n  mulN(lhs: bigint, rhs: bigint) {\n    return lhs * rhs;\n  }\n\n  inv(num: bigint) {\n    return invert(num, this.ORDER);\n  }\n  sqrt(num: bigint): bigint {\n    // Caching sqrt helpers speeds up sqrt9mod16 by 5x and Tonelli-Shanks by about 10% without keeping\n    // the field instance itself mutable.\n    let sqrt = FIELD_SQRT.get(this);\n    if (!sqrt) FIELD_SQRT.set(this, (sqrt = FpSqrt(this.ORDER)));\n    return sqrt(this, num);\n  }\n  toBytes(num: bigint) {\n    // Serialize fixed-width limbs without re-validating the field range. Callers that need a\n    // canonical encoding must pass a valid element; some protocols intentionally serialize raw\n    // residues here and reduce or validate them elsewhere.\n    return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);\n  }\n  fromBytes(bytes: Uint8Array, skipValidation = false) {\n    abytes(bytes);\n    const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;\n    if (allowedLengths) {\n      // `allowedLengths` must list real positive byte lengths; otherwise empty input would get\n      // padded into zero and silently decode as a field element.\n      if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n        throw new Error(\n          'Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length\n        );\n      }\n      const padded = new Uint8Array(BYTES);\n      // isLE add 0 to right, !isLE to the left.\n      padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n      bytes = padded;\n    }\n    if (bytes.length !== BYTES)\n      throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n    let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n    if (modFromBytes) scalar = mod(scalar, ORDER);\n    if (!skipValidation)\n      if (!this.isValid(scalar))\n        throw new Error('invalid field element: outside of range 0..ORDER');\n    // Range validation is optional here because some protocols intentionally decode raw residues\n    // and reduce or validate them elsewhere.\n    return scalar;\n  }\n  // TODO: we don't need it here, move out to separate fn\n  invertBatch(lst: bigint[]): bigint[] {\n    return FpInvertBatch(this, lst);\n  }\n  // We can't move this out because Fp6, Fp12 implement it\n  // and it's unclear what to return in there.\n  cmov(a: bigint, b: bigint, condition: boolean) {\n    // Field elements have `isValid(...)`; the CMOV branch bit is a direct runtime input, so reject\n    // non-boolean selectors here instead of letting JS truthiness silently change arithmetic.\n    abool(condition, 'condition');\n    return condition ? b : a;\n  }\n}\n// Freeze the shared method surface too; otherwise callers can still poison every Field instance by\n// monkey-patching `_Field.prototype` even if each instance is frozen.\nObject.freeze(_Field.prototype);\n\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations and low-level serializers like `toBytes` don't check `isValid` for\n * all elements for performance and protocol-flexibility reasons; callers are responsible for\n * supplying valid elements when they need canonical field behavior.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER - field order, probably prime, or could be composite\n * @param opts - Field options such as bit length or endianness. See {@link FieldOpts}.\n * @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight\n *   into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`.\n * @example\n * Construct one prime field with optional overrides.\n *\n * ```ts\n * Field(11n);\n * ```\n */\nexport function Field(ORDER: bigint, opts: FieldOpts = {}): TRet<Readonly<FpField>> {\n  return new _Field(ORDER, opts);\n}\n\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n//   const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n//   if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n//   const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n//   // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n//   const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n//   return reduced;\n// },\n\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Odd square root when two roots exist. The special case `elm = 0` still returns `0`,\n *   which is the only square root but is not odd.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the odd square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtOdd } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtOdd(Fp, 4n);\n * ```\n */\nexport function FpSqrtOdd<T>(Fp: TArg<IField<T>>, elm: T): T {\n  const F = Fp as IField<T>;\n  if (!F.isOdd) throw new Error(\"Field doesn't have isOdd\");\n  const root = F.sqrt(elm);\n  return F.isOdd(root) ? root : F.neg(root);\n}\n\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Even square root.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the even square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtEven } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtEven(Fp, 4n);\n * ```\n */\nexport function FpSqrtEven<T>(Fp: TArg<IField<T>>, elm: T): T {\n  const F = Fp as IField<T>;\n  if (!F.isOdd) throw new Error(\"Field doesn't have isOdd\");\n  const root = F.sqrt(elm);\n  return F.isOdd(root) ? F.neg(root) : root;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder - number of field elements, usually CURVE.n. Callers are expected to pass an\n *   order greater than 1.\n * @returns byte length of field\n * @throws If the field order is not a bigint. {@link Error}\n * @example\n * Read the fixed-width byte length of one field.\n *\n * ```ts\n * getFieldBytesLength(255n);\n * ```\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n  if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n  // Valid field elements are in 0..ORDER-1, so ORDER <= 1 would make the encoded range degenerate.\n  if (fieldOrder <= _1n) throw new Error('field order must be greater than 1');\n  // Valid field elements are < ORDER, so the maximal encoded element is ORDER - 1.\n  const bitLength = bitLen(fieldOrder - _1n);\n  return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger\n * absolute floor for policy reasons.\n * @param fieldOrder - number of field elements greater than 1, usually CURVE.n.\n * @returns byte length of target hash\n * @throws If the field order is invalid. {@link Error}\n * @example\n * Compute the minimum hash length needed for field reduction.\n *\n * ```ts\n * getMinHashLength(255n);\n * ```\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n  const length = getFieldBytesLength(fieldOrder);\n  return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key. The implementation also keeps a hard\n * 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look\n * accidentally acceptable for real scalar derivation.\n * See {@link https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ | Kudelski's modulo-bias guide},\n * {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and\n * {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380\n * `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`.\n * @param key - Uniform input bytes.\n * @param fieldOrder - Size of subgroup.\n * @param isLE - interpret hash bytes as LE num\n * @returns valid private scalar\n * @throws If the hash length or field order is invalid for scalar reduction. {@link Error}\n * @example\n * Map hash output into a private scalar range.\n *\n * ```ts\n * mapHashToField(new Uint8Array(48).fill(1), 255n);\n * ```\n */\nexport function mapHashToField(\n  key: TArg<Uint8Array>,\n  fieldOrder: bigint,\n  isLE = false\n): TRet<Uint8Array> {\n  abytes(key);\n  const len = key.length;\n  const fieldLen = getFieldBytesLength(fieldOrder);\n  const minLen = Math.max(getMinHashLength(fieldOrder), 16);\n  // No toy-small inputs: the helper is for real scalar derivation, not tiny test curves. No huge\n  // inputs: easier to reason about JS timing / allocation behavior.\n  if (len < minLen || len > 1024)\n    throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n  const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n  // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n  const reduced = mod(num, fieldOrder - _1n) + _1n;\n  return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n", "/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, validateObject, type Signer, type TArg, type TRet } from '../utils.ts';\nimport { Field, FpInvertBatch, validateField, type IField } from './modular.ts';\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\n/** Affine point coordinates without projective fields. */\nexport type AffinePoint<T> = {\n  /** Affine x coordinate. */\n  x: T;\n  /** Affine y coordinate. */\n  y: T;\n} & { Z?: never };\n\n// We can't \"abstract out\" coordinates (X, Y, Z; and T in Edwards): argument names of constructor\n// are not accessible. See Typescript gh-56093, gh-41594.\n//\n// We have to use recursive types, so it will return actual point, not constained `CurvePoint`.\n// If, at any point, P is `any`, it will erase all types and replace it\n// with `any`, because of recursion, `any implements CurvePoint`,\n// but we lose all constrains on methods.\n\n/** Base interface for all elliptic-curve point instances. */\nexport interface CurvePoint<F, P extends CurvePoint<F, P>> {\n  /** Affine x coordinate. Different from projective / extended X coordinate. */\n  x: F;\n  /** Affine y coordinate. Different from projective / extended Y coordinate. */\n  y: F;\n  /** Projective Z coordinate when the point keeps projective state. */\n  Z?: F;\n  /**\n   * Double the point.\n   * @returns Doubled point.\n   */\n  double(): P;\n  /**\n   * Negate the point.\n   * @returns Negated point.\n   */\n  negate(): P;\n  /**\n   * Add another point from the same curve.\n   * @param other - Point to add.\n   * @returns Sum point.\n   */\n  add(other: P): P;\n  /**\n   * Subtract another point from the same curve.\n   * @param other - Point to subtract.\n   * @returns Difference point.\n   */\n  subtract(other: P): P;\n  /**\n   * Compare two points for equality.\n   * @param other - Point to compare.\n   * @returns Whether the points are equal.\n   */\n  equals(other: P): boolean;\n  /**\n   * Multiply the point by a scalar in constant time.\n   * Implementations keep the subgroup-scalar contract strict and may reject\n   * `0` instead of returning the identity point.\n   * @param scalar - Scalar multiplier.\n   * @returns Product point.\n   */\n  multiply(scalar: bigint): P;\n  /** Assert that the point satisfies the curve equation and subgroup checks. */\n  assertValidity(): void;\n  /**\n   * Map the point into the prime-order subgroup when the curve requires it.\n   * @returns Prime-order point.\n   */\n  clearCofactor(): P;\n  /**\n   * Check whether the point is the point at infinity.\n   * @returns Whether the point is zero.\n   */\n  is0(): boolean;\n  /**\n   * Check whether the point belongs to the prime-order subgroup.\n   * @returns Whether the point is torsion-free.\n   */\n  isTorsionFree(): boolean;\n  /**\n   * Check whether the point lies in a small torsion subgroup.\n   * @returns Whether the point has small order.\n   */\n  isSmallOrder(): boolean;\n  /**\n   * Multiply the point by a scalar without constant-time guarantees.\n   * Public-scalar callers that need `0` should use this method instead of\n   * relying on `multiply(...)` to return the identity point.\n   * @param scalar - Scalar multiplier.\n   * @returns Product point.\n   */\n  multiplyUnsafe(scalar: bigint): P;\n  /**\n   * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}.\n   * Cache state lives in internal WeakMaps keyed by point identity, not on the point object.\n   * Repeating `precompute(...)` for the same point identity replaces the remembered window size\n   * and forces table regeneration for that point.\n   * @param windowSize - Precompute window size.\n   * @param isLazy - calculate cache now. Default (true) ensures it's deferred to first `multiply()`\n   * @returns Same point instance with precompute tables attached.\n   */\n  precompute(windowSize?: number, isLazy?: boolean): P;\n  /**\n   * Converts point to 2D xy affine coordinates.\n   * @param invertedZ - Optional inverted Z coordinate for batch normalization.\n   * @returns Affine x/y coordinates.\n   */\n  toAffine(invertedZ?: F): AffinePoint<F>;\n  /**\n   * Encode the point into the curve's canonical byte form.\n   * @returns Encoded point bytes.\n   */\n  toBytes(): Uint8Array;\n  /**\n   * Encode the point into the curve's canonical hex form.\n   * @returns Encoded point hex.\n   */\n  toHex(): string;\n}\n\n/** Base interface for elliptic-curve point constructors. */\nexport interface CurvePointCons<P extends CurvePoint<any, P>> {\n  /**\n   * Runtime brand check for points created by this constructor.\n   * @param item - Value to test.\n   * @returns Whether the value is a point from this constructor.\n   */\n  [Symbol.hasInstance]: (item: unknown) => boolean;\n  /** Canonical subgroup generator. */\n  BASE: P;\n  /** Point at infinity. */\n  ZERO: P;\n  /** Field for basic curve math */\n  Fp: IField<P_F<P>>;\n  /** Scalar field, for scalars in multiply and others */\n  Fn: IField<bigint>;\n  /**\n   * Create one point from affine coordinates.\n   * Does NOT validate curve, subgroup, or wrapper invariants.\n   * Use `.assertValidity()` on adversarial inputs.\n   * @param p - Affine point coordinates.\n   * @returns Point instance.\n   */\n  fromAffine(p: AffinePoint<P_F<P>>): P;\n  /**\n   * Decode a point from the canonical byte encoding.\n   * @param bytes - Encoded point bytes.\n   * Implementations MUST treat `bytes` as read-only.\n   * @returns Point instance.\n   */\n  fromBytes(bytes: Uint8Array): P;\n  /**\n   * Decode a point from the canonical hex encoding.\n   * @param hex - Encoded point hex.\n   * @returns Point instance.\n   */\n  fromHex(hex: string): P;\n}\n\n// Type inference helpers: PC - PointConstructor, P - Point, Fp - Field element\n// Short names, because we use them a lot in result types:\n// * we can't do 'P = GetCurvePoint<PC>': this is default value and doesn't constrain anything\n// * we can't do 'type X = GetCurvePoint<PC>': it won't be accesible for arguments/return types\n// * `CurvePointCons<P extends CurvePoint<any, P>>` constraints from interface definition\n//   won't propagate, if `PC extends CurvePointCons<any>`: the P would be 'any', which is incorrect\n// * PC could be super specific with super specific P, which implements CurvePoint<any, P>.\n//   this means we need to do stuff like\n//   `function test<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(`\n//   if we want type safety around P, otherwise PC_P<PC> will be any\n\n/** Returns the affine field type for a point instance (`P_F<P> == P.F`). */\nexport type P_F<P extends CurvePoint<any, P>> = P extends CurvePoint<infer F, P> ? F : never;\n/** Returns the affine field type for a point constructor (`PC_F<PC> == PC.P.F`). */\nexport type PC_F<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['Fp']['ZERO'];\n/** Returns the point instance type for a point constructor (`PC_P<PC> == PC.P`). */\nexport type PC_P<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['ZERO'];\n\n// Ugly hack to get proper type inference, because in typescript fails to infer resursively.\n// The hack allows to do up to 10 chained operations without applying type erasure.\n//\n// Types which won't work:\n// * `CurvePointCons<CurvePoint<any, any>>`, will return `any` after 1 operation\n// * `CurvePointCons<any>: WeierstrassPointCons<bigint> extends CurvePointCons<any> = false`\n// * `P extends CurvePoint, PC extends CurvePointCons<P>`\n//     * It can't infer P from PC alone\n//     * Too many relations between F, P & PC\n//     * It will infer P/F if `arg: CurvePointCons<F, P>`, but will fail if PC is generic\n//     * It will work correctly if there is an additional argument of type P\n//     * But generally, we don't want to parametrize `CurvePointCons` over `F`: it will complicate\n//       types, making them un-inferable\n// prettier-ignore\n/** Wide point-constructor type used when the concrete curve is not important. */\nexport type PC_ANY = CurvePointCons<\n  CurvePoint<any,\n  CurvePoint<any,\n  CurvePoint<any,\n  CurvePoint<any,\n  CurvePoint<any,\n  CurvePoint<any,\n  CurvePoint<any,\n  CurvePoint<any,\n  CurvePoint<any,\n  CurvePoint<any, any>\n  >>>>>>>>>\n>;\n\n/**\n * Validates the static surface of a point constructor.\n * This is only a cheap sanity check for the constructor hooks and fields consumed by generic\n * factories; it does not certify `BASE`/`ZERO` semantics or prove the curve implementation itself.\n * @param Point - Runtime point constructor.\n * @throws On missing constructor hooks or malformed field metadata. {@link TypeError}\n * @example\n * Check that one point constructor exposes the static hooks generic helpers need.\n *\n * ```ts\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * import { validatePointCons } from '@noble/curves/abstract/curve.js';\n * validatePointCons(ed25519.Point);\n * ```\n */\nexport function validatePointCons<P extends CurvePoint<any, P>>(Point: CurvePointCons<P>): void {\n  const pc = Point as unknown as CurvePointCons<any>;\n  if (typeof (pc as unknown) !== 'function') throw new TypeError('Point must be a constructor');\n  // validateObject only accepts plain objects, so copy the constructor statics into one bag first.\n  validateObject(\n    {\n      Fp: pc.Fp,\n      Fn: pc.Fn,\n      fromAffine: pc.fromAffine,\n      fromBytes: pc.fromBytes,\n      fromHex: pc.fromHex,\n    },\n    {\n      Fp: 'object',\n      Fn: 'object',\n      fromAffine: 'function',\n      fromBytes: 'function',\n      fromHex: 'function',\n    }\n  );\n  validateField(pc.Fp);\n  validateField(pc.Fn);\n}\n\n/** Byte lengths used by one curve implementation. */\nexport interface CurveLengths {\n  /** Secret-key length in bytes. */\n  secretKey?: number;\n  /** Compressed public-key length in bytes. */\n  publicKey?: number;\n  /** Uncompressed public-key length in bytes. */\n  publicKeyUncompressed?: number;\n  /** Whether public-key encodings include a format prefix byte. */\n  publicKeyHasPrefix?: boolean;\n  /** Signature length in bytes. */\n  signature?: number;\n  /** Seed length in bytes when the curve exposes deterministic keygen from seed. */\n  seed?: number;\n}\n\n/** Reorders or otherwise remaps a batch while preserving its element type. */\nexport type Mapper<T> = (i: T[]) => T[];\n\n/**\n * Computes both candidates first, but the final selection still branches on `condition`, so this\n * is not a strict constant-time CMOV primitive.\n * @param condition - Whether to negate the point.\n * @param item - Point-like value.\n * @returns Original or negated value.\n * @example\n * Keep the point or return its negation based on one boolean branch.\n *\n * ```ts\n * import { negateCt } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const maybeNegated = negateCt(true, p256.Point.BASE);\n * ```\n */\nexport function negateCt<T extends { negate: () => T }>(condition: boolean, item: T): T {\n  const neg = item.negate();\n  return condition ? neg : item;\n}\n\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n * Input points are left unchanged; the normalized points are returned as fresh instances.\n * @param c - Point constructor.\n * @param points - Projective points.\n * @returns Fresh projective points reconstructed from normalized affine coordinates.\n * @example\n * Batch-normalize projective points with a single shared inversion.\n *\n * ```ts\n * import { normalizeZ } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]);\n * ```\n */\nexport function normalizeZ<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n  c: PC,\n  points: P[]\n): P[] {\n  const invertedZs = FpInvertBatch(\n    c.Fp,\n    points.map((p) => p.Z!)\n  );\n  return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\n\nfunction validateW(W: number, bits: number) {\n  if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n    throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\n\n/** Internal wNAF opts for specific W and scalarBits.\n * Zero digits are skipped, so tables store only the positive half-window and callers reserve one\n * extra carry window.\n */\ntype WOpts = {\n  windows: number;\n  windowSize: number;\n  mask: bigint;\n  maxNumber: number;\n  shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n  validateW(W, scalarBits);\n  const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n  const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n  const maxNumber = 2 ** W; // W=8 256\n  const mask = bitMask(W); // W=8 255 == mask 0b11111111\n  const shiftBy = BigInt(W); // W=8 8\n  return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n  const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n  let wbits = Number(n & mask); // extract W bits.\n  let nextN = n >> shiftBy; // shift number by W bits.\n\n  // What actually happens here:\n  // const highestBit = Number(mask ^ (mask >> 1n));\n  // let wbits2 = wbits - 1; // skip zero\n  // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n  // split if bits > max: +224 => 256-32\n  if (wbits > windowSize) {\n    // we skip zero, which means instead of `>= size-1`, we do `> size`\n    wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n    nextN += _1n; // +256 (carry)\n  }\n  const offsetStart = window * windowSize;\n  const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero; ignore when isZero\n  const isZero = wbits === 0; // is current window slice a 0?\n  const isNeg = wbits < 0; // is current window slice negative?\n  const isNegF = window % 2 !== 0; // fake branch noise only\n  const offsetF = offsetStart; // fake branch noise only\n  return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\n\nfunction validateMSMPoints(points: any[], c: any) {\n  if (!Array.isArray(points)) throw new Error('array expected');\n  points.forEach((p, i) => {\n    if (!(p instanceof c)) throw new Error('invalid point at index ' + i);\n  });\n}\nfunction validateMSMScalars(scalars: any[], field: any) {\n  if (!Array.isArray(scalars)) throw new Error('array of scalars expected');\n  scalars.forEach((s, i) => {\n    if (!field.isValid(s)) throw new Error('invalid scalar at index ' + i);\n  });\n}\n\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap<any, any[]>();\nconst pointWindowSizes = new WeakMap<any, number>();\n\nfunction getW(P: any): number {\n  // To disable precomputes:\n  // return 1;\n  // `1` is also the uncached sentinel: use the ladder / non-precomputed path.\n  return pointWindowSizes.get(P) || 1;\n}\n\nfunction assert0(n: bigint): void {\n  // Internal invariant: a non-zero remainder here means the wNAF window decomposition or loop\n  // count is inconsistent, not that the original caller provided a bad scalar.\n  if (n !== _0n) throw new Error('invalid wNAF');\n}\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / \uD835\uDC4A) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * TODO: research returning a 2d JS array of windows instead of a single window.\n * This would allow windows to be in different memory locations.\n * @param Point - Point constructor.\n * @param bits - Scalar bit length.\n * @example\n * Elliptic curve multiplication of Point by scalar.\n *\n * ```ts\n * import { wNAF } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const ladder = new wNAF(p256.Point, p256.Point.Fn.BITS);\n * ```\n */\nexport class wNAF<PC extends PC_ANY> {\n  private readonly BASE: PC_P<PC>;\n  private readonly ZERO: PC_P<PC>;\n  private readonly Fn: PC['Fn'];\n  readonly bits: number;\n\n  // Parametrized with a given Point class (not individual point)\n  constructor(Point: PC, bits: number) {\n    this.BASE = Point.BASE;\n    this.ZERO = Point.ZERO;\n    this.Fn = Point.Fn;\n    this.bits = bits;\n  }\n\n  // non-const time multiplication ladder\n  _unsafeLadder(elm: PC_P<PC>, n: bigint, p: PC_P<PC> = this.ZERO): PC_P<PC> {\n    let d: PC_P<PC> = elm;\n    while (n > _0n) {\n      if (n & _1n) p = p.add(d);\n      d = d.double();\n      n >>= _1n;\n    }\n    return p;\n  }\n\n  /**\n   * Creates a wNAF precomputation window. Used for caching.\n   * Default window size is set by `utils.precompute()` and is equal to 8.\n   * Number of precomputed points depends on the curve size:\n   * 2^(\uD835\uDC4A\u22121) * (Math.ceil(\uD835\uDC5B / \uD835\uDC4A) + 1), where:\n   * - \uD835\uDC4A is the window size\n   * - \uD835\uDC5B is the bitlength of the curve order.\n   * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n   * @param point - Point instance\n   * @param W - window size\n   * @returns precomputed point tables flattened to a single array\n   */\n  private precomputeWindow(point: PC_P<PC>, W: number): PC_P<PC>[] {\n    const { windows, windowSize } = calcWOpts(W, this.bits);\n    const points: PC_P<PC>[] = [];\n    let p: PC_P<PC> = point;\n    let base = p;\n    for (let window = 0; window < windows; window++) {\n      base = p;\n      points.push(base);\n      // i=1, bc we skip 0\n      for (let i = 1; i < windowSize; i++) {\n        base = base.add(p);\n        points.push(base);\n      }\n      p = base.double();\n    }\n    return points;\n  }\n\n  /**\n   * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n   * More compact implementation:\n   * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n   * @returns real and fake (for const-time) points\n   */\n  private wNAF(W: number, precomputes: PC_P<PC>[], n: bigint): { p: PC_P<PC>; f: PC_P<PC> } {\n    // Scalar should be smaller than field order\n    if (!this.Fn.isValid(n)) throw new Error('invalid scalar');\n    // Accumulators\n    let p = this.ZERO;\n    let f = this.BASE;\n    // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n    // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n    // there is negate now: it is possible that negated element from low value\n    // would be the same as high element, which will create carry into next window.\n    // It's not obvious how this can fail, but still worth investigating later.\n    const wo = calcWOpts(W, this.bits);\n    for (let window = 0; window < wo.windows; window++) {\n      // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n      const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n      n = nextN;\n      if (isZero) {\n        // bits are 0: add garbage to fake point\n        // Important part for const-time getPublicKey: add random \"noise\" point to f.\n        f = f.add(negateCt(isNegF, precomputes[offsetF]));\n      } else {\n        // bits are 1: add to result point\n        p = p.add(negateCt(isNeg, precomputes[offset]));\n      }\n    }\n    assert0(n);\n    // Return both real and fake points so JIT keeps the noise path alive.\n    // Known caveat: negate/carry interactions can still drive `f` to infinity even when `p` is not,\n    // which weakens the noise path and leaves this only \"less const-time\" by about one bigint mul.\n    return { p, f };\n  }\n\n  /**\n   * Implements unsafe EC multiplication using precomputed tables\n   * and w-ary non-adjacent form.\n   * @param acc - accumulator point to add result of multiplication\n   * @returns point\n   */\n  private wNAFUnsafe(\n    W: number,\n    precomputes: PC_P<PC>[],\n    n: bigint,\n    acc: PC_P<PC> = this.ZERO\n  ): PC_P<PC> {\n    const wo = calcWOpts(W, this.bits);\n    for (let window = 0; window < wo.windows; window++) {\n      if (n === _0n) break; // Early-exit, skip 0 value\n      const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n      n = nextN;\n      if (isZero) {\n        // Window bits are 0: skip processing.\n        // Move to next window.\n        continue;\n      } else {\n        const item = precomputes[offset];\n        acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n      }\n    }\n    assert0(n);\n    return acc;\n  }\n\n  private getPrecomputes(W: number, point: PC_P<PC>, transform?: Mapper<PC_P<PC>>): PC_P<PC>[] {\n    // Cache key is only point identity plus the remembered window size; callers must not reuse the\n    // same point with incompatible `transform(...)` layouts and expect a separate cache entry.\n    let comp = pointPrecomputes.get(point);\n    if (!comp) {\n      comp = this.precomputeWindow(point, W) as PC_P<PC>[];\n      if (W !== 1) {\n        // Doing transform outside of if brings 15% perf hit\n        if (typeof transform === 'function') comp = transform(comp);\n        pointPrecomputes.set(point, comp);\n      }\n    }\n    return comp;\n  }\n\n  cached(\n    point: PC_P<PC>,\n    scalar: bigint,\n    transform?: Mapper<PC_P<PC>>\n  ): { p: PC_P<PC>; f: PC_P<PC> } {\n    const W = getW(point);\n    return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n  }\n\n  unsafe(point: PC_P<PC>, scalar: bigint, transform?: Mapper<PC_P<PC>>, prev?: PC_P<PC>): PC_P<PC> {\n    const W = getW(point);\n    if (W === 1) return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n    return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n  }\n\n  // We calculate precomputes for elliptic curve point multiplication\n  // using windowed method. This specifies window size and\n  // stores precomputed values. Usually only base point would be precomputed.\n  createCache(P: PC_P<PC>, W: number): void {\n    validateW(W, this.bits);\n    pointWindowSizes.set(P, W);\n    pointPrecomputes.delete(P);\n  }\n\n  hasCache(elm: PC_P<PC>): boolean {\n    return getW(elm) !== 1;\n  }\n}\n\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n * @param Point - Point constructor.\n * @param point - Input point.\n * @param k1 - First non-negative absolute scalar chunk.\n * @param k2 - Second non-negative absolute scalar chunk.\n * @returns Partial multiplication results.\n * @example\n * Endomorphism-specific multiplication for Koblitz curves.\n *\n * ```ts\n * import { mulEndoUnsafe } from '@noble/curves/abstract/curve.js';\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const parts = mulEndoUnsafe(secp256k1.Point, secp256k1.Point.BASE, 3n, 5n);\n * ```\n */\nexport function mulEndoUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n  Point: PC,\n  point: P,\n  k1: bigint,\n  k2: bigint\n): { p1: P; p2: P } {\n  let acc = point;\n  let p1 = Point.ZERO;\n  let p2 = Point.ZERO;\n  while (k1 > _0n || k2 > _0n) {\n    if (k1 & _1n) p1 = p1.add(acc);\n    if (k2 & _1n) p2 = p2.add(acc);\n    acc = acc.double();\n    k1 >>= _1n;\n    k2 >>= _1n;\n  }\n  return { p1, p2 };\n}\n\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c - Curve Point constructor\n * @param points - array of L curve points\n * @param scalars - array of L scalars (aka secret keys / bigints)\n * @returns MSM result point. Empty input is accepted and returns the identity.\n * @throws If the point set, scalar set, or MSM sizing is invalid. {@link Error}\n * @example\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { pippenger } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const point = pippenger(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()], [2n, 3n]);\n * ```\n */\nexport function pippenger<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n  c: PC,\n  points: P[],\n  scalars: bigint[]\n): P {\n  // If we split scalars by some window (let's say 8 bits), every chunk will only\n  // take 256 buckets even if there are 4096 scalars, also re-uses double.\n  // TODO:\n  // - https://eprint.iacr.org/2024/750.pdf\n  // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n  // 0 is accepted in scalars\n  const fieldN = c.Fn;\n  validateMSMPoints(points, c);\n  validateMSMScalars(scalars, fieldN);\n  const plength = points.length;\n  const slength = scalars.length;\n  if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n  // if (plength === 0) throw new Error('array must be of length >= 2');\n  const zero = c.ZERO;\n  const wbits = bitLen(BigInt(plength));\n  let windowSize = 1; // bits\n  if (wbits > 12) windowSize = wbits - 3;\n  else if (wbits > 4) windowSize = wbits - 2;\n  else if (wbits > 0) windowSize = 2;\n  const MASK = bitMask(windowSize);\n  const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n  const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n  let sum = zero;\n  for (let i = lastBits; i >= 0; i -= windowSize) {\n    buckets.fill(zero);\n    for (let j = 0; j < slength; j++) {\n      const scalar = scalars[j];\n      const wbits = Number((scalar >> BigInt(i)) & MASK);\n      buckets[wbits] = buckets[wbits].add(points[j]);\n    }\n    let resI = zero; // not using this will do small speed-up, but will lose ct\n    // Skip first bucket, because it is zero\n    for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n      sumI = sumI.add(buckets[j]);\n      resI = resI.add(sumI);\n    }\n    sum = sum.add(resI);\n    if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();\n  }\n  return sum as P;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c - Curve Point constructor\n * @param points - array of L curve points\n * @param windowSize - Precompute window size.\n * @returns Function which multiplies points with scalars. The closure accepts\n *   `scalars.length <= points.length`, and omitted trailing scalars are treated as zero.\n * @throws If the point set or precompute window is invalid. {@link Error}\n * @example\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { precomputeMSMUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const msm = precomputeMSMUnsafe(p256.Point, [p256.Point.BASE], 4);\n * const point = msm([3n]);\n * ```\n */\nexport function precomputeMSMUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n  c: PC,\n  points: P[],\n  windowSize: number\n): (scalars: bigint[]) => P {\n  /**\n   * Performance Analysis of Window-based Precomputation\n   *\n   * Base Case (256-bit scalar, 8-bit window):\n   * - Standard precomputation requires:\n   *   - 31 additions per scalar \u00D7 256 scalars = 7,936 ops\n   *   - Plus 255 summary additions = 8,191 total ops\n   *   Note: Summary additions can be optimized via accumulator\n   *\n   * Chunked Precomputation Analysis:\n   * - Using 32 chunks requires:\n   *   - 255 additions per chunk\n   *   - 256 doublings\n   *   - Total: (255 \u00D7 32) + 256 = 8,416 ops\n   *\n   * Memory Usage Comparison:\n   * Window Size | Standard Points | Chunked Points\n   * ------------|-----------------|---------------\n   *     4-bit   |     520         |      15\n   *     8-bit   |    4,224        |     255\n   *    10-bit   |   13,824        |   1,023\n   *    16-bit   |  557,056        |  65,535\n   *\n   * Key Advantages:\n   * 1. Enables larger window sizes due to reduced memory overhead\n   * 2. More efficient for smaller scalar counts:\n   *    - 16 chunks: (16 \u00D7 255) + 256 = 4,336 ops\n   *    - ~2x faster than standard 8,191 ops\n   *\n   * Limitations:\n   * - Not suitable for plain precomputes (requires 256 constant doublings)\n   * - Performance degrades with larger scalar counts:\n   *   - Optimal for ~256 scalars\n   *   - Less efficient for 4096+ scalars (Pippenger preferred)\n   */\n  const fieldN = c.Fn;\n  validateW(windowSize, fieldN.BITS);\n  validateMSMPoints(points, c);\n  const zero = c.ZERO;\n  const tableSize = 2 ** windowSize - 1; // table size (without zero)\n  const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n  const MASK = bitMask(windowSize);\n  const tables = points.map((p: P) => {\n    const res = [];\n    for (let i = 0, acc = p; i < tableSize; i++) {\n      res.push(acc);\n      acc = acc.add(p);\n    }\n    return res;\n  });\n  return (scalars: bigint[]): P => {\n    validateMSMScalars(scalars, fieldN);\n    if (scalars.length > points.length)\n      throw new Error('array of scalars must be smaller than array of points');\n    let res = zero;\n    for (let i = 0; i < chunks; i++) {\n      // No need to double if accumulator is still zero.\n      if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double();\n      const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n      for (let j = 0; j < scalars.length; j++) {\n        const n = scalars[j];\n        const curr = Number((n >> shiftBy) & MASK);\n        if (!curr) continue; // skip zero scalars chunks\n        res = res.add(tables[j][curr - 1]);\n      }\n    }\n    return res;\n  };\n}\n\n/** Minimal curve parameters needed to construct a Weierstrass or Edwards curve. */\nexport type ValidCurveParams<T> = {\n  /** Base-field modulus. */\n  p: bigint;\n  /** Prime subgroup order. */\n  n: bigint;\n  /** Cofactor. */\n  h: bigint;\n  /** Curve parameter `a`. */\n  a: T;\n  /** Weierstrass curve parameter `b`. */\n  b?: T;\n  /** Edwards curve parameter `d`. */\n  d?: T;\n  /** Generator x coordinate. */\n  Gx: T;\n  /** Generator y coordinate. */\n  Gy: T;\n};\n\nfunction createField<T>(order: bigint, field?: TArg<IField<T>>, isLE?: boolean): TRet<IField<T>> {\n  if (field) {\n    // Reuse supplied field overrides as-is; `isLE` only affects freshly constructed fallback\n    // fields, and validateField() below only checks the arithmetic subset, not full byte/cmov\n    // behavior.\n    if (field.ORDER !== order) throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n    validateField(field);\n    return field as TRet<IField<T>>;\n  } else {\n    return Field(order, { isLE }) as unknown as TRet<IField<T>>;\n  }\n}\n/** Pair of fields used by curve constructors. */\nexport type FpFn<T> = {\n  /** Base field used for curve coordinates. */\n  Fp: IField<T>;\n  /** Scalar field used for secret scalars and subgroup arithmetic. */\n  Fn: IField<bigint>;\n};\n\n/**\n * Validates basic CURVE shape and field membership, then creates fields.\n * This does not prove that the generator is on-curve, that subgroup/order data are consistent, or\n * that the curve equation itself is otherwise sane.\n * @param type - Curve family.\n * @param CURVE - Curve parameters.\n * @param curveOpts - Optional field overrides:\n *   - `Fp` (optional): Optional base-field override.\n *   - `Fn` (optional): Optional scalar-field override.\n * @param FpFnLE - Whether field encoding is little-endian.\n * @returns Frozen curve parameters and fields.\n * @throws If the curve parameters or field overrides are invalid. {@link Error}\n * @example\n * Build curve fields from raw constants before constructing a curve instance.\n *\n * ```ts\n * const curve = createCurveFields('weierstrass', {\n *   p: 17n,\n *   n: 19n,\n *   h: 1n,\n *   a: 2n,\n *   b: 2n,\n *   Gx: 5n,\n *   Gy: 1n,\n * });\n * ```\n */\nexport function createCurveFields<T>(\n  type: 'weierstrass' | 'edwards',\n  CURVE: ValidCurveParams<T>,\n  curveOpts: TArg<Partial<FpFn<T>>> = {},\n  FpFnLE?: boolean\n): TRet<FpFn<T> & { CURVE: ValidCurveParams<T> }> {\n  if (FpFnLE === undefined) FpFnLE = type === 'edwards';\n  if (!CURVE || typeof CURVE !== 'object') throw new Error(`expected valid ${type} CURVE object`);\n  for (const p of ['p', 'n', 'h'] as const) {\n    const val = CURVE[p];\n    if (!(typeof val === 'bigint' && val > _0n))\n      throw new Error(`CURVE.${p} must be positive bigint`);\n  }\n  const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n  const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n  const _b: 'b' | 'd' = type === 'weierstrass' ? 'b' : 'd';\n  const params = ['Gx', 'Gy', 'a', _b] as const;\n  for (const p of params) {\n    // @ts-ignore\n    if (!Fp.isValid(CURVE[p]))\n      throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n  }\n  CURVE = Object.freeze(Object.assign({}, CURVE));\n  return { CURVE, Fp, Fn } as TRet<FpFn<T> & { CURVE: ValidCurveParams<T> }>;\n}\n\ntype KeygenFn = (\n  seed?: Uint8Array,\n  isCompressed?: boolean\n) => { secretKey: Uint8Array; publicKey: Uint8Array };\n/**\n * @param randomSecretKey - Secret-key generator.\n * @param getPublicKey - Public-key derivation helper.\n * @returns Keypair generator.\n * @example\n * Build a `keygen()` helper from existing secret-key and public-key primitives.\n *\n * ```ts\n * import { createKeygen } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey);\n * const pair = keygen();\n * ```\n */\nexport function createKeygen(\n  randomSecretKey: Function,\n  getPublicKey: TArg<Signer['getPublicKey']>\n): TRet<KeygenFn> {\n  return function keygen(seed?: TArg<Uint8Array>) {\n    const secretKey = randomSecretKey(seed) as TRet<Uint8Array>;\n    return { secretKey, publicKey: getPublicKey(secretKey) as TRet<Uint8Array> };\n  };\n}\n", "/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport {\n  abytes,\n  aexists,\n  ahash,\n  aoutput,\n  clean,\n  type CHash,\n  type Hash,\n  type TArg,\n  type TRet,\n} from './utils.ts';\n\n/**\n * Internal class for HMAC.\n * Accepts any byte key, although RFC 2104 \u00A73 recommends keys at least\n * `HashLen` bytes long.\n */\nexport class _HMAC<T extends Hash<T>> implements Hash<_HMAC<T>> {\n  oHash: T;\n  iHash: T;\n  blockLen: number;\n  outputLen: number;\n  canXOF = false;\n  private finished = false;\n  private destroyed = false;\n\n  constructor(hash: TArg<CHash>, key: TArg<Uint8Array>) {\n    ahash(hash);\n    abytes(key, undefined, 'key');\n    this.iHash = hash.create() as T;\n    if (typeof this.iHash.update !== 'function')\n      throw new Error('Expected instance of class which extends utils.Hash');\n    this.blockLen = this.iHash.blockLen;\n    this.outputLen = this.iHash.outputLen;\n    const blockLen = this.blockLen;\n    const pad = new Uint8Array(blockLen);\n    // blockLen can be bigger than outputLen\n    pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n    for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n    this.iHash.update(pad);\n    // By doing update (processing of the first block) of the outer hash here,\n    // we can re-use it between multiple calls via clone.\n    this.oHash = hash.create() as T;\n    // Undo internal XOR && apply outer XOR\n    for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n    this.oHash.update(pad);\n    clean(pad);\n  }\n  update(buf: TArg<Uint8Array>): this {\n    aexists(this);\n    this.iHash.update(buf);\n    return this;\n  }\n  digestInto(out: TArg<Uint8Array>): void {\n    aexists(this);\n    aoutput(out, this);\n    this.finished = true;\n    const buf = out.subarray(0, this.outputLen);\n    // Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before\n    // overwriting that same prefix with the final tag, leaving any oversized tail untouched.\n    this.iHash.digestInto(buf);\n    this.oHash.update(buf);\n    this.oHash.digestInto(buf);\n    this.destroy();\n  }\n  digest(): TRet<Uint8Array> {\n    const out = new Uint8Array(this.oHash.outputLen);\n    this.digestInto(out);\n    return out as TRet<Uint8Array>;\n  }\n  _cloneInto(to?: _HMAC<T>): _HMAC<T> {\n    // Create new instance without calling constructor since the key\n    // is already in state and we don't know it.\n    to ||= Object.create(Object.getPrototypeOf(this), {});\n    const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n    to = to as this;\n    to.finished = finished;\n    to.destroyed = destroyed;\n    to.blockLen = blockLen;\n    to.outputLen = outputLen;\n    to.oHash = oHash._cloneInto(to.oHash);\n    to.iHash = iHash._cloneInto(to.iHash);\n    return to;\n  }\n  clone(): _HMAC<T> {\n    return this._cloneInto();\n  }\n  destroy(): void {\n    this.destroyed = true;\n    this.oHash.destroy();\n    this.iHash.destroy();\n  }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - authentication key bytes\n * @param message - message bytes to authenticate\n * @returns Authentication tag bytes.\n * @example\n * Compute an RFC 2104 HMAC.\n * ```ts\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const mac = hmac(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));\n * ```\n */\ntype HmacFn = {\n  (hash: TArg<CHash>, key: TArg<Uint8Array>, message: TArg<Uint8Array>): TRet<Uint8Array>;\n  create(hash: TArg<CHash>, key: TArg<Uint8Array>): TRet<_HMAC<any>>;\n};\nexport const hmac: TRet<HmacFn> = /* @__PURE__ */ (() => {\n  const hmac_ = ((\n    hash: TArg<CHash>,\n    key: TArg<Uint8Array>,\n    message: TArg<Uint8Array>\n  ): TRet<Uint8Array> => new _HMAC<any>(hash, key).update(message).digest()) as TRet<HmacFn>;\n  hmac_.create = (hash: TArg<CHash>, key: TArg<Uint8Array>): TRet<_HMAC<any>> =>\n    new _HMAC<any>(hash, key) as TRet<_HMAC<any>>;\n  return hmac_;\n})();\n", "/**\n * Short Weierstrass curve methods. The formula is: y\u00B2 = x\u00B3 + ax + b.\n *\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n *   `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n *   `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n *   it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n *     1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n *     which is hard to debug.\n *     2. Params can be generic and we can't enforce them to be constant value:\n *     if somebody creates curve from non-constant params,\n *     it would be allowed to interact with other curves with non-constant params\n *\n * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils.js';\nimport {\n  abignumber,\n  abool,\n  abytes,\n  aInRange,\n  asafenumber,\n  bitLen,\n  bitMask,\n  bytesToHex,\n  bytesToNumberBE,\n  concatBytes,\n  createHmacDrbg,\n  hexToBytes,\n  isBytes,\n  numberToHexUnpadded,\n  validateObject,\n  randomBytes as wcRandomBytes,\n  type CHash,\n  type HmacFn,\n  type Signer,\n  type TArg,\n  type TRet,\n} from '../utils.ts';\nimport {\n  createCurveFields,\n  createKeygen,\n  mulEndoUnsafe,\n  negateCt,\n  normalizeZ,\n  wNAF,\n  type AffinePoint,\n  type CurveLengths,\n  type CurvePoint,\n  type CurvePointCons,\n} from './curve.ts';\nimport {\n  FpInvertBatch,\n  FpIsSquare,\n  getMinHashLength,\n  mapHashToField,\n  validateField,\n  type IField,\n} from './modular.ts';\n\n/** Shared affine point shape used by Weierstrass helpers. */\nexport type { AffinePoint };\n\ntype EndoBasis = [[bigint, bigint], [bigint, bigint]];\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV endomorphism \u03C8**.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism \u03C8 transforms a point: `P = (x, y) \u21A6 \u03C8(P) = (\u03B2\u00B7x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k \u2261 k\u2081 + k\u2082\u00B7\u03BB (mod n)`\n * 3. Then these are combined: `k\u00B7P = k\u2081\u00B7P + k\u2082\u00B7\u03C8(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n *    one 256-bit multiplication.\n *\n * where\n * * beta: \u03B2 \u2208 F\u209A with \u03B2\u00B3 = 1, \u03B2 \u2260 1\n * * lambda: \u03BB \u2208 F\u2099 with \u03BB\u00B3 = 1, \u03BB \u2260 1\n * * splitScalar decomposes k \u21A6 k\u2081, k\u2082, by using reduced basis vectors.\n *   Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-\u03BB, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * {@link https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 | this endomorphism gist}.\n */\nexport type EndomorphismOpts = {\n  /** Cube root of unity used by the GLV endomorphism. */\n  beta: bigint;\n  /** Reduced lattice basis used for scalar splitting. */\n  basises?: EndoBasis;\n  /**\n   * Optional custom scalar-splitting helper.\n   * Receives one scalar and returns two half-sized scalar components.\n   */\n  splitScalar?: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\n// We construct the basis so `den` is always positive and equals `n`,\n// but the `num` sign depends on the basis, not on the secret value.\n// Exact half-way cases round away from zero, which keeps the split symmetric\n// around the reduced-basis boundaries used by endomorphism decomposition.\nconst divNearest = (num: bigint, den: bigint) => (num + (num >= 0 ? den : -den) / _2n) / den;\n\n/** Two half-sized scalar components returned by endomorphism splitting. */\nexport type ScalarEndoParts = {\n  /** Whether the first split scalar should be negated. */\n  k1neg: boolean;\n  /** Absolute value of the first split scalar. */\n  k1: bigint;\n  /** Whether the second split scalar should be negated. */\n  k2neg: boolean;\n  /** Absolute value of the second split scalar. */\n  k2: bigint;\n};\n\n/** Splits scalar for GLV endomorphism. */\nexport function _splitEndoScalar(k: bigint, basis: EndoBasis, n: bigint): ScalarEndoParts {\n  // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n  // Since part can be negative, we need to do this on point.\n  // Callers must provide a reduced GLV basis whose vectors satisfy\n  // `a + b * lambda \u2261 0 (mod n)`; this helper only sees the basis and `n`.\n  // Reject unreduced scalars instead of silently treating them mod n.\n  aInRange('scalar', k, _0n, n);\n  // TODO: verifyScalar function which consumes lambda\n  const [[a1, b1], [a2, b2]] = basis;\n  const c1 = divNearest(b2 * k, n);\n  const c2 = divNearest(-b1 * k, n);\n  // |k1|/|k2| is < sqrt(N), but can be negative.\n  // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n  let k1 = k - c1 * a1 - c2 * a2;\n  let k2 = -c1 * b1 - c2 * b2;\n  const k1neg = k1 < _0n;\n  const k2neg = k2 < _0n;\n  if (k1neg) k1 = -k1;\n  if (k2neg) k2 = -k2;\n  // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.\n  // This should only happen on wrong bases.\n  // Also, the math inside is complex enough that this guard is worth keeping.\n  const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n  if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n    throw new Error('splitScalar (endomorphism): failed for k');\n  }\n  return { k1neg, k1, k2neg, k2 };\n}\n\n/**\n * Option to enable hedged signatures with improved security.\n *\n * * Randomly generated k is bad, because broken CSPRNG would leak private keys.\n * * Deterministic k (RFC6979) is better; but is suspectible to fault attacks.\n *\n * We allow using technique described in RFC6979 3.6: additional k', a.k.a. adding randomness\n * to deterministic sig. If CSPRNG is broken & randomness is weak, it would STILL be as secure\n * as ordinary sig without ExtraEntropy.\n *\n * * `true` means \"fetch data, from CSPRNG, incorporate it into k generation\"\n * * `false` means \"disable extra entropy, use purely deterministic k\"\n * * `Uint8Array` passed means \"incorporate following data into k generation\"\n *\n * See {@link https://paulmillr.com/posts/deterministic-signatures/ | deterministic signatures}.\n */\nexport type ECDSAExtraEntropy = boolean | Uint8Array;\n/**\n * - `compact` is the default format\n * - `recovered` is the same as compact, but with an extra byte indicating recovery byte\n * - `der` is ASN.1 DER encoding\n */\nexport type ECDSASignatureFormat = 'compact' | 'recovered' | 'der';\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n *   When a custom hash is used, it must be set to `false`.\n */\nexport type ECDSARecoverOpts = {\n  /** Whether to hash the message before signature recovery. */\n  prehash?: boolean;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n *   When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures with `sig.s >= CURVE.n/2n`.\n *   Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n *   which is default openssl behavior.\n *   Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n */\nexport type ECDSAVerifyOpts = {\n  /** Whether to hash the message before verification. */\n  prehash?: boolean;\n  /** Whether to reject high-S signatures. */\n  lowS?: boolean;\n  /** Signature encoding to accept. */\n  format?: ECDSASignatureFormat;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n *   When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures with `sig.s >= CURVE.n/2n`.\n *   Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n *   which is default openssl behavior.\n *   Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n * - `extraEntropy`: (default: false) creates signatures with increased\n *   security, see {@link ECDSAExtraEntropy}\n */\nexport type ECDSASignOpts = {\n  /** Whether to hash the message before signing. */\n  prehash?: boolean;\n  /** Whether to normalize signatures into the low-S half-order. */\n  lowS?: boolean;\n  /** Signature encoding to produce. */\n  format?: ECDSASignatureFormat;\n  /** Optional hedging input for deterministic k generation. */\n  extraEntropy?: ECDSAExtraEntropy;\n};\n\nfunction validateSigFormat(format: string): ECDSASignatureFormat {\n  if (!['compact', 'recovered', 'der'].includes(format))\n    throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n  return format as ECDSASignatureFormat;\n}\n\nfunction validateSigOpts<T extends ECDSASignOpts, D extends Required<ECDSASignOpts>>(\n  opts: T,\n  def: D\n): D {\n  validateObject(opts);\n  const optsn = {} as D;\n  // Normalize only the declared option subset from `def`; unknown keys are\n  // intentionally ignored so shared / superset option bags stay valid here too.\n  // `extraEntropy` stays an opaque payload until the signing path consumes it.\n  for (let optName of Object.keys(def) as (keyof D)[]) {\n    // @ts-ignore\n    optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n  }\n  abool(optsn.lowS!, 'lowS');\n  abool(optsn.prehash!, 'prehash');\n  if (optsn.format !== undefined) validateSigFormat(optsn.format);\n  return optsn;\n}\n\n/** Projective XYZ point used by short Weierstrass curves. */\nexport interface WeierstrassPoint<T> extends CurvePoint<T, WeierstrassPoint<T>> {\n  /** projective X coordinate. Different from affine x. */\n  readonly X: T;\n  /** projective Y coordinate. Different from affine y. */\n  readonly Y: T;\n  /** projective z coordinate */\n  readonly Z: T;\n  /** affine x coordinate. Different from projective X. */\n  get x(): T;\n  /** affine y coordinate. Different from projective Y. */\n  get y(): T;\n  /**\n   * Encode the point into compressed or uncompressed SEC1 bytes.\n   * @param isCompressed - Whether to use the compressed form.\n   * @returns Encoded point bytes.\n   */\n  toBytes(isCompressed?: boolean): TRet<Uint8Array>;\n  /**\n   * Encode the point into compressed or uncompressed SEC1 hex.\n   * @param isCompressed - Whether to use the compressed form.\n   * @returns Encoded point hex.\n   */\n  toHex(isCompressed?: boolean): string;\n}\n\n/** Constructor and metadata helpers for Weierstrass points. */\nexport interface WeierstrassPointCons<T> extends CurvePointCons<WeierstrassPoint<T>> {\n  /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n  new (X: T, Y: T, Z: T): WeierstrassPoint<T>;\n  /**\n   * Return the curve parameters captured by this point constructor.\n   * @returns Curve parameters.\n   */\n  CURVE(): WeierstrassOpts<T>;\n}\n\n/**\n * Weierstrass curve options.\n *\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor, usually 1. h*n is group order; n is subgroup order\n * * a: formula param, must be in field of p\n * * b: formula param, must be in field of p\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type WeierstrassOpts<T> = Readonly<{\n  /** Base-field modulus. */\n  p: bigint;\n  /** Prime subgroup order. */\n  n: bigint;\n  /** Curve cofactor. */\n  h: bigint;\n  /** Weierstrass curve parameter `a`. */\n  a: T;\n  /** Weierstrass curve parameter `b`. */\n  b: T;\n  /** Generator x coordinate. */\n  Gx: T;\n  /** Generator y coordinate. */\n  Gy: T;\n}>;\n\n/**\n * Optional helpers and overrides for a Weierstrass point constructor.\n *\n * When a cofactor != 1, there can be effective methods to:\n * 1. Determine whether a point is torsion-free\n * 2. Clear torsion component\n */\nexport type WeierstrassExtraOpts<T> = Partial<{\n  /** Optional base-field override. */\n  Fp: IField<T>;\n  /** Optional scalar-field override. */\n  Fn: IField<bigint>;\n  /** Whether the point constructor accepts infinity points. */\n  allowInfinityPoint: boolean;\n  /** Optional GLV endomorphism data. */\n  endo: EndomorphismOpts;\n  /** Optional torsion-check override. */\n  isTorsionFree: (c: WeierstrassPointCons<T>, point: WeierstrassPoint<T>) => boolean;\n  /** Optional cofactor-clearing override. */\n  clearCofactor: (c: WeierstrassPointCons<T>, point: WeierstrassPoint<T>) => WeierstrassPoint<T>;\n  /** Optional custom point decoder. */\n  fromBytes: (bytes: TArg<Uint8Array>) => AffinePoint<T>;\n  /** Optional custom point encoder. */\n  toBytes: (\n    c: WeierstrassPointCons<T>,\n    point: WeierstrassPoint<T>,\n    isCompressed: boolean\n  ) => TRet<Uint8Array>;\n}>;\n\n/**\n * Options for ECDSA signatures over a Weierstrass curve.\n *\n * * lowS: (default: true) whether produced or verified signatures occupy the\n *   low half of `ecdsaOpts.n`. Prevents malleability.\n * * hmac: (default: noble-hashes hmac) function, would be used to init hmac-drbg for k generation.\n * * randomBytes: (default: webcrypto os-level CSPRNG) custom method for fetching secure randomness.\n * * bits2int, bits2int_modN: used in sigs, sometimes overridden by curves. Custom hooks are\n *   treated as pure functions over validated bytes and MUST NOT mutate caller-owned buffers or\n *   closure-captured option bags. `bits2int_modN` must also return a canonical scalar in\n *   `[0..Point.Fn.ORDER-1]`.\n */\nexport type ECDSAOpts = Partial<{\n  /** Default low-S policy for this ECDSA instance. */\n  lowS: boolean;\n  /** HMAC implementation used by RFC6979 DRBG. */\n  hmac: HmacFn;\n  /** RNG override used by helper constructors. */\n  randomBytes: (bytesLength?: number) => TRet<Uint8Array>;\n  /** Hash-to-integer conversion override. */\n  bits2int: (bytes: TArg<Uint8Array>) => bigint;\n  /** Hash-to-integer-mod-n conversion override. Returns a canonical scalar in `[0..Fn.ORDER-1]`. */\n  bits2int_modN: (bytes: TArg<Uint8Array>) => bigint;\n}>;\n\n/** Elliptic Curve Diffie-Hellman helper namespace. */\nexport interface ECDH {\n  /**\n   * Generate a secret/public key pair.\n   * @param seed - Optional seed material.\n   * @returns Secret/public key pair.\n   */\n  keygen: (seed?: TArg<Uint8Array>) => { secretKey: TRet<Uint8Array>; publicKey: TRet<Uint8Array> };\n  /**\n   * Derive the public key from a secret key.\n   * @param secretKey - Secret key bytes.\n   * @param isCompressed - Whether to emit compressed SEC1 bytes.\n   * @returns Encoded public key.\n   */\n  getPublicKey: (secretKey: TArg<Uint8Array>, isCompressed?: boolean) => TRet<Uint8Array>;\n  /**\n   * Compute the shared secret point from a secret key and peer public key.\n   * @param secretKeyA - Local secret key bytes.\n   * @param publicKeyB - Peer public key bytes.\n   * @param isCompressed - Whether to emit compressed SEC1 bytes.\n   * @returns Encoded shared point.\n   */\n  getSharedSecret: (\n    secretKeyA: TArg<Uint8Array>,\n    publicKeyB: TArg<Uint8Array>,\n    isCompressed?: boolean\n  ) => TRet<Uint8Array>;\n  /** Point constructor used by this ECDH instance. */\n  Point: WeierstrassPointCons<bigint>;\n  /** Validation and random-key helpers. */\n  utils: {\n    /** Check whether a secret key has the expected encoding. */\n    isValidSecretKey: (secretKey: TArg<Uint8Array>) => boolean;\n    /** Check whether a public key decodes to a valid point. */\n    isValidPublicKey: (publicKey: TArg<Uint8Array>, isCompressed?: boolean) => boolean;\n    /** Generate a valid random secret key. */\n    randomSecretKey: (seed?: TArg<Uint8Array>) => TRet<Uint8Array>;\n  };\n  /** Byte lengths for keys and signatures exposed by this curve. */\n  lengths: CurveLengths;\n}\n\n/**\n * ECDSA interface.\n * Only supported for prime fields, not Fp2 (extension fields).\n */\nexport interface ECDSA extends ECDH {\n  /**\n   * Sign a message with the given secret key.\n   * @param message - Message bytes.\n   * @param secretKey - Secret key bytes.\n   * @param opts - Optional signing tweaks. See {@link ECDSASignOpts}.\n   * @returns Encoded signature bytes.\n   */\n  sign: (\n    message: TArg<Uint8Array>,\n    secretKey: TArg<Uint8Array>,\n    opts?: TArg<ECDSASignOpts>\n  ) => TRet<Uint8Array>;\n  /**\n   * Verify a signature against a message and public key.\n   * @param signature - Encoded signature bytes.\n   * @param message - Message bytes.\n   * @param publicKey - Encoded public key.\n   * @param opts - Optional verification tweaks. See {@link ECDSAVerifyOpts}.\n   * @returns Whether the signature is valid.\n   */\n  verify: (\n    signature: TArg<Uint8Array>,\n    message: TArg<Uint8Array>,\n    publicKey: TArg<Uint8Array>,\n    opts?: TArg<ECDSAVerifyOpts>\n  ) => boolean;\n  /**\n   * Recover the public key encoded into a recoverable signature.\n   * @param signature - Recoverable signature bytes.\n   * @param message - Message bytes.\n   * @param opts - Optional recovery tweaks. See {@link ECDSARecoverOpts}.\n   * @returns Encoded recovered public key.\n   */\n  recoverPublicKey(\n    signature: TArg<Uint8Array>,\n    message: TArg<Uint8Array>,\n    opts?: TArg<ECDSARecoverOpts>\n  ): TRet<Uint8Array>;\n  /** Signature constructor and parser helpers. */\n  Signature: ECDSASignatureCons;\n}\n/**\n * @param m - Error message.\n * @example\n * Throw a DER-specific error when signature parsing encounters invalid bytes.\n *\n * ```ts\n * new DERErr('bad der');\n * ```\n */\nexport class DERErr extends Error {\n  constructor(m = '') {\n    super(m);\n  }\n}\n/** DER helper namespace used by ECDSA signature parsing and encoding. */\nexport type IDER = {\n  // asn.1 DER encoding utils\n  /**\n   * DER-specific error constructor.\n   * @param m - Error message.\n   * @returns DER-specific error instance.\n   */\n  Err: typeof DERErr;\n  // Basic building block is TLV (Tag-Length-Value)\n  /** Low-level tag-length-value helpers used by DER encoders. */\n  _tlv: {\n    /**\n     * Encode one TLV record.\n     * @param tag - ASN.1 tag byte.\n     * @param data - Hex-encoded value payload.\n     * @returns Encoded TLV string.\n     */\n    encode: (tag: number, data: string) => string;\n    // v - value, l - left bytes (unparsed)\n    /**\n     * Decode one TLV record and return the value plus leftover bytes.\n     * @param tag - Expected ASN.1 tag byte.\n     * @param data - Remaining DER bytes.\n     * @returns Parsed value plus leftover bytes.\n     */\n    decode(tag: number, data: TArg<Uint8Array>): TRet<{ v: Uint8Array; l: Uint8Array }>;\n  };\n  // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n  // since we always use positive integers here. It must always be empty:\n  // - add zero byte if exists\n  // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n  /** Positive-integer DER helpers used by ECDSA signature encoding. */\n  _int: {\n    /**\n     * Encode one positive bigint as a DER INTEGER.\n     * @param num - Positive integer to encode.\n     * @returns Encoded DER INTEGER.\n     */\n    encode(num: bigint): string;\n    /**\n     * Decode one DER INTEGER into a bigint.\n     * @param data - DER INTEGER bytes.\n     * @returns Decoded bigint.\n     */\n    decode(data: TArg<Uint8Array>): bigint;\n  };\n  /**\n   * Parse a DER signature into `{ r, s }`.\n   * @param bytes - DER signature bytes.\n   * @returns Parsed signature components.\n   */\n  toSig(bytes: TArg<Uint8Array>): { r: bigint; s: bigint };\n  /**\n   * Encode `{ r, s }` as a DER signature.\n   * @param sig - Signature components.\n   * @returns DER-encoded signature hex.\n   */\n  hexFromSig(sig: { r: bigint; s: bigint }): string;\n};\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n *     [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: {@link https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/ | Let's Encrypt ASN.1 guide} and\n * {@link https://luca.ntop.org/Teaching/Appunti/asn1.html | Luca Deri's ASN.1 notes}.\n * @example\n * ASN.1 DER encoding utilities.\n *\n * ```ts\n * const der = DER.hexFromSig({ r: 1n, s: 2n });\n * ```\n */\nexport const DER: IDER = {\n  // asn.1 DER encoding utils\n  Err: DERErr,\n  // Basic building block is TLV (Tag-Length-Value)\n  _tlv: {\n    encode: (tag: number, data: string): string => {\n      const { Err: E } = DER;\n      asafenumber(tag, 'tag');\n      if (tag < 0 || tag > 255) throw new E('tlv.encode: wrong tag');\n      if (typeof data !== 'string')\n        throw new TypeError('\"data\" expected string, got type=' + typeof data);\n      // Internal helper: callers hand this already-validated hex payload, so we only enforce\n      // byte alignment here instead of re-validating every nibble.\n      if (data.length & 1) throw new E('tlv.encode: unpadded data');\n      const dataLen = data.length / 2;\n      const len = numberToHexUnpadded(dataLen);\n      if ((len.length / 2) & 0b1000_0000) throw new E('tlv.encode: long form length too big');\n      // length of length with long form flag\n      const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n      const t = numberToHexUnpadded(tag);\n      return t + lenLen + len + data;\n    },\n    // v - value, l - left bytes (unparsed)\n    decode(tag: number, data: TArg<Uint8Array>): TRet<{ v: Uint8Array; l: Uint8Array }> {\n      const { Err: E } = DER;\n      data = abytes(data, undefined, 'DER data');\n      let pos = 0;\n      if (tag < 0 || tag > 255) throw new E('tlv.encode: wrong tag');\n      if (data.length < 2 || data[pos++] !== tag) throw new E('tlv.decode: wrong tlv');\n      const first = data[pos++];\n      // First bit of first length byte is the short/long form flag.\n      const isLong = !!(first & 0b1000_0000);\n      let length = 0;\n      if (!isLong) length = first;\n      else {\n        // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n        const lenLen = first & 0b0111_1111;\n        if (!lenLen) throw new E('tlv.decode(long): indefinite length not supported');\n        // This would overflow u32 in JS.\n        if (lenLen > 4) throw new E('tlv.decode(long): byte length is too big');\n        const lengthBytes = data.subarray(pos, pos + lenLen);\n        if (lengthBytes.length !== lenLen) throw new E('tlv.decode: length bytes not complete');\n        if (lengthBytes[0] === 0) throw new E('tlv.decode(long): zero leftmost byte');\n        for (const b of lengthBytes) length = (length << 8) | b;\n        pos += lenLen;\n        if (length < 128) throw new E('tlv.decode(long): not minimal encoding');\n      }\n      const v = data.subarray(pos, pos + length);\n      if (v.length !== length) throw new E('tlv.decode: wrong value length');\n      return { v, l: data.subarray(pos + length) } as TRet<{ v: Uint8Array; l: Uint8Array }>;\n    },\n  },\n  // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n  // since we always use positive integers here. It must always be empty:\n  // - add zero byte if exists\n  // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n  _int: {\n    encode(num: bigint): string {\n      const { Err: E } = DER;\n      abignumber(num);\n      if (num < _0n) throw new E('integer: negative integers are not allowed');\n      let hex = numberToHexUnpadded(num);\n      // Pad with zero byte if negative flag is present\n      if (Number.parseInt(hex[0], 16) & 0b1000) hex = '00' + hex;\n      if (hex.length & 1) throw new E('unexpected DER parsing assertion: unpadded hex');\n      return hex;\n    },\n    decode(data: TArg<Uint8Array>): bigint {\n      const { Err: E } = DER;\n      if (data.length < 1) throw new E('invalid signature integer: empty');\n      if (data[0] & 0b1000_0000) throw new E('invalid signature integer: negative');\n      // Single-byte zero `00` is the canonical DER INTEGER encoding for zero.\n      if (data.length > 1 && data[0] === 0x00 && !(data[1] & 0b1000_0000))\n        throw new E('invalid signature integer: unnecessary leading zero');\n      return bytesToNumberBE(data);\n    },\n  },\n  toSig(bytes: TArg<Uint8Array>): { r: bigint; s: bigint } {\n    // parse DER signature\n    const { Err: E, _int: int, _tlv: tlv } = DER;\n    const data = abytes(bytes, undefined, 'signature');\n    const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n    if (seqLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n    const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n    const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n    if (sLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n    return { r: int.decode(rBytes), s: int.decode(sBytes) };\n  },\n  hexFromSig(sig: { r: bigint; s: bigint }): string {\n    const { _tlv: tlv, _int: int } = DER;\n    const rs = tlv.encode(0x02, int.encode(sig.r));\n    const ss = tlv.encode(0x02, int.encode(sig.s));\n    const seq = rs + ss;\n    return tlv.encode(0x30, seq);\n  },\n};\nObject.freeze(DER._tlv);\nObject.freeze(DER._int);\nObject.freeze(DER);\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4);\n\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * See {@link WeierstrassOpts}.\n * @param params - Curve parameters. See {@link WeierstrassOpts}.\n * @param extraOpts - Optional helpers and overrides. See {@link WeierstrassExtraOpts}.\n * @returns Weierstrass point constructor.\n * @throws If the curve parameters, overrides, or point codecs are invalid. {@link Error}\n *\n * @example\n * Construct a point type from explicit Weierstrass curve parameters.\n *\n * ```js\n * const opts = {\n *   p: 0xfffffffffffffffffffffffffffffffeffffac73n,\n *   n: 0x100000000000000000001b8fa16dfab9aca16b6b3n,\n *   h: 1n,\n *   a: 0n,\n *   b: 7n,\n *   Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn,\n *   Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen,\n * };\n * const secp160k1_Point = weierstrass(opts);\n * ```\n */\nexport function weierstrass<T>(\n  params: WeierstrassOpts<T>,\n  extraOpts: WeierstrassExtraOpts<T> = {}\n): WeierstrassPointCons<T> {\n  const validated = createCurveFields('weierstrass', params, extraOpts);\n  const Fp = validated.Fp as IField<T>;\n  const Fn = validated.Fn as IField<bigint>;\n  let CURVE = validated.CURVE as WeierstrassOpts<T>;\n  const { h: cofactor, n: CURVE_ORDER } = CURVE;\n  validateObject(\n    extraOpts,\n    {},\n    {\n      allowInfinityPoint: 'boolean',\n      clearCofactor: 'function',\n      isTorsionFree: 'function',\n      fromBytes: 'function',\n      toBytes: 'function',\n      endo: 'object',\n    }\n  );\n\n  // Snapshot constructor-time flags whose later mutation would otherwise change\n  // validity semantics of an already-built point type.\n  const { endo, allowInfinityPoint } = extraOpts;\n  if (endo) {\n    // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });\n    if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {\n      throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n    }\n  }\n\n  const lengths = getWLengths(Fp as TArg<IField<T>>, Fn);\n\n  function assertCompressionIsSupported() {\n    if (!Fp.isOdd) throw new Error('compression is not supported: Field does not have .isOdd()');\n  }\n\n  // Implements IEEE P1363 point encoding\n  function pointToBytes(\n    _c: WeierstrassPointCons<T>,\n    point: WeierstrassPoint<T>,\n    isCompressed: boolean\n  ): TRet<Uint8Array> {\n    // SEC 1 v2.0 \u00A72.3.3 encodes infinity as the single octet 0x00. Only curves\n    // that opt into infinity as a public point value should expose that byte form.\n    if (allowInfinityPoint && point.is0()) return Uint8Array.of(0) as TRet<Uint8Array>;\n    const { x, y } = point.toAffine();\n    const bx = Fp.toBytes(x);\n    abool(isCompressed, 'isCompressed');\n    if (isCompressed) {\n      assertCompressionIsSupported();\n      const hasEvenY = !Fp.isOdd!(y);\n      return concatBytes(pprefix(hasEvenY), bx) as TRet<Uint8Array>;\n    } else {\n      return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y)) as TRet<Uint8Array>;\n    }\n  }\n  function pointFromBytes(bytes: TArg<Uint8Array>) {\n    abytes(bytes, undefined, 'Point');\n    const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n    const length = bytes.length;\n    const head = bytes[0];\n    const tail = bytes.subarray(1);\n    if (allowInfinityPoint && length === 1 && head === 0x00) return { x: Fp.ZERO, y: Fp.ZERO };\n    // SEC 1 v2.0 \u00A72.3.4 decodes 0x00 as infinity, but \u00A73.2.2 public-key validation\n    // rejects infinity. We therefore keep 0x00 rejected by default because callers\n    // reuse this parser as the strict public-key boundary, and only admit it when\n    // the curve explicitly opts into infinity as a public point value. secp256k1\n    // crosstests show OpenSSL raw point codecs accept 0x00 too.\n    // No actual validation is done here: use .assertValidity()\n    if (length === comp && (head === 0x02 || head === 0x03)) {\n      const x = Fp.fromBytes(tail);\n      if (!Fp.isValid(x)) throw new Error('bad point: is not on curve, wrong x');\n      const y2 = weierstrassEquation(x); // y\u00B2 = x\u00B3 + ax + b\n      let y: T;\n      try {\n        y = Fp.sqrt(y2); // y = y\u00B2 ^ (p+1)/4\n      } catch (sqrtError) {\n        const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n        throw new Error('bad point: is not on curve, sqrt error' + err);\n      }\n      assertCompressionIsSupported();\n      const evenY = Fp.isOdd!(y);\n      const evenH = (head & 1) === 1; // ECDSA-specific\n      if (evenH !== evenY) y = Fp.neg(y);\n      return { x, y };\n    } else if (length === uncomp && head === 0x04) {\n      // TODO: more checks\n      const L = Fp.BYTES;\n      const x = Fp.fromBytes(tail.subarray(0, L));\n      const y = Fp.fromBytes(tail.subarray(L, L * 2));\n      if (!isValidXY(x, y)) throw new Error('bad point: is not on curve');\n      return { x, y };\n    } else {\n      throw new Error(\n        `bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`\n      );\n    }\n  }\n\n  const encodePoint = extraOpts.toBytes === undefined ? pointToBytes : extraOpts.toBytes;\n  const decodePoint = extraOpts.fromBytes === undefined ? pointFromBytes : extraOpts.fromBytes;\n  function weierstrassEquation(x: T): T {\n    const x2 = Fp.sqr(x); // x * x\n    const x3 = Fp.mul(x2, x); // x\u00B2 * x\n    return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x\u00B3 + a * x + b\n  }\n\n  // TODO: move top-level\n  /** Checks whether equation holds for given x, y: y\u00B2 == x\u00B3 + ax + b */\n  function isValidXY(x: T, y: T): boolean {\n    const left = Fp.sqr(y); // y\u00B2\n    const right = weierstrassEquation(x); // x\u00B3 + ax + b\n    return Fp.eql(left, right);\n  }\n\n  // Keep constructor-time generator validation cheap: callers are responsible for supplying the\n  // correct prime-order base point, while eager subgroup checks here would slow heavy module imports.\n  // Test 1: equation y\u00B2 = x\u00B3 + ax + b should work for generator point.\n  if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n  // Test 2: discriminant \u0394 part should be non-zero: 4a\u00B3 + 27b\u00B2 != 0.\n  // Guarantees curve is genus-1, smooth (non-singular).\n  const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n  const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n  if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b');\n\n  /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n  function acoord(title: string, n: T, banZero = false) {\n    if (!Fp.isValid(n) || (banZero && Fp.is0(n))) throw new Error(`bad point coordinate ${title}`);\n    return n;\n  }\n\n  function aprjpoint(other: unknown): asserts other is Point {\n    if (!(other instanceof Point)) throw new Error('Weierstrass Point expected');\n  }\n\n  function splitEndoScalarN(k: bigint) {\n    if (!endo || !endo.basises) throw new Error('no endo');\n    return _splitEndoScalar(k, endo.basises, Fn.ORDER);\n  }\n\n  function finishEndo(\n    endoBeta: EndomorphismOpts['beta'],\n    k1p: Point,\n    k2p: Point,\n    k1neg: boolean,\n    k2neg: boolean\n  ) {\n    k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);\n    k1p = negateCt(k1neg, k1p);\n    k2p = negateCt(k2neg, k2p);\n    return k1p.add(k2p);\n  }\n\n  /**\n   * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) \u220B (x=X/Z, y=Y/Z).\n   * Default Point works in 2d / affine coordinates: (x, y).\n   * We're doing calculations in projective, because its operations don't require costly inversion.\n   */\n  class Point implements WeierstrassPoint<T> {\n    // base / generator point\n    static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n    // zero / infinity / identity point\n    static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n    // math field\n    static readonly Fp = Fp;\n    // scalar field\n    static readonly Fn = Fn;\n\n    readonly X: T;\n    readonly Y: T;\n    readonly Z: T;\n\n    /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n    constructor(X: T, Y: T, Z: T) {\n      this.X = acoord('x', X);\n      // This is not just about ZERO / infinity: ambient curves can have real\n      // finite points with y=0. Those points are 2-torsion, so they cannot lie\n      // in the odd prime-order subgroups this point type is meant to represent.\n      this.Y = acoord('y', Y, true);\n      this.Z = acoord('z', Z);\n      Object.freeze(this);\n    }\n\n    static CURVE(): WeierstrassOpts<T> {\n      return CURVE;\n    }\n\n    /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\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      // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n      if (Fp.is0(x) && Fp.is0(y)) return Point.ZERO;\n      return new Point(x, y, Fp.ONE);\n    }\n\n    static fromBytes(bytes: TArg<Uint8Array>): Point {\n      const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n      P.assertValidity();\n      return P;\n    }\n\n    static fromHex(hex: string): Point {\n      return Point.fromBytes(hexToBytes(hex));\n    }\n\n    get x(): T {\n      return this.toAffine().x;\n    }\n    get y(): T {\n      return this.toAffine().y;\n    }\n\n    /**\n     *\n     * @param windowSize\n     * @param isLazy - true will defer table computation until the first multiplication\n     * @returns\n     */\n    precompute(windowSize: number = 8, isLazy = true): Point {\n      wnaf.createCache(this, windowSize);\n      if (!isLazy) this.multiply(_3n); // random number\n      return this;\n    }\n\n    // TODO: return `this`\n    /** A point on curve is valid if it conforms to equation. */\n    assertValidity(): void {\n      const p = this;\n      if (p.is0()) {\n        // (0, 1, 0) aka ZERO is invalid in most contexts.\n        // In BLS, ZERO can be serialized, so we allow it.\n        // Keep the accepted infinity encoding canonical: projective-equivalent (X, Y, 0) points\n        // like (1, 1, 0) compare equal to ZERO, but only (0, 1, 0) should pass this guard.\n        if (extraOpts.allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z))\n          return;\n        throw new Error('bad point: ZERO');\n      }\n      // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n      const { x, y } = p.toAffine();\n      if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not field elements');\n      if (!isValidXY(x, y)) throw new Error('bad point: equation left != right');\n      if (!p.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n    }\n\n    hasEvenY(): boolean {\n      const { y } = this.toAffine();\n      if (!Fp.isOdd) throw new Error(\"Field doesn't support isOdd\");\n      return !Fp.isOdd(y);\n    }\n\n    /** Compare one point to another. */\n    equals(other: WeierstrassPoint<T>): boolean {\n      aprjpoint(other);\n      const { X: X1, Y: Y1, Z: Z1 } = this;\n      const { X: X2, Y: Y2, Z: Z2 } = other;\n      const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n      const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n      return U1 && U2;\n    }\n\n    /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n    negate(): Point {\n      return new Point(this.X, Fp.neg(this.Y), this.Z);\n    }\n\n    // Renes-Costello-Batina exception-free doubling formula.\n    // There is 30% faster Jacobian formula, but it is not complete.\n    // https://eprint.iacr.org/2015/1060, algorithm 3\n    // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n    double() {\n      const { a, b } = CURVE;\n      const b3 = Fp.mul(b, _3n);\n      const { X: X1, Y: Y1, Z: Z1 } = this;\n      let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n      let t0 = Fp.mul(X1, X1); // step 1\n      let t1 = Fp.mul(Y1, Y1);\n      let t2 = Fp.mul(Z1, Z1);\n      let t3 = Fp.mul(X1, Y1);\n      t3 = Fp.add(t3, t3); // step 5\n      Z3 = Fp.mul(X1, Z1);\n      Z3 = Fp.add(Z3, Z3);\n      X3 = Fp.mul(a, Z3);\n      Y3 = Fp.mul(b3, t2);\n      Y3 = Fp.add(X3, Y3); // step 10\n      X3 = Fp.sub(t1, Y3);\n      Y3 = Fp.add(t1, Y3);\n      Y3 = Fp.mul(X3, Y3);\n      X3 = Fp.mul(t3, X3);\n      Z3 = Fp.mul(b3, Z3); // step 15\n      t2 = Fp.mul(a, t2);\n      t3 = Fp.sub(t0, t2);\n      t3 = Fp.mul(a, t3);\n      t3 = Fp.add(t3, Z3);\n      Z3 = Fp.add(t0, t0); // step 20\n      t0 = Fp.add(Z3, t0);\n      t0 = Fp.add(t0, t2);\n      t0 = Fp.mul(t0, t3);\n      Y3 = Fp.add(Y3, t0);\n      t2 = Fp.mul(Y1, Z1); // step 25\n      t2 = Fp.add(t2, t2);\n      t0 = Fp.mul(t2, t3);\n      X3 = Fp.sub(X3, t0);\n      Z3 = Fp.mul(t2, t1);\n      Z3 = Fp.add(Z3, Z3); // step 30\n      Z3 = Fp.add(Z3, Z3);\n      return new Point(X3, Y3, Z3);\n    }\n\n    // Renes-Costello-Batina exception-free addition formula.\n    // There is 30% faster Jacobian formula, but it is not complete.\n    // https://eprint.iacr.org/2015/1060, algorithm 1\n    // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n    add(other: WeierstrassPoint<T>): Point {\n      aprjpoint(other);\n      const { X: X1, Y: Y1, Z: Z1 } = this;\n      const { X: X2, Y: Y2, Z: Z2 } = other;\n      let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n      const a = CURVE.a;\n      const b3 = Fp.mul(CURVE.b, _3n);\n      let t0 = Fp.mul(X1, X2); // step 1\n      let t1 = Fp.mul(Y1, Y2);\n      let t2 = Fp.mul(Z1, Z2);\n      let t3 = Fp.add(X1, Y1);\n      let t4 = Fp.add(X2, Y2); // step 5\n      t3 = Fp.mul(t3, t4);\n      t4 = Fp.add(t0, t1);\n      t3 = Fp.sub(t3, t4);\n      t4 = Fp.add(X1, Z1);\n      let t5 = Fp.add(X2, Z2); // step 10\n      t4 = Fp.mul(t4, t5);\n      t5 = Fp.add(t0, t2);\n      t4 = Fp.sub(t4, t5);\n      t5 = Fp.add(Y1, Z1);\n      X3 = Fp.add(Y2, Z2); // step 15\n      t5 = Fp.mul(t5, X3);\n      X3 = Fp.add(t1, t2);\n      t5 = Fp.sub(t5, X3);\n      Z3 = Fp.mul(a, t4);\n      X3 = Fp.mul(b3, t2); // step 20\n      Z3 = Fp.add(X3, Z3);\n      X3 = Fp.sub(t1, Z3);\n      Z3 = Fp.add(t1, Z3);\n      Y3 = Fp.mul(X3, Z3);\n      t1 = Fp.add(t0, t0); // step 25\n      t1 = Fp.add(t1, t0);\n      t2 = Fp.mul(a, t2);\n      t4 = Fp.mul(b3, t4);\n      t1 = Fp.add(t1, t2);\n      t2 = Fp.sub(t0, t2); // step 30\n      t2 = Fp.mul(a, t2);\n      t4 = Fp.add(t4, t2);\n      t0 = Fp.mul(t1, t4);\n      Y3 = Fp.add(Y3, t0);\n      t0 = Fp.mul(t5, t4); // step 35\n      X3 = Fp.mul(t3, X3);\n      X3 = Fp.sub(X3, t0);\n      t0 = Fp.mul(t3, t1);\n      Z3 = Fp.mul(t5, Z3);\n      Z3 = Fp.add(Z3, t0); // step 40\n      return new Point(X3, Y3, Z3);\n    }\n\n    subtract(other: WeierstrassPoint<T>) {\n      // Validate before calling `negate()` so wrong inputs fail with the point guard\n      // instead of leaking a foreign `negate()` error.\n      aprjpoint(other);\n      return this.add(other.negate());\n    }\n\n    is0(): boolean {\n      return this.equals(Point.ZERO);\n    }\n\n    /**\n     * Constant time multiplication.\n     * Uses wNAF method. Windowed method may be 10% faster,\n     * but takes 2x longer to generate and consumes 2x memory.\n     * Uses precomputes when available.\n     * Uses endomorphism for Koblitz curves.\n     * @param scalar - by which the point would be multiplied\n     * @returns New point\n     */\n    multiply(scalar: bigint): Point {\n      const { endo } = extraOpts;\n      // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.\n      // In key/signature-style callers, those values usually mean broken hash/scalar plumbing,\n      // and failing closed is safer than silently producing the identity point.\n      if (!Fn.isValidNot0(scalar)) throw new RangeError('invalid scalar: out of range'); // 0 is invalid\n      let point: Point, fake: Point; // Fake point is used to const-time mult\n      const mul = (n: bigint) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));\n      /** See docs for {@link EndomorphismOpts} */\n      if (endo) {\n        const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);\n        const { p: k1p, f: k1f } = mul(k1);\n        const { p: k2p, f: k2f } = mul(k2);\n        fake = k1f.add(k2f);\n        point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);\n      } else {\n        const { p, f } = mul(scalar);\n        point = p;\n        fake = f;\n      }\n      // Normalize `z` for both points, but return only real one\n      return normalizeZ(Point, [point, fake])[0];\n    }\n\n    /**\n     * Non-constant-time multiplication. Uses double-and-add algorithm.\n     * It's faster, but should only be used when you don't care about\n     * an exposed secret key e.g. sig verification, which works over *public* keys.\n     */\n    multiplyUnsafe(scalar: bigint): Point {\n      const { endo } = extraOpts;\n      const p = this as Point;\n      const sc = scalar;\n      // Public-scalar callers may need 0, but n and larger values stay rejected here too.\n      // Reducing them mod n would turn bad caller input into an accidental identity point.\n      if (!Fn.isValid(sc)) throw new RangeError('invalid scalar: out of range'); // 0 is valid\n      if (sc === _0n || p.is0()) return Point.ZERO; // 0\n      if (sc === _1n) return p; // 1\n      if (wnaf.hasCache(this)) return this.multiply(sc); // precomputes\n      // We don't have method for double scalar multiplication (aP + bQ):\n      // Even with using Strauss-Shamir trick, it's 35% slower than na\u00EFve mul+add.\n      if (endo) {\n        const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);\n        const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe\n        return finishEndo(endo.beta, p1, p2, k1neg, k2neg);\n      } else {\n        return wnaf.unsafe(p, sc);\n      }\n    }\n\n    /**\n     * Converts Projective point to affine (x, y) coordinates.\n     * (X, Y, Z) \u220B (x=X/Z, y=Y/Z).\n     * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n     */\n    toAffine(invertedZ?: T): AffinePoint<T> {\n      const p = this;\n      let iz = invertedZ;\n      const { X, Y, Z } = p;\n      // Fast-path for normalized points\n      if (Fp.eql(Z, Fp.ONE)) return { x: X, y: Y };\n      const is0 = p.is0();\n      // If invZ was 0, we return zero point. However we still want to execute\n      // all operations, so we replace invZ with a random number, 1.\n      if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(Z);\n      const x = Fp.mul(X, iz);\n      const y = Fp.mul(Y, iz);\n      const zz = Fp.mul(Z, iz);\n      if (is0) return { x: Fp.ZERO, y: Fp.ZERO };\n      if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid');\n      return { x, y };\n    }\n\n    /**\n     * Checks whether Point is free of torsion elements (is in prime subgroup).\n     * Always torsion-free for cofactor=1 curves.\n     */\n    isTorsionFree(): boolean {\n      const { isTorsionFree } = extraOpts;\n      if (cofactor === _1n) return true;\n      if (isTorsionFree) return isTorsionFree(Point, this);\n      return wnaf.unsafe(this, CURVE_ORDER).is0();\n    }\n\n    clearCofactor(): Point {\n      const { clearCofactor } = extraOpts;\n      if (cofactor === _1n) return this; // Fast-path\n      if (clearCofactor) return clearCofactor(Point, this) as Point;\n      // Default fallback assumes the cofactor fits the usual subgroup-scalar\n      // multiplyUnsafe() contract. Curves with larger / structured cofactors\n      // should define a clearCofactor override anyway (e.g. psi/Frobenius maps).\n      return this.multiplyUnsafe(cofactor);\n    }\n\n    isSmallOrder(): boolean {\n      if (cofactor === _1n) return this.is0(); // Fast-path\n      return this.clearCofactor().is0();\n    }\n\n    toBytes(isCompressed = true): TRet<Uint8Array> {\n      abool(isCompressed, 'isCompressed');\n      // Same policy as pointFromBytes(): keep ZERO out of the default byte surface because\n      // callers use these encodings as public keys, where SEC 1 validation rejects infinity.\n      this.assertValidity();\n      return encodePoint(Point, this, isCompressed);\n    }\n\n    toHex(isCompressed = true): string {\n      return bytesToHex(this.toBytes(isCompressed));\n    }\n\n    toString() {\n      return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n    }\n  }\n  const bits = Fn.BITS;\n  const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);\n  // Tiny toy curves can have scalar fields narrower than 8 bits. Skip the\n  // eager W=8 cache there instead of rejecting an otherwise valid constructor.\n  if (bits >= 8) Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n  Object.freeze(Point.prototype);\n  Object.freeze(Point);\n  return Point;\n}\n\n/** Parsed ECDSA signature with helpers for recovery and re-encoding. */\nexport interface ECDSASignature {\n  /** Signature component `r`. */\n  readonly r: bigint;\n  /** Signature component `s`. */\n  readonly s: bigint;\n  /** Optional recovery bit for recoverable signatures. */\n  readonly recovery?: number;\n  /**\n   * Return a copy of the signature with a recovery bit attached.\n   * @param recovery - Recovery bit to attach.\n   * @returns Signature with an attached recovery bit.\n   */\n  addRecoveryBit(recovery: number): ECDSASignature & { readonly recovery: number };\n  /**\n   * Check whether the signature uses the high-S half-order.\n   * @returns Whether the signature uses the high-S half-order.\n   */\n  hasHighS(): boolean;\n  /**\n   * Recover the public key from the hashed message and recovery bit.\n   * @param messageHash - Hashed message bytes.\n   * @returns Recovered public-key point.\n   */\n  recoverPublicKey(messageHash: TArg<Uint8Array>): WeierstrassPoint<bigint>;\n  /**\n   * Encode the signature into bytes.\n   * @param format - Signature encoding to produce.\n   * @returns Encoded signature bytes.\n   */\n  toBytes(format?: string): TRet<Uint8Array>;\n  /**\n   * Encode the signature into hex.\n   * @param format - Signature encoding to produce.\n   * @returns Encoded signature hex.\n   */\n  toHex(format?: string): string;\n}\n/** Constructor and decoding helpers for ECDSA signatures. */\nexport type ECDSASignatureCons = {\n  /** Create a signature from `r`, `s`, and an optional recovery bit. */\n  new (r: bigint, s: bigint, recovery?: number): ECDSASignature;\n  /**\n   * Decode a signature from bytes.\n   * @param bytes - Encoded signature bytes.\n   * @param format - Signature encoding to parse.\n   * @returns Parsed signature.\n   */\n  fromBytes(bytes: TArg<Uint8Array>, format?: ECDSASignatureFormat): ECDSASignature;\n  /**\n   * Decode a signature from hex.\n   * @param hex - Encoded signature hex.\n   * @param format - Signature encoding to parse.\n   * @returns Parsed signature.\n   */\n  fromHex(hex: string, format?: ECDSASignatureFormat): ECDSASignature;\n};\n\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY: boolean): TRet<Uint8Array> {\n  return Uint8Array.of(hasEvenY ? 0x02 : 0x03) as TRet<Uint8Array>;\n}\n\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * RFC 9380 expects callers to provide `v != 0`; this helper does not enforce it.\n * @param Fp - Field implementation.\n * @param Z - Simplified SWU map parameter.\n * @returns Square-root ratio helper.\n * @example\n * Build the square-root ratio helper used by SWU map implementations.\n *\n * ```ts\n * import { SWUFpSqrtRatio } from '@noble/curves/abstract/weierstrass.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrtRatio = SWUFpSqrtRatio(Fp, 3n);\n * const out = sqrtRatio(4n, 1n);\n * ```\n */\nexport function SWUFpSqrtRatio<T>(\n  Fp: TArg<IField<T>>,\n  Z: T\n): (u: T, v: T) => { isValid: boolean; value: T } {\n  // Fail with the usual field-shape error before touching pow/cmov on malformed field shims.\n  const F = validateField(Fp as IField<T>) as IField<T>;\n  // Generic implementation\n  const q = F.ORDER;\n  let l = _0n;\n  for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n;\n  const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n  // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n  // 2n ** c1 == 2n << (c1-1)\n  const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n  const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n  const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1)  # Integer arithmetic\n  const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2            # Integer arithmetic\n  const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1                # Integer arithmetic\n  const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1)                  # Integer arithmetic\n  const c6 = F.pow(Z, c2); // 6. c6 = Z^c2\n  const c7 = F.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n  // RFC 9380 Appendix F.2.1.1 defines sqrt_ratio(u, v) only for v != 0.\n  // We keep v=0 on the regular result path with isValid=false instead of\n  // throwing so the helper stays closer to the RFC's fixed control flow.\n  let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => {\n    let tv1 = c6; // 1. tv1 = c6\n    let tv2 = F.pow(v, c4); // 2. tv2 = v^c4\n    let tv3 = F.sqr(tv2); // 3. tv3 = tv2^2\n    tv3 = F.mul(tv3, v); // 4. tv3 = tv3 * v\n    let tv5 = F.mul(u, tv3); // 5. tv5 = u * tv3\n    tv5 = F.pow(tv5, c3); // 6. tv5 = tv5^c3\n    tv5 = F.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n    tv2 = F.mul(tv5, v); // 8. tv2 = tv5 * v\n    tv3 = F.mul(tv5, u); // 9. tv3 = tv5 * u\n    let tv4 = F.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n    tv5 = F.pow(tv4, c5); // 11. tv5 = tv4^c5\n    let isQR = F.eql(tv5, F.ONE); // 12. isQR = tv5 == 1\n    tv2 = F.mul(tv3, c7); // 13. tv2 = tv3 * c7\n    tv5 = F.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n    tv3 = F.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n    tv4 = F.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n    // 17. for i in (c1, c1 - 1, ..., 2):\n    for (let i = c1; i > _1n; i--) {\n      let tv5 = i - _2n; // 18.    tv5 = i - 2\n      tv5 = _2n << (tv5 - _1n); // 19.    tv5 = 2^tv5\n      let tvv5 = F.pow(tv4, tv5); // 20.    tv5 = tv4^tv5\n      const e1 = F.eql(tvv5, F.ONE); // 21.    e1 = tv5 == 1\n      tv2 = F.mul(tv3, tv1); // 22.    tv2 = tv3 * tv1\n      tv1 = F.mul(tv1, tv1); // 23.    tv1 = tv1 * tv1\n      tvv5 = F.mul(tv4, tv1); // 24.    tv5 = tv4 * tv1\n      tv3 = F.cmov(tv2, tv3, e1); // 25.    tv3 = CMOV(tv2, tv3, e1)\n      tv4 = F.cmov(tvv5, tv4, e1); // 26.    tv4 = CMOV(tv5, tv4, e1)\n    }\n    // RFC 9380 Appendix F.2.1.1 defines sqrt_ratio(u, v) for v != 0.\n    // When u = 0 and v != 0, u / v = 0 is square and the computed root is\n    // still 0, so widen only the final flag and keep the full control flow.\n    return { isValid: !F.is0(v) && (isQR || F.is0(u)), value: tv3 };\n  };\n  if (F.ORDER % _4n === _3n) {\n    // sqrt_ratio_3mod4(u, v)\n    const c1 = (F.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4     # Integer arithmetic\n    const c2 = F.sqrt(F.neg(Z)); // 2. c2 = sqrt(-Z)\n    sqrtRatio = (u: T, v: T) => {\n      let tv1 = F.sqr(v); // 1. tv1 = v^2\n      const tv2 = F.mul(u, v); // 2. tv2 = u * v\n      tv1 = F.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n      let y1 = F.pow(tv1, c1); // 4. y1 = tv1^c1\n      y1 = F.mul(y1, tv2); // 5. y1 = y1 * tv2\n      const y2 = F.mul(y1, c2); // 6. y2 = y1 * c2\n      const tv3 = F.mul(F.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n      const isQR = F.eql(tv3, u); // 9. isQR = tv3 == u\n      let y = F.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n      return { isValid: !F.is0(v) && isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n    };\n  }\n  // No curves uses that\n  // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n  return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2 | RFC 9380 section 6.6.2}.\n * @param Fp - Field implementation.\n * @param opts - SWU parameters:\n *   - `A`: Curve parameter `A`.\n *   - `B`: Curve parameter `B`.\n *   - `Z`: Simplified SWU map parameter.\n * @returns Deterministic map-to-curve function.\n * @throws If the SWU parameters are invalid or the field lacks the required helpers. {@link Error}\n * @example\n * Map one field element to a Weierstrass curve point with the SWU recipe.\n *\n * ```ts\n * import { mapToCurveSimpleSWU } from '@noble/curves/abstract/weierstrass.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const map = mapToCurveSimpleSWU(Fp, { A: 1n, B: 2n, Z: 3n });\n * const point = map(5n);\n * ```\n */\nexport function mapToCurveSimpleSWU<T>(\n  Fp: TArg<IField<T>>,\n  opts: {\n    A: T;\n    B: T;\n    Z: T;\n  }\n): (u: T) => { x: T; y: T } {\n  const F = validateField(Fp as IField<T>) as IField<T>;\n  const { A, B, Z } = opts;\n  if (!F.isValidNot0(A) || !F.isValidNot0(B) || !F.isValid(Z))\n    throw new Error('mapToCurveSimpleSWU: invalid opts');\n  // RFC 9380 \u00A76.6.2 and Appendix H.2 require:\n  // 1. Z is non-square in F\n  // 2. Z != -1 in F\n  // 3. g(x) - Z is irreducible over F\n  // 4. g(B / (Z * A)) is square in F\n  // We can enforce 1, 2, and 4 with the current field API.\n  // Criterion 3 is not checked here because generic `IField<T>` does not expose\n  // polynomial-ring / irreducibility operations, and this helper is used for\n  // both prime and extension fields.\n  if (F.eql(Z, F.neg(F.ONE)) || FpIsSquare(F, Z))\n    throw new Error('mapToCurveSimpleSWU: invalid opts');\n  // RFC 9380 Appendix H.2 criterion 4: g(B / (Z * A)) is square in F.\n  // x = B / (Z * A)\n  const x = F.mul(B, F.inv(F.mul(Z, A)));\n  // g(x) = x^3 + A*x + B\n  const gx = F.add(F.add(F.mul(F.sqr(x), x), F.mul(A, x)), B);\n  if (!FpIsSquare(F, gx)) throw new Error('mapToCurveSimpleSWU: invalid opts');\n  const sqrtRatio = SWUFpSqrtRatio(F, Z);\n  if (!F.isOdd) throw new Error('Field does not have .isOdd()');\n  // Input: u, an element of F.\n  // Output: (x, y), a point on E.\n  return (u: T): { x: T; y: T } => {\n    // prettier-ignore\n    let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n    tv1 = F.sqr(u); // 1.  tv1 = u^2\n    tv1 = F.mul(tv1, Z); // 2.  tv1 = Z * tv1\n    tv2 = F.sqr(tv1); // 3.  tv2 = tv1^2\n    tv2 = F.add(tv2, tv1); // 4.  tv2 = tv2 + tv1\n    tv3 = F.add(tv2, F.ONE); // 5.  tv3 = tv2 + 1\n    tv3 = F.mul(tv3, B); // 6.  tv3 = B * tv3\n    tv4 = F.cmov(Z, F.neg(tv2), !F.eql(tv2, F.ZERO)); // 7.  tv4 = CMOV(Z, -tv2, tv2 != 0)\n    tv4 = F.mul(tv4, A); // 8.  tv4 = A * tv4\n    tv2 = F.sqr(tv3); // 9.  tv2 = tv3^2\n    tv6 = F.sqr(tv4); // 10. tv6 = tv4^2\n    tv5 = F.mul(tv6, A); // 11. tv5 = A * tv6\n    tv2 = F.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n    tv2 = F.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n    tv6 = F.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n    tv5 = F.mul(tv6, B); // 15. tv5 = B * tv6\n    tv2 = F.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n    x = F.mul(tv1, tv3); // 17.   x = tv1 * tv3\n    const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n    y = F.mul(tv1, u); // 19.   y = tv1 * u  -> Z * u^3 * y1\n    y = F.mul(y, value); // 20.   y = y * y1\n    x = F.cmov(x, tv3, isValid); // 21.   x = CMOV(x, tv3, is_gx1_square)\n    y = F.cmov(y, value, isValid); // 22.   y = CMOV(y, y1, is_gx1_square)\n    const e1 = F.isOdd!(u) === F.isOdd!(y); // 23.  e1 = sgn0(u) == sgn0(y)\n    y = F.cmov(F.neg(y), y, e1); // 24.   y = CMOV(-y, y, e1)\n    const tv4_inv = FpInvertBatch(F, [tv4], true)[0];\n    x = F.mul(x, tv4_inv); // 25.   x = x / tv4\n    return { x, y };\n  };\n}\n\nfunction getWLengths<T>(Fp: TArg<IField<T>>, Fn: TArg<IField<bigint>>) {\n  return {\n    secretKey: Fn.BYTES,\n    publicKey: 1 + Fp.BYTES,\n    publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n    publicKeyHasPrefix: true,\n    // Raw compact `(r || s)` signature width; DER and recovered signatures use\n    // different lengths outside this helper.\n    signature: 2 * Fn.BYTES,\n  };\n}\n\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n * @param Point - Weierstrass point constructor.\n * @param ecdhOpts - Optional randomness helpers:\n *   - `randomBytes` (optional): Optional RNG override.\n * @returns ECDH helper namespace.\n * @example\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n *\n * ```ts\n * import { ecdh } from '@noble/curves/abstract/weierstrass.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const dh = ecdh(p256.Point);\n * const alice = dh.keygen();\n * const shared = dh.getSharedSecret(alice.secretKey, alice.publicKey);\n * ```\n */\nexport function ecdh(\n  Point: WeierstrassPointCons<bigint>,\n  ecdhOpts: TArg<{ randomBytes?: (bytesLength?: number) => TRet<Uint8Array> }> = {}\n): ECDH {\n  const { Fn } = Point;\n  const randomBytes_ = ecdhOpts.randomBytes === undefined ? wcRandomBytes : ecdhOpts.randomBytes;\n  // Keep the advertised seed length aligned with mapHashToField(), which keeps a hard 16-byte\n  // minimum even on toy curves.\n  const lengths = Object.assign(getWLengths(Point.Fp, Fn), {\n    seed: Math.max(getMinHashLength(Fn.ORDER), 16),\n  });\n\n  function isValidSecretKey(secretKey: TArg<Uint8Array>) {\n    try {\n      const num = Fn.fromBytes(secretKey);\n      return Fn.isValidNot0(num);\n    } catch (error) {\n      return false;\n    }\n  }\n\n  function isValidPublicKey(publicKey: TArg<Uint8Array>, isCompressed?: boolean): boolean {\n    const { publicKey: comp, publicKeyUncompressed } = lengths;\n    try {\n      const l = publicKey.length;\n      if (isCompressed === true && l !== comp) return false;\n      if (isCompressed === false && l !== publicKeyUncompressed) return false;\n      return !!Point.fromBytes(publicKey);\n    } catch (error) {\n      return false;\n    }\n  }\n\n  /**\n   * Produces cryptographically secure secret key from random of size\n   * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n   */\n  function randomSecretKey(seed?: TArg<Uint8Array>): TRet<Uint8Array> {\n    seed = seed === undefined ? randomBytes_(lengths.seed) : seed;\n    return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER) as TRet<Uint8Array>;\n  }\n\n  /**\n   * Computes public key for a secret key. Checks for validity of the secret key.\n   * @param isCompressed - whether to return compact (default), or full key\n   * @returns Public key, full when isCompressed=false; short when isCompressed=true\n   */\n  function getPublicKey(secretKey: TArg<Uint8Array>, isCompressed = true): TRet<Uint8Array> {\n    return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);\n  }\n\n  /**\n   * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n   */\n  function isProbPub(item: TArg<Uint8Array>): boolean | undefined {\n    const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n    const allowedLengths = (Fn as { _lengths?: readonly number[] })._lengths;\n    if (!isBytes(item)) return undefined;\n    const l = abytes(item, undefined, 'key').length;\n    const isPub = l === publicKey || l === publicKeyUncompressed;\n    const isSec = l === secretKey || !!allowedLengths?.includes(l);\n    // P-521 accepts both 65- and 66-byte secret keys, so overlapping lengths stay ambiguous.\n    if (isPub && isSec) return undefined;\n    return isPub;\n  }\n\n  /**\n   * ECDH (Elliptic Curve Diffie Hellman).\n   * Computes encoded shared point from secret key A and public key B.\n   * Checks: 1) secret key validity 2) shared key is on-curve.\n   * Does NOT hash the result or expose the SEC 1 x-coordinate-only `z`.\n   * Returns the encoded shared point on purpose: callers that need `x_P`\n   * can derive it from the encoded point, but `x_P` alone cannot recover the\n   * point/parity back.\n   * This helper only exposes the fully validated public-key path, not cofactor DH.\n   * @param isCompressed - whether to return compact (default), or full key\n   * @returns shared point encoding\n   */\n  function getSharedSecret(\n    secretKeyA: TArg<Uint8Array>,\n    publicKeyB: TArg<Uint8Array>,\n    isCompressed = true\n  ): TRet<Uint8Array> {\n    if (isProbPub(secretKeyA) === true) throw new Error('first arg must be private key');\n    if (isProbPub(publicKeyB) === false) throw new Error('second arg must be public key');\n    const s = Fn.fromBytes(secretKeyA);\n    const b = Point.fromBytes(publicKeyB); // checks for being on-curve\n    return b.multiply(s).toBytes(isCompressed);\n  }\n\n  const utils = {\n    isValidSecretKey,\n    isValidPublicKey,\n    randomSecretKey,\n  };\n  const keygen = createKeygen(randomSecretKey, getPublicKey);\n  Object.freeze(utils);\n  Object.freeze(lengths);\n\n  return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n *\n * @param Point - created using {@link weierstrass} function\n * @param hash - used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash)\n * @param ecdsaOpts - rarely needed, see {@link ECDSAOpts}:\n *   - `lowS`: Default low-S policy.\n *   - `hmac`: HMAC implementation used by RFC6979 DRBG.\n *   - `randomBytes`: Optional RNG override.\n *   - `bits2int`: Optional hash-to-int conversion override.\n *   - `bits2int_modN`: Optional hash-to-int-mod-n conversion override.\n *\n * @returns ECDSA helper namespace.\n * @example\n * Create an ECDSA signer/verifier bundle for one curve implementation.\n *\n * ```ts\n * import { ecdsa } from '@noble/curves/abstract/weierstrass.js';\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const p256ecdsa = ecdsa(p256.Point, sha256);\n * const { secretKey, publicKey } = p256ecdsa.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = p256ecdsa.sign(msg, secretKey);\n * const isValid = p256ecdsa.verify(sig, msg, publicKey);\n * ```\n */\nexport function ecdsa(\n  Point: WeierstrassPointCons<bigint>,\n  hash: TArg<CHash>,\n  ecdsaOpts: TArg<ECDSAOpts> = {}\n): ECDSA {\n  // Custom hash / bits2int hooks are treated as pure functions over validated caller-owned bytes.\n  const hash_ = hash as CHash;\n  ahash(hash_);\n  validateObject(\n    ecdsaOpts,\n    {},\n    {\n      hmac: 'function',\n      lowS: 'boolean',\n      randomBytes: 'function',\n      bits2int: 'function',\n      bits2int_modN: 'function',\n    }\n  );\n  ecdsaOpts = Object.assign({}, ecdsaOpts);\n  const randomBytes = ecdsaOpts.randomBytes === undefined ? wcRandomBytes : ecdsaOpts.randomBytes;\n  const hmac =\n    ecdsaOpts.hmac === undefined\n      ? (key: TArg<Uint8Array>, msg: TArg<Uint8Array>) => nobleHmac(hash_, key, msg)\n      : (ecdsaOpts.hmac as HmacFn);\n\n  const { Fp, Fn } = Point;\n  const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n  const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);\n  const defaultSigOpts: Required<ECDSASignOpts> = {\n    prehash: true,\n    lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : true,\n    format: 'compact' as ECDSASignatureFormat,\n    extraEntropy: false,\n  };\n  // SEC 1 4.1.6 public-key recovery tries x = r + jn for j = 0..h. Our recovered-signature\n  // format only stores one overflow bit, so it can only distinguish q.x = r from q.x = r + n.\n  // A third lift would have the form q.x = r + 2n. Since valid ECDSA r is in 1..n-1, the\n  // smallest such lift is 1 + 2n, not 2n.\n  const hasLargeRecoveryLifts = CURVE_ORDER * _2n + _1n < Fp.ORDER;\n\n  function isBiggerThanHalfOrder(number: bigint) {\n    const HALF = CURVE_ORDER >> _1n;\n    return number > HALF;\n  }\n  function validateRS(title: string, num: bigint): bigint {\n    if (!Fn.isValidNot0(num))\n      throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n    return num;\n  }\n  function assertRecoverableCurve(): void {\n    // ECDSA recovery only supports curves where the current recovery id can distinguish\n    // q.x = r and q.x = r + n; larger lifts may need additional `r + n*i` branches.\n    // SEC 1 4.1.6 recovers candidates via x = r + jn, but this format only encodes j = 0 or 1.\n    // The next possible candidate is q.x = r + 2n, and its smallest valid value is 1 + 2n.\n    // To easily get i, we either need to:\n    // a. increase amount of valid recid values (4, 5...); OR\n    // b. prohibit recovered signatures for those curves.\n    if (hasLargeRecoveryLifts)\n      throw new Error('\"recovered\" sig type is not supported for cofactor >2 curves');\n  }\n  function validateSigLength(bytes: TArg<Uint8Array>, format: ECDSASignatureFormat) {\n    validateSigFormat(format);\n    const size = lengths.signature!;\n    const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n    return abytes(bytes, sizer);\n  }\n\n  /**\n   * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n   */\n  class Signature implements ECDSASignature {\n    readonly r: bigint;\n    readonly s: bigint;\n    readonly recovery?: number;\n\n    constructor(r: bigint, s: bigint, recovery?: number) {\n      this.r = validateRS('r', r); // r in [1..N-1];\n      this.s = validateRS('s', s); // s in [1..N-1];\n      if (recovery != null) {\n        assertRecoverableCurve();\n        if (![0, 1, 2, 3].includes(recovery)) throw new Error('invalid recovery id');\n        this.recovery = recovery;\n      }\n      Object.freeze(this);\n    }\n\n    static fromBytes(\n      bytes: TArg<Uint8Array>,\n      format: ECDSASignatureFormat = defaultSigOpts.format\n    ): Signature {\n      validateSigLength(bytes, format);\n      let recid: number | undefined;\n      if (format === 'der') {\n        const { r, s } = DER.toSig(abytes(bytes));\n        return new Signature(r, s);\n      }\n      if (format === 'recovered') {\n        recid = bytes[0];\n        format = 'compact';\n        bytes = bytes.subarray(1);\n      }\n      const L = lengths.signature! / 2;\n      const r = bytes.subarray(0, L);\n      const s = bytes.subarray(L, L * 2);\n      return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n    }\n\n    static fromHex(hex: string, format?: ECDSASignatureFormat) {\n      return this.fromBytes(hexToBytes(hex), format);\n    }\n\n    private assertRecovery(): number {\n      const { recovery } = this;\n      if (recovery == null) throw new Error('invalid recovery id: must be present');\n      return recovery;\n    }\n\n    addRecoveryBit(recovery: number): RecoveredSignature {\n      return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n    }\n\n    // Unlike the top-level helper below, this method expects a digest that has\n    // already been hashed to the curve's message representative.\n    recoverPublicKey(messageHash: TArg<Uint8Array>): WeierstrassPoint<bigint> {\n      const { r, s } = this;\n      const recovery = this.assertRecovery();\n      const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;\n      if (!Fp.isValid(radj)) throw new Error('invalid recovery id: sig.r+curve.n != R.x');\n      const x = Fp.toBytes(radj);\n      const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));\n      const ir = Fn.inv(radj); // r^-1\n      const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash\n      const u1 = Fn.create(-h * ir); // -hr^-1\n      const u2 = Fn.create(s * ir); // sr^-1\n      // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n      const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));\n      if (Q.is0()) throw new Error('invalid recovery: point at infinify');\n      Q.assertValidity();\n      return Q;\n    }\n\n    // Signatures should be low-s, to prevent malleability.\n    hasHighS(): boolean {\n      return isBiggerThanHalfOrder(this.s);\n    }\n\n    toBytes(format: ECDSASignatureFormat = defaultSigOpts.format): TRet<Uint8Array> {\n      validateSigFormat(format);\n      if (format === 'der') return hexToBytes(DER.hexFromSig(this)) as TRet<Uint8Array>;\n      const { r, s } = this;\n      const rb = Fn.toBytes(r);\n      const sb = Fn.toBytes(s);\n      if (format === 'recovered') {\n        assertRecoverableCurve();\n        return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb) as TRet<Uint8Array>;\n      }\n      return concatBytes(rb, sb) as TRet<Uint8Array>;\n    }\n\n    toHex(format?: ECDSASignatureFormat) {\n      return bytesToHex(this.toBytes(format));\n    }\n  }\n  type RecoveredSignature = Signature & { recovery: number };\n  Object.freeze(Signature.prototype);\n  Object.freeze(Signature);\n\n  // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n  // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n  // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n  // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n  const bits2int: (bytes: TArg<Uint8Array>) => bigint =\n    ecdsaOpts.bits2int === undefined\n      ? function bits2int_def(bytes: TArg<Uint8Array>): bigint {\n          // Our custom check \"just in case\", for protection against DoS\n          if (bytes.length > 8192) throw new Error('input is too large');\n          // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n          // for some cases, since bytes.length * 8 is not actual bitLength.\n          const num = bytesToNumberBE(bytes); // check for == u8 done here\n          const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits\n          return delta > 0 ? num >> BigInt(delta) : num;\n        }\n      : (ecdsaOpts.bits2int as (bytes: TArg<Uint8Array>) => bigint);\n  const bits2int_modN: (bytes: TArg<Uint8Array>) => bigint =\n    ecdsaOpts.bits2int_modN === undefined\n      ? function bits2int_modN_def(bytes: TArg<Uint8Array>): bigint {\n          return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n        }\n      : (ecdsaOpts.bits2int_modN as (bytes: TArg<Uint8Array>) => bigint);\n  const ORDER_MASK = bitMask(fnBits);\n  // Pads output with zero as per spec.\n  /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n  function int2octets(num: bigint): TRet<Uint8Array> {\n    aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n    return Fn.toBytes(num) as TRet<Uint8Array>;\n  }\n\n  function validateMsgAndHash(message: TArg<Uint8Array>, prehash: boolean): TRet<Uint8Array> {\n    abytes(message, undefined, 'message');\n    return (\n      prehash ? abytes(hash_(message), undefined, 'prehashed message') : message\n    ) as TRet<Uint8Array>;\n  }\n\n  /**\n   * Steps A, D of RFC6979 3.2.\n   * Creates RFC6979 seed; converts msg/privKey to numbers.\n   * Used only in sign, not in verify.\n   *\n   * Warning: we cannot assume here that message has same amount of bytes as curve order,\n   * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.\n   */\n  function prepSig(\n    message: TArg<Uint8Array>,\n    secretKey: TArg<Uint8Array>,\n    opts: TArg<ECDSASignOpts>\n  ) {\n    const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n    message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n    // We can't later call bits2octets, since nested bits2int is broken for curves\n    // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n    // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n    const h1int = bits2int_modN(message);\n    const d = Fn.fromBytes(secretKey); // validate secret key, convert to bigint\n    if (!Fn.isValidNot0(d)) throw new Error('invalid private key');\n    const seedArgs: TArg<Uint8Array>[] = [int2octets(d), int2octets(h1int)];\n    // extraEntropy. RFC6979 3.6: additional k' (optional).\n    if (extraEntropy != null && extraEntropy !== false) {\n      // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n      // gen random bytes OR pass as-is\n      const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n      seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes\n    }\n    const seed = concatBytes(...seedArgs) as TRet<Uint8Array>; // Step D of RFC6979 3.2\n    const m = h1int; // no need to call bits2int second time here, it is inside truncateHash!\n    // Converts signature params into point w r/s, checks result for validity.\n    // To transform k => Signature:\n    // q = k\u22C5G\n    // r = q.x mod n\n    // s = k^-1(m + rd) mod n\n    // Can use scalar blinding b^-1(bm + bdr) where b \u2208 [1,q\u22121] according to\n    // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n    // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n    function k2sig(kBytes: TArg<Uint8Array>): Signature | undefined {\n      // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n      // Important: all mod() calls here must be done over N\n      const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n      if (!Fn.isValidNot0(k)) return; // Valid scalars (including k) must be in 1..N-1\n      const ik = Fn.inv(k); // k^-1 mod n\n      const q = Point.BASE.multiply(k).toAffine(); // q = k\u22C5G\n      const r = Fn.create(q.x); // r = q.x mod n\n      if (r === _0n) return;\n      const s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n\n      if (s === _0n) return;\n      let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3 when q.x>n)\n      let normS = s;\n      if (lowS && isBiggerThanHalfOrder(s)) {\n        normS = Fn.neg(s); // if lowS was passed, ensure s is always in the bottom half of N\n        recovery ^= 1;\n      }\n      return new Signature(r, normS, hasLargeRecoveryLifts ? undefined : recovery);\n    }\n    return { seed, k2sig };\n  }\n\n  /**\n   * Signs a message or message hash with a secret key.\n   * With the default `prehash: true`, raw message bytes are hashed internally;\n   * only `{ prehash: false }` expects a caller-supplied digest.\n   *\n   * ```\n   * sign(m, d) where\n   *   k = rfc6979_hmac_drbg(m, d)\n   *   (x, y) = G \u00D7 k\n   *   r = x mod n\n   *   s = (m + dr) / k mod n\n   * ```\n   */\n  function sign(\n    message: TArg<Uint8Array>,\n    secretKey: TArg<Uint8Array>,\n    opts: TArg<ECDSASignOpts> = {}\n  ): TRet<Uint8Array> {\n    const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n    const drbg = createHmacDrbg<Signature>(hash_.outputLen, Fn.BYTES, hmac);\n    const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n    return sig.toBytes(opts.format);\n  }\n\n  /**\n   * Verifies a signature against message and public key.\n   * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n   * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n   *\n   * ```\n   * verify(r, s, h, P) where\n   *   u1 = hs^-1 mod n\n   *   u2 = rs^-1 mod n\n   *   R = u1\u22C5G + u2\u22C5P\n   *   mod(R.x, n) == r\n   * ```\n   */\n  function verify(\n    signature: TArg<Uint8Array>,\n    message: TArg<Uint8Array>,\n    publicKey: TArg<Uint8Array>,\n    opts: TArg<ECDSAVerifyOpts> = {}\n  ): boolean {\n    const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n    publicKey = abytes(publicKey, undefined, 'publicKey');\n    message = validateMsgAndHash(message, prehash);\n    if (!isBytes(signature as any)) {\n      const end = signature instanceof Signature ? ', use sig.toBytes()' : '';\n      throw new Error('verify expects Uint8Array signature' + end);\n    }\n    validateSigLength(signature, format); // execute this twice because we want loud error\n    try {\n      const sig = Signature.fromBytes(signature, format);\n      const P = Point.fromBytes(publicKey);\n      if (lowS && sig.hasHighS()) return false;\n      const { r, s } = sig;\n      const h = bits2int_modN(message); // mod n, not mod p\n      const is = Fn.inv(s); // s^-1 mod n\n      const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n      const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n      const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1\u22C5G + u2\u22C5P\n      if (R.is0()) return false;\n      const v = Fn.create(R.x); // v = r.x mod n\n      return v === r;\n    } catch (e) {\n      return false;\n    }\n  }\n\n  function recoverPublicKey(\n    signature: TArg<Uint8Array>,\n    message: TArg<Uint8Array>,\n    opts: TArg<ECDSARecoverOpts> = {}\n  ): TRet<Uint8Array> {\n    // Top-level recovery mirrors `sign()` / `verify()`: it hashes raw message\n    // bytes first unless the caller passes `{ prehash: false }`.\n    const { prehash } = validateSigOpts(opts, defaultSigOpts);\n    message = validateMsgAndHash(message, prehash);\n    return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n  }\n\n  return Object.freeze({\n    keygen,\n    getPublicKey,\n    getSharedSecret,\n    utils,\n    lengths,\n    Point,\n    sign,\n    verify,\n    recoverPublicKey,\n    Signature,\n    hash: hash_,\n  }) satisfies Signer;\n}\n", "/**\n * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism \u03C8,\n * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { createKeygen, type CurveLengths } from './abstract/curve.ts';\nimport {\n  createFROST,\n  type FROST,\n  type FrostPublic,\n  type FrostSecret,\n  type Nonces,\n} from './abstract/frost.ts';\nimport { createHasher, type H2CHasher, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mapHashToField, pow2 } from './abstract/modular.ts';\nimport {\n  type ECDSA,\n  ecdsa,\n  type EndomorphismOpts,\n  mapToCurveSimpleSWU,\n  type WeierstrassPoint as PointType,\n  weierstrass,\n  type WeierstrassOpts,\n  type WeierstrassPointCons,\n} from './abstract/weierstrass.ts';\nimport {\n  abytes,\n  asciiToBytes,\n  bytesToNumberBE,\n  concatBytes,\n  type TArg,\n  type TRet,\n} from './utils.ts';\n\n// Seems like generator was produced from some seed:\n// `Pointk1.BASE.multiply(Pointk1.Fn.inv(2n, N)).toAffine().x`\n// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n\nconst secp256k1_CURVE: WeierstrassOpts<bigint> = {\n  p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n  n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n  h: BigInt(1),\n  a: BigInt(0),\n  b: BigInt(7),\n  Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),\n  Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),\n};\n\nconst secp256k1_ENDO: EndomorphismOpts = {\n  beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n  basises: [\n    [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],\n    [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],\n  ],\n};\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _2n = /* @__PURE__ */ BigInt(2);\n\n/**\n * \u221An = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y: bigint): bigint {\n  const P = secp256k1_CURVE.p;\n  // prettier-ignore\n  const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n  // prettier-ignore\n  const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n  const b2 = (y * y * y) % P; // x^3, 11\n  const b3 = (b2 * b2 * y) % P; // x^7\n  const b6 = (pow2(b3, _3n, P) * b3) % P;\n  const b9 = (pow2(b6, _3n, P) * b3) % P;\n  const b11 = (pow2(b9, _2n, P) * b2) % P;\n  const b22 = (pow2(b11, _11n, P) * b11) % P;\n  const b44 = (pow2(b22, _22n, P) * b22) % P;\n  const b88 = (pow2(b44, _44n, P) * b44) % P;\n  const b176 = (pow2(b88, _88n, P) * b88) % P;\n  const b220 = (pow2(b176, _44n, P) * b44) % P;\n  const b223 = (pow2(b220, _3n, P) * b3) % P;\n  const t1 = (pow2(b223, _23n, P) * b22) % P;\n  const t2 = (pow2(t1, _6n, P) * b2) % P;\n  const root = pow2(t2, _2n, P);\n  if (!Fpk1.eql(Fpk1.sqr(root), y)) throw new Error('Cannot find square root');\n  return root;\n}\n\nconst Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });\nconst Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {\n  Fp: Fpk1,\n  endo: secp256k1_ENDO,\n});\n\n/**\n * secp256k1 curve: ECDSA and ECDH methods.\n *\n * Uses sha256 to hash messages. To use a different hash,\n * pass `{ prehash: false }` to sign / verify.\n *\n * @example\n * Generate one secp256k1 keypair, sign a message, and verify it.\n *\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = secp256k1.keygen();\n * // const publicKey = secp256k1.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = secp256k1.sign(msg, secretKey);\n * const isValid = secp256k1.verify(sig, msg, publicKey);\n * // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false });\n * ```\n */\nexport const secp256k1: ECDSA = /* @__PURE__ */ ecdsa(Pointk1, sha256);\n\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {};\n// BIP-340 phrases tags as UTF-8, but all current standardized names here are 7-bit ASCII.\nfunction taggedHash(tag: string, ...messages: TArg<Uint8Array[]>): TRet<Uint8Array> {\n  let tagP = TAGGED_HASH_PREFIXES[tag];\n  if (tagP === undefined) {\n    const tagH = sha256(asciiToBytes(tag));\n    tagP = concatBytes(tagH, tagH);\n    TAGGED_HASH_PREFIXES[tag] = tagP;\n  }\n  return sha256(concatBytes(tagP, ...messages)) as TRet<Uint8Array>;\n}\n\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point: TArg<PointType<bigint>>): TRet<Uint8Array> =>\n  point.toBytes(true).slice(1) as TRet<Uint8Array>;\nconst hasEven = (y: bigint) => y % _2n === _0n;\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: TArg<Uint8Array>) {\n  const { Fn, BASE } = Pointk1;\n  const d_ = Fn.fromBytes(priv);\n  const p = BASE.multiply(d_); // P = d'\u22C5G; 0 < d' < n check is done inside\n  const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);\n  return { scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x: bigint): PointType<bigint> {\n  const Fp = Fpk1;\n  if (!Fp.isValidNot0(x)) throw new Error('invalid x: Fail if x \u2265 p');\n  const xx = Fp.create(x * x);\n  const c = Fp.create(xx * x + BigInt(7)); // Let c = x\u00B3 + 7 mod p.\n  let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().\n  // Return the unique point P such that x(P) = x and\n  // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n  if (!hasEven(y)) y = Fp.neg(y);\n  const p = Pointk1.fromAffine({ x, y });\n  p.assertValidity();\n  return p;\n}\n// BIP-340 callers still need to supply canonical 32-byte inputs where required; this alias only\n// parses big-endian bytes and does not enforce the fixed-width contract itself.\nconst num = bytesToNumberBE;\n/** Create tagged hash, convert it to bigint, reduce modulo-n. */\nfunction challenge(...args: TArg<Uint8Array[]>): bigint {\n  return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/** Schnorr public key is just `x` coordinate of Point as per BIP340. */\nfunction schnorrGetPublicKey(secretKey: TArg<Uint8Array>): TRet<Uint8Array> {\n  return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'\u2265n. Ret bytes(d'\u22C5G)\n}\n\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * `auxRand` is optional and is not the sole source of `k` generation: bad CSPRNG output will not\n * be catastrophic, but BIP-340 still recommends fresh auxiliary randomness when available to harden\n * deterministic signing against side-channel and fault-injection attacks.\n */\nfunction schnorrSign(\n  message: TArg<Uint8Array>,\n  secretKey: TArg<Uint8Array>,\n  auxRand: TArg<Uint8Array> = randomBytes(32)\n): TRet<Uint8Array> {\n  const { Fn, BASE } = Pointk1;\n  const m = abytes(message, undefined, 'message');\n  const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder\n  const a = abytes(auxRand, 32, 'auxRand'); // Auxiliary random data a: a 32-byte array\n  // Let t be the byte-wise xor of bytes(d) and hash/aux(a).\n  const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a)));\n  const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n  // BIP340 defines k' = int(rand) mod n. We can't reuse schnorrGetExtPubKey(rand)\n  // here: that helper parses canonical secret keys and rejects rand >= n instead\n  // of reducing the nonce hash modulo the group order.\n  const k_ = Fn.create(num(rand));\n  // BIP-340: \"Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'\u22C5G.\"\n  if (k_ === 0n) throw new Error('sign failed: k is zero');\n  const p = BASE.multiply(k_); // Rejects zero; only the raw nonce hash needs reduction.\n  const k = hasEven(p.y) ? k_ : Fn.neg(k_);\n  const rx = pointToBytes(p);\n  const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n  const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n  sig.set(rx, 0);\n  sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);\n  // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n  if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced');\n  return sig as TRet<Uint8Array>;\n}\n\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(\n  signature: TArg<Uint8Array>,\n  message: TArg<Uint8Array>,\n  publicKey: TArg<Uint8Array>\n): boolean {\n  const { Fp, Fn, BASE } = Pointk1;\n  const sig = abytes(signature, 64, 'signature');\n  const m = abytes(message, undefined, 'message');\n  const pub = abytes(publicKey, 32, 'publicKey');\n  try {\n    const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n    const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r \u2265 p.\n    if (!Fp.isValidNot0(r)) return false;\n    const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s \u2265 n.\n    // Stricter than BIP-340/libsecp256k1, which only reject s >= n. Honest signing reaches\n    // s = 0 only with negligible probability (k + e*d \u2261 0 mod n), so treat zero-s inputs as\n    // crafted edge cases and fail closed instead of carrying that extra verification surface.\n    if (!Fn.isValidNot0(s)) return false;\n\n    // int(challenge(bytes(r) || bytes(P) || m)) % n\n    const e = challenge(Fn.toBytes(r), pointToBytes(P), m);\n    // R = s\u22C5G - e\u22C5P, where -eP == (n-e)P\n    const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));\n    const { x, y } = R.toAffine();\n    // Fail if is_infinite(R) / not has_even_y(R) / x(R) \u2260 r.\n    if (R.is0() || !hasEven(y) || x !== r) return false;\n    return true;\n  } catch (error) {\n    return false;\n  }\n}\n\nexport const __TEST: { lift_x: typeof lift_x } = /* @__PURE__ */ Object.freeze({ lift_x });\n\n/** Schnorr-specific secp256k1 API from BIP340. */\nexport type SecpSchnorr = {\n  /**\n   * Generate one Schnorr secret/public keypair.\n   * @param seed - Optional seed for deterministic testing or custom randomness.\n   * @returns Fresh secret/public keypair.\n   */\n  keygen: (seed?: TArg<Uint8Array>) => { secretKey: TRet<Uint8Array>; publicKey: TRet<Uint8Array> };\n  /**\n   * Derive the x-only public key from a secret key.\n   * @param secretKey - Secret key bytes.\n   * @returns X-only public key bytes.\n   */\n  getPublicKey: typeof schnorrGetPublicKey;\n  /**\n   * Create one BIP340 Schnorr signature.\n   * @param message - Message bytes to sign.\n   * @param secretKey - Secret key bytes.\n   * @param auxRand - Optional auxiliary randomness.\n   * @returns Compact Schnorr signature bytes.\n   */\n  sign: typeof schnorrSign;\n  /**\n   * Verify one BIP340 Schnorr signature.\n   * @param signature - Compact signature bytes.\n   * @param message - Signed message bytes.\n   * @param publicKey - X-only public key bytes.\n   * @returns `true` when the signature is valid.\n   */\n  verify: typeof schnorrVerify;\n  /** Underlying secp256k1 point constructor. */\n  Point: WeierstrassPointCons<bigint>;\n  /** Helper utilities for Schnorr-specific key handling and tagged hashing. */\n  utils: {\n    /** Generate one Schnorr secret key. */\n    randomSecretKey: (seed?: TArg<Uint8Array>) => TRet<Uint8Array>;\n    /** Convert one point into its x-only BIP340 byte encoding. */\n    pointToBytes: (point: TArg<PointType<bigint>>) => TRet<Uint8Array>;\n    /** Lift one x coordinate into the unique even-Y point. */\n    lift_x: typeof lift_x;\n    /** Compute a BIP340 tagged hash. */\n    taggedHash: typeof taggedHash;\n  };\n  /** Public byte lengths for keys, signatures, and seeds. */\n  lengths: CurveLengths;\n};\n/**\n * Schnorr signatures over secp256k1.\n * See {@link https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki | BIP 340}.\n * @example\n * Generate one BIP340 Schnorr keypair, sign a message, and verify it.\n *\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = schnorr.keygen();\n * // const publicKey = schnorr.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, secretKey);\n * const isValid = schnorr.verify(sig, msg, publicKey);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__PURE__ */ (() => {\n  const size = 32;\n  const seedLength = 48;\n  const randomSecretKey = (seed?: TArg<Uint8Array>): TRet<Uint8Array> => {\n    seed = seed === undefined ? randomBytes(seedLength) : seed;\n    return mapHashToField(seed, secp256k1_CURVE.n);\n  };\n  return Object.freeze({\n    keygen: createKeygen(randomSecretKey, schnorrGetPublicKey),\n    getPublicKey: schnorrGetPublicKey,\n    sign: schnorrSign,\n    verify: schnorrVerify,\n    Point: Pointk1,\n    utils: Object.freeze({\n      randomSecretKey,\n      taggedHash,\n      lift_x,\n      pointToBytes,\n    }),\n    lengths: Object.freeze({\n      secretKey: size,\n      publicKey: size,\n      publicKeyHasPrefix: false,\n      signature: size * 2,\n      seed: seedLength,\n    }),\n  });\n})();\n\n// RFC 9380 Appendix E.1 3-isogeny coefficients for secp256k1, stored in ascending degree order.\n// The final `1` in each denominator array is the explicit monic leading term.\nconst isoMap = /* @__PURE__ */ (() =>\n  isogenyMap(\n    Fpk1,\n    [\n      // xNum\n      [\n        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n        '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n        '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n      ],\n      // xDen\n      [\n        '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n        '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n      ],\n      // yNum\n      [\n        '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n        '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n        '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n        '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n      ],\n      // yDen\n      [\n        '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n        '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n        '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n      ],\n    ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]]\n  ))();\n// RFC 9380 \u00A78.7 secp256k1 E' parameters for the SWU-to-isogeny pipeline below.\nlet mapSWU: ((u: bigint) => { x: bigint; y: bigint }) | undefined;\nconst getMapSWU = () =>\n  mapSWU ||\n  (mapSWU = mapToCurveSimpleSWU(Fpk1, {\n    // Building the SWU sqrt-ratio helper eagerly adds noticeable `secp256k1.js` import cost, so\n    // defer it to first use; after that the cached mapper is reused directly.\n    A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n    B: BigInt('1771'),\n    Z: Fpk1.create(BigInt('-11')),\n  }));\n\n/**\n * Hashing / encoding to secp256k1 points / field. RFC 9380 methods.\n * @example\n * Hash one message onto secp256k1.\n *\n * ```ts\n * const point = secp256k1_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const secp256k1_hasher: H2CHasher<WeierstrassPointCons<bigint>> = /* @__PURE__ */ (() =>\n  createHasher(\n    Pointk1,\n    (scalars: bigint[]) => {\n      const { x, y } = getMapSWU()(Fpk1.create(scalars[0]));\n      return isoMap(x, y);\n    },\n    {\n      DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n      encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n      p: Fpk1.ORDER,\n      m: 1,\n      k: 128,\n      expand: 'xmd',\n      hash: sha256,\n    }\n  ))();\n/**\n * FROST threshold signatures over secp256k1. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 secp256k1 signing.\n *\n * ```ts\n * const alice = secp256k1_FROST.Identifier.derive('alice@example.com');\n * const bob = secp256k1_FROST.Identifier.derive('bob@example.com');\n * const carol = secp256k1_FROST.Identifier.derive('carol@example.com');\n * const deal = secp256k1_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const secp256k1_FROST: TRet<FROST> = /* @__PURE__ */ (() =>\n  createFROST({\n    name: 'FROST-secp256k1-SHA256-v1',\n    Point: Pointk1,\n    hashToScalar: secp256k1_hasher.hashToScalar,\n    hash: sha256,\n  }))();\n\n// Taproot utils\n// `undefined` means \"disable TapTweak entirely\"; callers that want the BIP-341/BIP-386 empty\n// merkle root must pass `new Uint8Array(0)` explicitly.\nfunction tweak(point: PointType<bigint>, merkleRoot?: TArg<Uint8Array>): bigint {\n  if (merkleRoot === undefined) return _0n;\n  const x = pointToBytes(point);\n  const t = bytesToNumberBE(taggedHash('TapTweak', x, merkleRoot));\n  // BIP-341 taproot_tweak_pubkey/taproot_tweak_seckey: \"if t >= SECP256K1_ORDER:\n  // raise ValueError\". TapTweak must reject overflow instead of reducing modulo n.\n  if (!Pointk1.Fn.isValid(t)) throw new Error('invalid TapTweak hash');\n  return t;\n}\nfunction frostPubToEvenY(pub: TArg<FrostPublic>): TRet<FrostPublic> {\n  const VK = Pointk1.fromBytes(pub.commitments[0]);\n  // Keep aliasing on the already-even path so wrapper callers can skip unnecessary cloning.\n  if (hasEven(VK.y)) return pub as TRet<FrostPublic>;\n  return {\n    signers: { min: pub.signers.min, max: pub.signers.max },\n    commitments: pub.commitments.map((i) => Pointk1.fromBytes(i).negate().toBytes()),\n    verifyingShares: Object.fromEntries(\n      Object.entries(pub.verifyingShares).map(([k, v]) => [\n        k,\n        Pointk1.fromBytes(v).negate().toBytes(),\n      ])\n    ),\n  } as TRet<FrostPublic>;\n}\nfunction frostSecretToEvenY(s: TArg<FrostSecret>, pub: TArg<FrostPublic>): TRet<FrostSecret> {\n  const VK = Pointk1.fromBytes(pub.commitments[0]);\n  // Keep aliasing on the already-even path so wrapper callers can preserve package identity.\n  if (hasEven(VK.y)) return s as TRet<FrostSecret>;\n  const Fn = Pointk1.Fn;\n  return {\n    ...s,\n    signingShare: Fn.toBytes(Fn.neg(Fn.fromBytes(s.signingShare))),\n  } as TRet<FrostSecret>;\n}\nfunction frostNoncesToEvenY(PK: PointType<bigint>, nonces: TArg<Nonces>): TRet<Nonces> {\n  if (hasEven(PK.y)) return nonces as TRet<Nonces>;\n  const Fn = Pointk1.Fn;\n  return {\n    binding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.binding))),\n    hiding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.hiding))),\n  } as TRet<Nonces>;\n}\n\nfunction frostTweakSecret(\n  s: TArg<FrostSecret>,\n  pub: TArg<FrostPublic>,\n  merkleRoot?: TArg<Uint8Array>\n): TRet<FrostSecret> {\n  const Fn = Pointk1.Fn;\n  const keyPackage = frostSecretToEvenY(s, pub);\n  const evenPub = frostPubToEvenY(pub);\n  const t = tweak(Pointk1.fromBytes(evenPub.commitments[0]), merkleRoot);\n  const signingShare = Fn.toBytes(Fn.add(Fn.fromBytes(keyPackage.signingShare), t));\n  return {\n    identifier: keyPackage.identifier,\n    signingShare,\n  } as TRet<FrostSecret>;\n}\n\nfunction frostTweakPublic(\n  pub: TArg<FrostPublic>,\n  merkleRoot?: TArg<Uint8Array>\n): TRet<FrostPublic> {\n  const PKPackage = frostPubToEvenY(pub);\n  const t = tweak(Pointk1.fromBytes(PKPackage.commitments[0]), merkleRoot);\n  const tp = Pointk1.BASE.multiply(t);\n  const commitments = PKPackage.commitments.map((c, i) =>\n    (i === 0 ? Pointk1.fromBytes(c).add(tp) : Pointk1.fromBytes(c)).toBytes()\n  );\n  const verifyingShares: Record<string, Uint8Array> = {};\n  for (const k in PKPackage.verifyingShares) {\n    verifyingShares[k] = Pointk1.fromBytes(PKPackage.verifyingShares[k]).add(tp).toBytes();\n  }\n  return {\n    signers: { min: PKPackage.signers.min, max: PKPackage.signers.max },\n    commitments,\n    verifyingShares,\n  } as TRet<FrostPublic>;\n}\n\n/**\n * FROST threshold signatures over secp256k1-schnorr-taproot. RFC 9591.\n * DKG outputs are auto-tweaked with the empty Taproot merkle root for compatibility, while\n * `trustedDealer()` outputs stay untweaked unless callers apply the Taproot tweak themselves.\n * @example\n * Create one trusted-dealer package for Taproot-compatible FROST signing.\n *\n * ```ts\n * const alice = schnorr_FROST.Identifier.derive('alice@example.com');\n * const bob = schnorr_FROST.Identifier.derive('bob@example.com');\n * const carol = schnorr_FROST.Identifier.derive('carol@example.com');\n * const deal = schnorr_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const schnorr_FROST: TRet<FROST> = /* @__PURE__ */ (() =>\n  createFROST({\n    name: 'FROST-secp256k1-SHA256-TR-v1',\n    Point: Pointk1,\n    hashToScalar: secp256k1_hasher.hashToScalar,\n    hash: sha256,\n    // Taproot related hacks\n    parsePublicKey(publicKey) {\n      // External Taproot keys are x-only, but local key packages still use compressed points.\n      if (publicKey.length === 32) return lift_x(bytesToNumberBE(publicKey));\n      if (publicKey.length === 33) return Pointk1.fromBytes(publicKey);\n      throw new Error(`expected x-only or compressed public key, got length=${publicKey.length}`);\n    },\n    adjustScalar(n: bigint) {\n      const PK = Pointk1.BASE.multiply(n);\n      return hasEven(PK.y) ? n : Pointk1.Fn.neg(n);\n    },\n    adjustPoint: (p) => (hasEven(p.y) ? p : p.negate()),\n    challenge(R, PK, msg) {\n      return challenge(pointToBytes(R), pointToBytes(PK), msg);\n    },\n    adjustNonces: frostNoncesToEvenY,\n    adjustGroupCommitmentShare: (GC, GCShare) => (!hasEven(GC.y) ? GCShare.negate() : GCShare),\n    adjustPublic: frostPubToEvenY,\n    adjustSecret: frostSecretToEvenY,\n    adjustTx: {\n      // Compat with official implementation\n      encode: (tx) => tx.subarray(1) as TRet<Uint8Array>,\n      decode: (tx) => concatBytes(Uint8Array.of(0x02), tx) as TRet<Uint8Array>,\n    },\n    adjustDKG: (k) => {\n      // Compatibility with frost-secp256k1-tr: DKG output is auto-tweaked with the\n      // empty Taproot merkle root, while dealer-generated keys stay untweaked.\n      const merkleRoot = new Uint8Array(0);\n      return {\n        public: frostTweakPublic(k.public, merkleRoot),\n        secret: frostTweakSecret(k.secret, k.public, merkleRoot),\n      };\n    },\n  }))();\n", "/**\n * @file Hive crypto helpers.\n * @author Johan Nordberg <code@johan-nordberg.com>\n * @license\n * Copyright (c) 2017 Johan Nordberg. All Rights Reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n *  1. Redistribution of source code must retain the above copyright notice, this\n *     list of conditions and the following disclaimer.\n *\n *  2. Redistribution in binary form must reproduce the above copyright notice,\n *     this list of conditions and the following disclaimer in the documentation\n *     and/or other materials provided with the distribution.\n *\n *  3. Neither the name of the copyright holder nor the names of its contributors\n *     may be used to endorse or promote products derived from this software without\n *     specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * You acknowledge that this software is not designed, licensed or intended for use\n * in the design, construction, operation or maintenance of any military facility.\n */\n\nimport { SerializationError } from \"./errors.js\";\nimport { Types } from \"./chain/serializer.js\";\nimport { SignedTransaction, Transaction } from \"./chain/transaction.js\";\nimport { DEFAULT_ADDRESS_PREFIX, DEFAULT_CHAIN_ID } from \"./client.js\";\nimport { copy, BinaryWriter, toHex, fromHex, concat, bytesEqual, assert } from \"./utils.js\";\n\nimport { base58 } from \"@scure/base\";\nimport { ripemd160 as nobleRipemd160 } from \"@noble/hashes/legacy.js\";\nimport { sha256 as nobleSha256, sha512 as nobleSha512 } from \"@noble/hashes/sha2.js\";\nimport { secp256k1 as nobleSecp256k1 } from \"@noble/curves/secp256k1.js\";\n\n/**\n * Network marker byte used by Hive WIF private keys.\n */\nexport const NETWORK_ID = new Uint8Array([0x80]);\n\n/**\n * Return ripemd160 hash of input.\n */\nfunction ripemd160(input: Uint8Array | string): Uint8Array {\n  const data = typeof input === \"string\" ? new TextEncoder().encode(input) : input;\n  return nobleRipemd160(data);\n}\n\n/**\n * Return sha256 hash of input.\n */\nfunction sha256(input: Uint8Array | string): Uint8Array {\n  const data = typeof input === \"string\" ? new TextEncoder().encode(input) : input;\n  return nobleSha256(data);\n}\n\n/**\n * Return sha512 hash of input\n */\nfunction sha512(input: Uint8Array | string): Uint8Array {\n  const data = typeof input === \"string\" ? new TextEncoder().encode(input) : input;\n  return nobleSha512(data);\n}\n\n/**\n * Return 2-round sha256 hash of input.\n */\nfunction doubleSha256(input: Uint8Array | string): Uint8Array {\n  return sha256(sha256(input));\n}\n\n/**\n * Encode public key with bs58+ripemd160-checksum.\n */\nfunction encodePublic(key: Uint8Array, prefix: string): string {\n  const checksum = ripemd160(key);\n  return prefix + base58.encode(concat([key, checksum.slice(0, 4)]));\n}\n\n/**\n * Decode bs58+ripemd160-checksum encoded public key.\n */\nfunction decodePublic(encodedKey: string): { key: Uint8Array; prefix: string } {\n  const prefix = encodedKey.slice(0, 3);\n  assert(prefix.length === 3, \"public key invalid prefix\");\n  encodedKey = encodedKey.slice(3);\n  const buffer = base58.decode(encodedKey);\n  const checksum = buffer.slice(-4);\n  const key = buffer.slice(0, -4);\n  const checksumVerify = ripemd160(key).slice(0, 4);\n  assert(bytesEqual(checksumVerify, checksum), \"public key checksum mismatch\");\n  return { key, prefix };\n}\n\n/**\n * Encode bs58+doubleSha256-checksum private key.\n */\nfunction encodePrivate(key: Uint8Array): string {\n  assert(key[0] === 0x80, \"private key network id mismatch\");\n  const checksum = doubleSha256(key);\n  return base58.encode(concat([key, checksum.slice(0, 4)]));\n}\n\n/**\n * Decode bs58+doubleSha256-checksum encoded private key.\n */\nfunction decodePrivate(encodedKey: string): Uint8Array {\n  const buffer = base58.decode(encodedKey);\n  assert(bytesEqual(buffer.slice(0, 1), NETWORK_ID), \"private key network id mismatch\");\n  const checksum = buffer.slice(-4);\n  const key = buffer.slice(0, -4);\n  const checksumVerify = doubleSha256(key).slice(0, 4);\n  assert(bytesEqual(checksumVerify, checksum), \"private key checksum mismatch\");\n  return key;\n}\n\n/**\n * Return true if signature is canonical, otherwise false.\n */\nfunction isCanonicalSignature(signature: Uint8Array): boolean {\n  return (\n    !(signature[0] & 0x80) &&\n    !(signature[0] === 0 && !(signature[1] & 0x80)) &&\n    !(signature[32] & 0x80) &&\n    !(signature[32] === 0 && !(signature[33] & 0x80))\n  );\n}\n\n/**\n * Return true if string is wif, otherwise false.\n */\nfunction isWif(privWif: string | Uint8Array): boolean {\n  try {\n    const wifStr = typeof privWif === \"string\" ? privWif : new TextDecoder().decode(privWif);\n    const bufWif = base58.decode(wifStr);\n    const privKey = bufWif.slice(0, -4);\n    const checksum = bufWif.slice(-4);\n    let newChecksum = sha256(privKey);\n    newChecksum = sha256(newChecksum);\n    newChecksum = newChecksum.slice(0, 4);\n    return bytesEqual(checksum, newChecksum);\n  } catch (e: any) {\n    return false;\n  }\n}\n\n/**\n * Hive public key backed by the secp256k1 elliptic curve.\n */\nexport class PublicKey {\n  public readonly uncompressed: Uint8Array;\n\n  constructor(\n    public readonly key: Uint8Array,\n    public readonly prefix = DEFAULT_ADDRESS_PREFIX,\n  ) {\n    try {\n      // Validate key and store uncompressed version\n      const k = new Uint8Array(key);\n      const point = (nobleSecp256k1 as any).Point.fromHex(toHex(k));\n      this.uncompressed = point.toBytes(false);\n    } catch (err: any) {\n      throw new Error(`invalid public key: ${err.message}`);\n    }\n  }\n\n  public static fromBuffer(key: Uint8Array) {\n    return new PublicKey(key);\n  }\n\n  /**\n   * Creates a public key from its Hive string representation.\n   */\n  public static fromString(wif: string) {\n    const { key, prefix } = decodePublic(wif);\n    return new PublicKey(key, prefix);\n  }\n\n  /**\n   * Normalizes a public-key input into a {@link PublicKey} instance.\n   */\n  public static from(value: string | PublicKey) {\n    if (value instanceof PublicKey) {\n      return value;\n    } else {\n      return PublicKey.fromString(value);\n    }\n  }\n\n  /**\n   * Verifies a compact ECDSA signature against a 32-byte digest.\n   */\n  public verify(message: Uint8Array, signature: Signature): boolean {\n    try {\n      // In noble v2, verify accepts compact signature bytes directly\n      return nobleSecp256k1.verify(signature.data, message, this.key, {\n        prehash: false,\n        lowS: true,\n      });\n    } catch (e: any) {\n      return false;\n    }\n  }\n\n  /**\n   * Renders the key as a Hive public-key string.\n   */\n  public toString() {\n    return encodePublic(this.key, this.prefix);\n  }\n\n  /**\n   * Return JSON representation of this key, same as toString().\n   */\n  public toJSON() {\n    return this.toString();\n  }\n\n  /**\n   * Used by `utils.inspect` and `console.log` in node.js.\n   */\n  public inspect() {\n    return `PublicKey: ${this.toString()}`;\n  }\n}\n\n/**\n * Hive authority role used for password-derived account keys.\n */\nexport type KeyRole = \"owner\" | \"active\" | \"posting\" | \"memo\";\n\n/**\n * Hive private key backed by the secp256k1 elliptic curve.\n */\nexport class PrivateKey {\n  constructor(private key: Uint8Array) {\n    try {\n      assert(nobleSecp256k1.utils.isValidSecretKey(key), \"invalid private key\");\n    } catch (e: any) {\n      assert(false, \"invalid private key\");\n    }\n  }\n\n  /**\n   * Normalizes a WIF string or raw 32-byte secret into a private key.\n   *\n   * @remarks\n   * Raw secrets are accepted as `Uint8Array` values so Pollen's key path stays\n   * independent of Node `Buffer` while still working in browser builds.\n   */\n  public static from(value: string | Uint8Array) {\n    if (typeof value === \"string\") {\n      return PrivateKey.fromString(value);\n    } else {\n      return new PrivateKey(value);\n    }\n  }\n\n  /**\n   * Parses a WIF-encoded Hive private key.\n   */\n  public static fromString(wif: string) {\n    return new PrivateKey(decodePrivate(wif).slice(1));\n  }\n\n  /**\n   * Derives a private key by hashing an arbitrary seed string.\n   */\n  public static fromSeed(seed: string) {\n    return new PrivateKey(sha256(seed));\n  }\n\n  /**\n   * Derives a Hive role key from an account name and master password.\n   */\n  public static fromLogin(username: string, password: string, role: KeyRole = \"active\") {\n    const seed = username + role + password;\n    return PrivateKey.fromSeed(seed);\n  }\n\n  /**\n   * Signs a 32-byte digest with this private key.\n   */\n  public sign(message: Uint8Array): Signature {\n    let attempts = 0;\n    let sigRaw: Uint8Array;\n    do {\n      attempts++;\n      const extra = sha256(concat([message, new Uint8Array([attempts])]));\n      // Use format: 'recovered' to get 65 bytes [recovery, r, s]\n      sigRaw = nobleSecp256k1.sign(message, this.key, {\n        extraEntropy: extra,\n        prehash: false,\n        lowS: true,\n        format: \"recovered\",\n      });\n    } while (!isCanonicalSignature(sigRaw.slice(1)));\n\n    // Hive expects recovery 0-3 internally (stored as 31-34 in signature buffer)\n    return new Signature(sigRaw.slice(1), sigRaw[0]);\n  }\n\n  /**\n   * Derives the compressed public key for this private key.\n   */\n  public createPublic(prefix?: string): PublicKey {\n    const pubKey = nobleSecp256k1.getPublicKey(this.key, true);\n    return new PublicKey(pubKey, prefix);\n  }\n\n  /**\n   * Renders the private key as a WIF string.\n   */\n  public toString() {\n    return encodePrivate(concat([NETWORK_ID, this.key]));\n  }\n\n  /**\n   * Used by `utils.inspect` and `console.log` in node.js.\n   */\n  public inspect() {\n    const key = this.toString();\n    return `PrivateKey: ${key.slice(0, 6)}...${key.slice(-6)}`;\n  }\n\n  /**\n   * Derives the shared secret used by encrypted Hive memos.\n   */\n  public get_shared_secret(public_key: PublicKey): Uint8Array {\n    const S = nobleSecp256k1.getSharedSecret(this.key, public_key.key, false);\n    // Hive uses the X coordinate (32 bytes after the 0x04 prefix)\n    return sha512(S.slice(1, 33));\n  }\n}\n\n/**\n * Compact recoverable secp256k1 signature.\n */\nexport class Signature {\n  constructor(\n    public data: Uint8Array,\n    public recovery: number,\n  ) {\n    assert(data.length === 64, \"invalid signature\");\n  }\n\n  public static fromBuffer(buffer: Uint8Array) {\n    assert(buffer.length === 65, \"invalid signature\");\n    // Hive uses 27-30 or 31-34. Noble wants 0-3.\n    let recovery = buffer[0];\n    if (recovery >= 31) recovery -= 31;\n    else if (recovery >= 27) recovery -= 27;\n\n    const data = buffer.slice(1);\n    return new Signature(data, recovery);\n  }\n\n  public static fromString(string: string) {\n    return Signature.fromBuffer(fromHex(string));\n  }\n\n  /**\n   * Recovers the public key that produced this signature.\n   */\n  public recover(message: Uint8Array, prefix?: string) {\n    // In noble v2, recoverPublicKey expects (signature65, messageHash, { prehash: false })\n    // signature65 format is [recovery, r, s]\n    const sigRaw = concat([new Uint8Array([this.recovery % 4]), this.data]);\n    const pubKeyBytes = nobleSecp256k1.recoverPublicKey(sigRaw, message, { prehash: false });\n    return new PublicKey(pubKeyBytes, prefix);\n  }\n\n  public toBuffer() {\n    const buffer = new Uint8Array(65);\n    // Hive convention: recovery + 31\n    buffer[0] = this.recovery + 31;\n    buffer.set(this.data, 1);\n    return buffer;\n  }\n\n  public toString() {\n    return toHex(this.toBuffer());\n  }\n}\n\n/**\n * Return the sha256 transaction digest.\n */\nfunction transactionDigest(\n  transaction: Transaction | SignedTransaction,\n  chainId: Uint8Array = DEFAULT_CHAIN_ID,\n) {\n  const writer = new BinaryWriter();\n  try {\n    Types.Transaction(writer, transaction);\n  } catch (cause: any) {\n    throw new SerializationError(\"Unable to serialize transaction\", cause);\n  }\n  const transactionData = writer.getBuffer();\n  const digest = sha256(concat([chainId, transactionData]));\n  return digest;\n}\n\n/**\n * Returns a copy of a transaction with one or more signatures appended.\n */\nfunction signTransaction(\n  transaction: Transaction,\n  keys: PrivateKey | PrivateKey[],\n  chainId: Uint8Array = DEFAULT_CHAIN_ID,\n) {\n  const digest = transactionDigest(transaction, chainId);\n  const signedTransaction = copy(transaction) as SignedTransaction;\n  if (!signedTransaction.signatures) {\n    signedTransaction.signatures = [];\n  }\n\n  if (!Array.isArray(keys)) {\n    keys = [keys];\n  }\n  for (const key of keys) {\n    const signature = key.sign(digest);\n    signedTransaction.signatures.push(signature.toString());\n  }\n\n  return signedTransaction;\n}\n\nfunction generateTrxId(transaction: Transaction) {\n  const writer = new BinaryWriter();\n  try {\n    Types.Transaction(writer, transaction);\n  } catch (cause: any) {\n    throw new SerializationError(\"Unable to serialize transaction\", cause);\n  }\n  const transactionData = writer.getBuffer();\n  return toHex(sha256(transactionData)).slice(0, 40);\n}\n\n/**\n * Low-level cryptographic utility namespace.\n */\nexport const cryptoUtils = {\n  decodePrivate,\n  doubleSha256,\n  encodePrivate,\n  encodePublic,\n  generateTrxId,\n  isCanonicalSignature,\n  isWif,\n  ripemd160,\n  sha256,\n  signTransaction,\n  transactionDigest,\n};\n", "/**\n * @file Hive protocol serialization.\n * @author Johan Nordberg <code@johan-nordberg.com>\n * @license\n * Copyright (c) 2017 Johan Nordberg. All Rights Reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n *  1. Redistribution of source code must retain the above copyright notice, this\n *     list of conditions and the following disclaimer.\n *\n *  2. Redistribution in binary form must reproduce the above copyright notice,\n *     this list of conditions and the following disclaimer in the documentation\n *     and/or other materials provided with the distribution.\n *\n *  3. Neither the name of the copyright holder nor the names of its contributors\n *     may be used to endorse or promote products derived from this software without\n *     specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * You acknowledge that this software is not designed, licensed or intended for use\n * in the design, construction, operation or maintenance of any military facility.\n */\n\nimport { BinaryWriter } from \"../utils.js\";\nimport { PublicKey } from \"../crypto.js\";\nimport { Asset } from \"./asset.js\";\nimport { HexBuffer } from \"./misc.js\";\nimport { Operation } from \"./operation.js\";\n\n/**\n * Function signature for writing one Hive protocol value to Pollen's native\n * byte writer.\n *\n * @param buffer - Destination binary writer.\n * @param data - Value to serialize.\n *\n * @remarks\n * Serializers are intentionally composable. Complex operation serializers are\n * built by combining primitive serializers for numbers, native `bigint`-backed\n * 64-bit values, strings, assets, public keys, arrays, options, and objects.\n *\n * @example\n * ```ts\n * const writer = new BinaryWriter()\n * Types.String(writer, 'pollen')\n * ```\n */\nexport type Serializer = (buffer: BinaryWriter, data: any) => void;\n\nconst VoidSerializer = (_buffer: BinaryWriter) => {\n  throw new Error(\"Void can not be serialized\");\n};\n\nconst StringSerializer = (buffer: BinaryWriter, data: string) => {\n  buffer.writeString(data);\n};\n\nconst Int8Serializer = (buffer: BinaryWriter, data: number) => {\n  buffer.writeInt8(data);\n};\n\nconst Int16Serializer = (buffer: BinaryWriter, data: number) => {\n  buffer.writeInt16(data);\n};\n\nconst Int32Serializer = (buffer: BinaryWriter, data: number) => {\n  buffer.writeInt32(data);\n};\n\nconst Int64Serializer = (buffer: BinaryWriter, data: number) => {\n  buffer.writeInt64(data);\n};\n\nconst UInt8Serializer = (buffer: BinaryWriter, data: number) => {\n  buffer.writeUint8(data);\n};\n\nconst UInt16Serializer = (buffer: BinaryWriter, data: number) => {\n  buffer.writeUint16(data);\n};\n\nconst UInt32Serializer = (buffer: BinaryWriter, data: number) => {\n  buffer.writeUint32(data);\n};\n\nconst UInt64Serializer = (buffer: BinaryWriter, data: number) => {\n  buffer.writeUint64(data);\n};\n\nconst BooleanSerializer = (buffer: BinaryWriter, data: boolean) => {\n  buffer.writeUint8(data ? 1 : 0);\n};\n\nconst StaticVariantSerializer =\n  (itemSerializers: Serializer[]) => (buffer: BinaryWriter, data: [number, unknown]) => {\n    const [id, item] = data;\n    buffer.writeVarint32(id);\n    itemSerializers[id](buffer, item);\n  };\n\n/**\n * Serialize asset.\n *\n * @remarks\n * This loses precision for amounts larger than 2^53-1/10^precision.\n * Should not be a problem in real-world usage.\n */\nconst AssetSerializer = (buffer: BinaryWriter, data: Asset | string | number) => {\n  const asset = Asset.from(data).steem_symbols();\n  const precision = asset.getPrecision();\n  buffer.writeInt64(Math.round(asset.amount * Math.pow(10, precision)));\n  buffer.writeUint8(precision);\n  for (let i = 0; i < 7; i++) {\n    buffer.writeUint8(asset.symbol.charCodeAt(i) || 0);\n  }\n};\n\nconst DateSerializer = (buffer: BinaryWriter, data: string) => {\n  buffer.writeUint32(Math.floor(new Date(data + \"Z\").getTime() / 1000));\n};\n\nconst PublicKeySerializer = (buffer: BinaryWriter, data: PublicKey | string | null) => {\n  if (\n    data === null ||\n    (typeof data === \"string\" && data.endsWith(\"1111111111111111111111111111111114T1Anm\"))\n  ) {\n    buffer.writeBytes(new Uint8Array(33));\n  } else {\n    buffer.writeBytes(PublicKey.from(data).key);\n  }\n};\n\nconst BinarySerializer =\n  (size?: number) => (buffer: BinaryWriter, data: Uint8Array | HexBuffer) => {\n    data = HexBuffer.from(data);\n    const len = data.buffer.length;\n    if (size) {\n      if (len !== size) {\n        throw new Error(`Unable to serialize binary. Expected ${size} bytes, got ${len}`);\n      }\n    } else {\n      buffer.writeVarint32(len);\n    }\n    buffer.writeBytes(data.buffer);\n  };\n\nconst VariableBinarySerializer = BinarySerializer();\n\nconst FlatMapSerializer =\n  (keySerializer: Serializer, valueSerializer: Serializer) =>\n  (buffer: BinaryWriter, data: [unknown, unknown][]) => {\n    buffer.writeVarint32(data.length);\n    for (const [key, value] of data) {\n      keySerializer(buffer, key);\n      valueSerializer(buffer, value);\n    }\n  };\n\nconst ArraySerializer = (itemSerializer: Serializer) => (buffer: BinaryWriter, data: unknown[]) => {\n  buffer.writeVarint32(data.length);\n  for (const item of data) {\n    itemSerializer(buffer, item);\n  }\n};\n\nconst ObjectSerializer =\n  (keySerializers: [string, Serializer][]) => (buffer: BinaryWriter, data: any) => {\n    for (const [key, serializer] of keySerializers) {\n      try {\n        serializer(buffer, data[key]);\n      } catch (error: unknown) {\n        if (error instanceof Error) {\n          error.message = `${key}: ${error.message}`;\n          throw error;\n        }\n        throw new Error(`${key}: ${String(error)}`);\n      }\n    }\n  };\n\nconst OptionalSerializer =\n  (valueSerializer: Serializer) => (buffer: BinaryWriter, data: unknown) => {\n    if (data) {\n      buffer.writeUint8(1);\n      valueSerializer(buffer, data);\n    } else {\n      buffer.writeUint8(0);\n    }\n  };\n\nconst AuthoritySerializer = ObjectSerializer([\n  [\"weight_threshold\", UInt32Serializer],\n  [\"account_auths\", FlatMapSerializer(StringSerializer, UInt16Serializer)],\n  [\"key_auths\", FlatMapSerializer(PublicKeySerializer, UInt16Serializer)],\n]);\n\nconst BeneficiarySerializer = ObjectSerializer([\n  [\"account\", StringSerializer],\n  [\"weight\", UInt16Serializer],\n]);\n\nconst PriceSerializer = ObjectSerializer([\n  [\"base\", AssetSerializer],\n  [\"quote\", AssetSerializer],\n]);\n\nconst ProposalUpdateSerializer = ObjectSerializer([[\"end_date\", DateSerializer]]);\n\nconst SignedBlockHeaderSerializer = ObjectSerializer([\n  [\"previous\", BinarySerializer(20)],\n  [\"timestamp\", DateSerializer],\n  [\"witness\", StringSerializer],\n  [\"transaction_merkle_root\", BinarySerializer(20)],\n  [\"extensions\", ArraySerializer(VoidSerializer)],\n  [\"witness_signature\", BinarySerializer(65)],\n]);\n\nconst ChainPropertiesSerializer = ObjectSerializer([\n  [\"account_creation_fee\", AssetSerializer],\n  [\"maximum_block_size\", UInt32Serializer],\n  [\"hbd_interest_rate\", UInt16Serializer],\n]);\n\nconst OperationDataSerializer = (operationId: number, definitions: [string, Serializer][]) => {\n  const objectSerializer = ObjectSerializer(definitions);\n  return (buffer: BinaryWriter, data: any) => {\n    buffer.writeVarint32(operationId);\n    objectSerializer(buffer, data);\n  };\n};\n\nconst OperationSerializers: { [name: string]: Serializer } = {};\nOperationSerializers.account_create = OperationDataSerializer(9, [\n  [\"fee\", AssetSerializer],\n  [\"creator\", StringSerializer],\n  [\"new_account_name\", StringSerializer],\n  [\"owner\", AuthoritySerializer],\n  [\"active\", AuthoritySerializer],\n  [\"posting\", AuthoritySerializer],\n  [\"memo_key\", PublicKeySerializer],\n  [\"json_metadata\", StringSerializer],\n]);\n\nOperationSerializers.account_create_with_delegation = OperationDataSerializer(41, [\n  [\"fee\", AssetSerializer],\n  [\"delegation\", AssetSerializer],\n  [\"creator\", StringSerializer],\n  [\"new_account_name\", StringSerializer],\n  [\"owner\", AuthoritySerializer],\n  [\"active\", AuthoritySerializer],\n  [\"posting\", AuthoritySerializer],\n  [\"memo_key\", PublicKeySerializer],\n  [\"json_metadata\", StringSerializer],\n  [\"extensions\", ArraySerializer(VoidSerializer)],\n]);\n\nOperationSerializers.account_update = OperationDataSerializer(10, [\n  [\"account\", StringSerializer],\n  [\"owner\", OptionalSerializer(AuthoritySerializer)],\n  [\"active\", OptionalSerializer(AuthoritySerializer)],\n  [\"posting\", OptionalSerializer(AuthoritySerializer)],\n  [\"memo_key\", PublicKeySerializer],\n  [\"json_metadata\", StringSerializer],\n]);\n\nOperationSerializers.account_witness_proxy = OperationDataSerializer(13, [\n  [\"account\", StringSerializer],\n  [\"proxy\", StringSerializer],\n]);\n\nOperationSerializers.account_witness_vote = OperationDataSerializer(12, [\n  [\"account\", StringSerializer],\n  [\"witness\", StringSerializer],\n  [\"approve\", BooleanSerializer],\n]);\n\nOperationSerializers.cancel_transfer_from_savings = OperationDataSerializer(34, [\n  [\"from\", StringSerializer],\n  [\"request_id\", UInt32Serializer],\n]);\n\nOperationSerializers.change_recovery_account = OperationDataSerializer(26, [\n  [\"account_to_recover\", StringSerializer],\n  [\"new_recovery_account\", StringSerializer],\n  [\"extensions\", ArraySerializer(VoidSerializer)],\n]);\n\nOperationSerializers.claim_account = OperationDataSerializer(22, [\n  [\"creator\", StringSerializer],\n  [\"fee\", AssetSerializer],\n  [\"extensions\", ArraySerializer(VoidSerializer)],\n]);\n\nOperationSerializers.claim_reward_balance = OperationDataSerializer(39, [\n  [\"account\", StringSerializer],\n  [\"reward_hive\", AssetSerializer],\n  [\"reward_hbd\", AssetSerializer],\n  [\"reward_vests\", AssetSerializer],\n]);\n\nOperationSerializers.comment = OperationDataSerializer(1, [\n  [\"parent_author\", StringSerializer],\n  [\"parent_permlink\", StringSerializer],\n  [\"author\", StringSerializer],\n  [\"permlink\", StringSerializer],\n  [\"title\", StringSerializer],\n  [\"body\", StringSerializer],\n  [\"json_metadata\", StringSerializer],\n]);\n\nOperationSerializers.comment_options = OperationDataSerializer(19, [\n  [\"author\", StringSerializer],\n  [\"permlink\", StringSerializer],\n  [\"max_accepted_payout\", AssetSerializer],\n  [\"percent_hbd\", UInt16Serializer],\n  [\"allow_votes\", BooleanSerializer],\n  [\"allow_curation_rewards\", BooleanSerializer],\n  [\n    \"extensions\",\n    ArraySerializer(\n      StaticVariantSerializer([\n        ObjectSerializer([[\"beneficiaries\", ArraySerializer(BeneficiarySerializer)]]),\n      ]),\n    ),\n  ],\n]);\n\nOperationSerializers.convert = OperationDataSerializer(8, [\n  [\"owner\", StringSerializer],\n  [\"requestid\", UInt32Serializer],\n  [\"amount\", AssetSerializer],\n]);\n\nOperationSerializers.create_claimed_account = OperationDataSerializer(23, [\n  [\"creator\", StringSerializer],\n  [\"new_account_name\", StringSerializer],\n  [\"owner\", AuthoritySerializer],\n  [\"active\", AuthoritySerializer],\n  [\"posting\", AuthoritySerializer],\n  [\"memo_key\", PublicKeySerializer],\n  [\"json_metadata\", StringSerializer],\n  [\"extensions\", ArraySerializer(VoidSerializer)],\n]);\n\nOperationSerializers.custom = OperationDataSerializer(15, [\n  [\"required_auths\", ArraySerializer(StringSerializer)],\n  [\"id\", UInt16Serializer],\n  [\"data\", VariableBinarySerializer],\n]);\n\nOperationSerializers.custom_binary = OperationDataSerializer(35, [\n  [\"required_owner_auths\", ArraySerializer(StringSerializer)],\n  [\"required_active_auths\", ArraySerializer(StringSerializer)],\n  [\"required_posting_auths\", ArraySerializer(StringSerializer)],\n  [\"required_auths\", ArraySerializer(AuthoritySerializer)],\n  [\"id\", StringSerializer],\n  [\"data\", VariableBinarySerializer],\n]);\n\nOperationSerializers.custom_json = OperationDataSerializer(18, [\n  [\"required_auths\", ArraySerializer(StringSerializer)],\n  [\"required_posting_auths\", ArraySerializer(StringSerializer)],\n  [\"id\", StringSerializer],\n  [\"json\", StringSerializer],\n]);\n\nOperationSerializers.decline_voting_rights = OperationDataSerializer(36, [\n  [\"account\", StringSerializer],\n  [\"decline\", BooleanSerializer],\n]);\n\nOperationSerializers.delegate_vesting_shares = OperationDataSerializer(40, [\n  [\"delegator\", StringSerializer],\n  [\"delegatee\", StringSerializer],\n  [\"vesting_shares\", AssetSerializer],\n]);\n\nOperationSerializers.delete_comment = OperationDataSerializer(17, [\n  [\"author\", StringSerializer],\n  [\"permlink\", StringSerializer],\n]);\n\nOperationSerializers.escrow_approve = OperationDataSerializer(31, [\n  [\"from\", StringSerializer],\n  [\"to\", StringSerializer],\n  [\"agent\", StringSerializer],\n  [\"who\", StringSerializer],\n  [\"escrow_id\", UInt32Serializer],\n  [\"approve\", BooleanSerializer],\n]);\n\nOperationSerializers.escrow_dispute = OperationDataSerializer(28, [\n  [\"from\", StringSerializer],\n  [\"to\", StringSerializer],\n  [\"agent\", StringSerializer],\n  [\"who\", StringSerializer],\n  [\"escrow_id\", UInt32Serializer],\n]);\n\nOperationSerializers.escrow_release = OperationDataSerializer(29, [\n  [\"from\", StringSerializer],\n  [\"to\", StringSerializer],\n  [\"agent\", StringSerializer],\n  [\"who\", StringSerializer],\n  [\"receiver\", StringSerializer],\n  [\"escrow_id\", UInt32Serializer],\n  [\"hbd_amount\", AssetSerializer],\n  [\"hive_amount\", AssetSerializer],\n]);\n\nOperationSerializers.escrow_transfer = OperationDataSerializer(27, [\n  [\"from\", StringSerializer],\n  [\"to\", StringSerializer],\n  [\"hbd_amount\", AssetSerializer],\n  [\"hive_amount\", AssetSerializer],\n  [\"escrow_id\", UInt32Serializer],\n  [\"agent\", StringSerializer],\n  [\"fee\", AssetSerializer],\n  [\"json_meta\", StringSerializer],\n  [\"ratification_deadline\", DateSerializer],\n  [\"escrow_expiration\", DateSerializer],\n]);\n\nOperationSerializers.feed_publish = OperationDataSerializer(7, [\n  [\"publisher\", StringSerializer],\n  [\"exchange_rate\", PriceSerializer],\n]);\n\nOperationSerializers.limit_order_cancel = OperationDataSerializer(6, [\n  [\"owner\", StringSerializer],\n  [\"orderid\", UInt32Serializer],\n]);\n\nOperationSerializers.limit_order_create = OperationDataSerializer(5, [\n  [\"owner\", StringSerializer],\n  [\"orderid\", UInt32Serializer],\n  [\"amount_to_sell\", AssetSerializer],\n  [\"min_to_receive\", AssetSerializer],\n  [\"fill_or_kill\", BooleanSerializer],\n  [\"expiration\", DateSerializer],\n]);\n\nOperationSerializers.limit_order_create2 = OperationDataSerializer(21, [\n  [\"owner\", StringSerializer],\n  [\"orderid\", UInt32Serializer],\n  [\"amount_to_sell\", AssetSerializer],\n  [\"exchange_rate\", PriceSerializer],\n  [\"fill_or_kill\", BooleanSerializer],\n  [\"expiration\", DateSerializer],\n]);\n\nOperationSerializers.recover_account = OperationDataSerializer(25, [\n  [\"account_to_recover\", StringSerializer],\n  [\"new_owner_authority\", AuthoritySerializer],\n  [\"recent_owner_authority\", AuthoritySerializer],\n  [\"extensions\", ArraySerializer(VoidSerializer)],\n]);\n\nOperationSerializers.report_over_production = OperationDataSerializer(16, [\n  [\"reporter\", StringSerializer],\n  [\"first_block\", SignedBlockHeaderSerializer],\n  [\"second_block\", SignedBlockHeaderSerializer],\n]);\n\nOperationSerializers.request_account_recovery = OperationDataSerializer(24, [\n  [\"recovery_account\", StringSerializer],\n  [\"account_to_recover\", StringSerializer],\n  [\"new_owner_authority\", AuthoritySerializer],\n  [\"extensions\", ArraySerializer(VoidSerializer)],\n]);\n\nOperationSerializers.reset_account = OperationDataSerializer(37, [\n  [\"reset_account\", StringSerializer],\n  [\"account_to_reset\", StringSerializer],\n  [\"new_owner_authority\", AuthoritySerializer],\n]);\n\nOperationSerializers.set_reset_account = OperationDataSerializer(38, [\n  [\"account\", StringSerializer],\n  [\"current_reset_account\", StringSerializer],\n  [\"reset_account\", StringSerializer],\n]);\n\nOperationSerializers.set_withdraw_vesting_route = OperationDataSerializer(20, [\n  [\"from_account\", StringSerializer],\n  [\"to_account\", StringSerializer],\n  [\"percent\", UInt16Serializer],\n  [\"auto_vest\", BooleanSerializer],\n]);\n\nOperationSerializers.transfer = OperationDataSerializer(2, [\n  [\"from\", StringSerializer],\n  [\"to\", StringSerializer],\n  [\"amount\", AssetSerializer],\n  [\"memo\", StringSerializer],\n]);\n\nOperationSerializers.transfer_from_savings = OperationDataSerializer(33, [\n  [\"from\", StringSerializer],\n  [\"request_id\", UInt32Serializer],\n  [\"to\", StringSerializer],\n  [\"amount\", AssetSerializer],\n  [\"memo\", StringSerializer],\n]);\n\nOperationSerializers.transfer_to_savings = OperationDataSerializer(32, [\n  [\"from\", StringSerializer],\n  [\"to\", StringSerializer],\n  [\"amount\", AssetSerializer],\n  [\"memo\", StringSerializer],\n]);\n\nOperationSerializers.transfer_to_vesting = OperationDataSerializer(3, [\n  [\"from\", StringSerializer],\n  [\"to\", StringSerializer],\n  [\"amount\", AssetSerializer],\n]);\n\nOperationSerializers.vote = OperationDataSerializer(0, [\n  [\"voter\", StringSerializer],\n  [\"author\", StringSerializer],\n  [\"permlink\", StringSerializer],\n  [\"weight\", Int16Serializer],\n]);\n\nOperationSerializers.withdraw_vesting = OperationDataSerializer(4, [\n  [\"account\", StringSerializer],\n  [\"vesting_shares\", AssetSerializer],\n]);\n\nOperationSerializers.witness_update = OperationDataSerializer(11, [\n  [\"owner\", StringSerializer],\n  [\"url\", StringSerializer],\n  [\"block_signing_key\", PublicKeySerializer],\n  [\"props\", ChainPropertiesSerializer],\n  [\"fee\", AssetSerializer],\n]);\n\nOperationSerializers.witness_set_properties = OperationDataSerializer(42, [\n  [\"owner\", StringSerializer],\n  [\"props\", FlatMapSerializer(StringSerializer, VariableBinarySerializer)],\n  [\"extensions\", ArraySerializer(VoidSerializer)],\n]);\n\nOperationSerializers.account_update2 = OperationDataSerializer(43, [\n  [\"account\", StringSerializer],\n  [\"owner\", OptionalSerializer(AuthoritySerializer)],\n  [\"active\", OptionalSerializer(AuthoritySerializer)],\n  [\"posting\", OptionalSerializer(AuthoritySerializer)],\n  [\"memo_key\", OptionalSerializer(PublicKeySerializer)],\n  [\"json_metadata\", StringSerializer],\n  [\"posting_json_metadata\", StringSerializer],\n  [\"extensions\", ArraySerializer(VoidSerializer)],\n]);\n\nOperationSerializers.create_proposal = OperationDataSerializer(44, [\n  [\"creator\", StringSerializer],\n  [\"receiver\", StringSerializer],\n  [\"start_date\", DateSerializer],\n  [\"end_date\", DateSerializer],\n  [\"daily_pay\", AssetSerializer],\n  [\"subject\", StringSerializer],\n  [\"permlink\", StringSerializer],\n  [\"extensions\", ArraySerializer(VoidSerializer)],\n]);\n\nOperationSerializers.update_proposal_votes = OperationDataSerializer(45, [\n  [\"voter\", StringSerializer],\n  [\"proposal_ids\", ArraySerializer(Int64Serializer)],\n  [\"approve\", BooleanSerializer],\n  [\"extensions\", ArraySerializer(VoidSerializer)],\n]);\n\nOperationSerializers.remove_proposal = OperationDataSerializer(46, [\n  [\"proposal_owner\", StringSerializer],\n  [\"proposal_ids\", ArraySerializer(Int64Serializer)],\n  [\"extensions\", ArraySerializer(VoidSerializer)],\n]);\n\nOperationSerializers.update_proposal = OperationDataSerializer(47, [\n  [\"proposal_id\", UInt64Serializer],\n  [\"creator\", StringSerializer],\n  [\"daily_pay\", AssetSerializer],\n  [\"subject\", StringSerializer],\n  [\"permlink\", StringSerializer],\n  [\n    \"extensions\",\n    ArraySerializer(StaticVariantSerializer([VoidSerializer, ProposalUpdateSerializer])),\n  ],\n]);\n\nOperationSerializers.collateralized_convert = OperationDataSerializer(48, [\n  [\"owner\", StringSerializer],\n  [\"requestid\", UInt32Serializer],\n  [\"amount\", AssetSerializer],\n]);\n\nOperationSerializers.recurrent_transfer = OperationDataSerializer(49, [\n  [\"from\", StringSerializer],\n  [\"to\", StringSerializer],\n  [\"amount\", AssetSerializer],\n  [\"memo\", StringSerializer],\n  [\"recurrence\", UInt16Serializer],\n  [\"executions\", UInt16Serializer],\n  [\"extensions\", ArraySerializer(VoidSerializer)],\n]);\n\nconst OperationSerializer = (buffer: BinaryWriter, operation: Operation) => {\n  const serializer = OperationSerializers[operation[0]];\n  if (!serializer) {\n    throw new Error(`No serializer for operation: ${operation[0]}`);\n  }\n  try {\n    serializer(buffer, operation[1]);\n  } catch (error: unknown) {\n    if (error instanceof Error) {\n      error.message = `${operation[0]}: ${error.message}`;\n      throw error;\n    }\n    throw new Error(`${operation[0]}: ${String(error)}`);\n  }\n};\n\nconst TransactionSerializer = ObjectSerializer([\n  [\"ref_block_num\", UInt16Serializer],\n  [\"ref_block_prefix\", UInt32Serializer],\n  [\"expiration\", DateSerializer],\n  [\"operations\", ArraySerializer(OperationSerializer)],\n  [\"extensions\", ArraySerializer(StringSerializer)],\n]);\n\nconst EncryptedMemoSerializer = ObjectSerializer([\n  [\"from\", PublicKeySerializer],\n  [\"to\", PublicKeySerializer],\n  [\"nonce\", UInt64Serializer],\n  [\"check\", UInt32Serializer],\n  [\"encrypted\", BinarySerializer()],\n]);\n\n/**\n * Hive protocol serializer registry.\n *\n * @remarks\n * `Types` is the internal engine behind transaction signing, transaction id\n * generation, memo envelopes, and witness property encoding. Each member writes\n * one Hive-compatible value into a {@link BinaryWriter}, which is backed by\n * `Uint8Array` and `DataView` rather than legacy byte-buffer dependencies. The\n * object is exported for advanced protocol tooling, but most applications\n * should use higher-level helpers such as `client.broadcast`.\n *\n * @example\n * ```ts\n * const writer = new BinaryWriter()\n * Types.Transaction(writer, transaction)\n *\n * const bytes = writer.getBuffer()\n * ```\n *\n * @throws Error\n * Individual serializers throw when a value cannot be represented in the\n * expected Hive wire format, such as a binary field with the wrong byte length\n * or an operation name with no registered serializer.\n */\nexport const Types = {\n  Array: ArraySerializer,\n  Asset: AssetSerializer,\n  Authority: AuthoritySerializer,\n  Binary: BinarySerializer,\n  Boolean: BooleanSerializer,\n  Date: DateSerializer,\n  EncryptedMemo: EncryptedMemoSerializer,\n  FlatMap: FlatMapSerializer,\n  Int16: Int16Serializer,\n  Int32: Int32Serializer,\n  Int64: Int64Serializer,\n  Int8: Int8Serializer,\n  Object: ObjectSerializer,\n  Operation: OperationSerializer,\n  Optional: OptionalSerializer,\n  Price: PriceSerializer,\n  PublicKey: PublicKeySerializer,\n  StaticVariant: StaticVariantSerializer,\n  String: StringSerializer,\n  Transaction: TransactionSerializer,\n  UInt16: UInt16Serializer,\n  UInt32: UInt32Serializer,\n  UInt64: UInt64Serializer,\n  UInt8: UInt8Serializer,\n  Void: VoidSerializer,\n};\n", "/**\n * Operation filter bitmask constants for condenser_api.get_account_history.\n *\n * Pass the [low, high] pair returned by opFilter() as the 4th and 5th params:\n *   client.call('condenser_api', 'get_account_history', [account, -1, 1000, low, high])\n *\n * All bit positions confirmed empirically against live Hive accounts (2026-06-19).\n * Entries marked ? are inferred from protocol ordering but not yet live-confirmed.\n *\n * BigInt is used throughout to avoid IEEE 754 precision loss. Bits >= 53 cannot\n * be safely represented as Number \u2014 pollen's call() serializes BigInt params\n * correctly via serializeRpcBody().\n */\nexport const OP = {\n  // \u2500\u2500 Regular operations (bits 0\u201349) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  vote: 1n << 0n, // \u2705\n  comment: 1n << 1n, // \u2705\n  transfer: 1n << 2n, // \u2705\n  transfer_to_vesting: 1n << 3n, // \u2705\n  withdraw_vesting: 1n << 4n, // ?\n  limit_order_create: 1n << 5n, // \u2705\n  limit_order_cancel: 1n << 6n, // \u2705\n  feed_publish: 1n << 7n, // \u2705\n  convert: 1n << 8n, // \u2705\n  account_create: 1n << 9n, // \u2705\n  account_update: 1n << 10n, // \u2705\n  witness_update: 1n << 11n, // ?\n  account_witness_vote: 1n << 12n, // ?\n  account_witness_proxy: 1n << 13n, // \u2705\n  custom: 1n << 14n, // ?\n  pow: 1n << 15n, // ?\n  report_over_production: 1n << 16n, // ?\n  delete_comment: 1n << 17n, // \u2705\n  custom_json: 1n << 18n, // \u2705\n  comment_options: 1n << 19n, // \u2705\n  set_withdraw_vesting_route: 1n << 20n, // \u2705\n  limit_order_create2: 1n << 21n, // ?\n  claim_account: 1n << 22n, // \u2705\n  create_claimed_account: 1n << 23n, // \u2705\n  request_account_recovery: 1n << 24n, // ?\n  recover_account: 1n << 25n, // ?\n  change_recovery_account: 1n << 26n, // ?\n  escrow_transfer: 1n << 27n, // ?\n  escrow_dispute: 1n << 28n, // ?\n  escrow_release: 1n << 29n, // ?\n  escrow_approve: 1n << 30n, // ?\n  transfer_to_savings: 1n << 32n, // \u2705 (gap at 31 = pow2?)\n  transfer_from_savings: 1n << 33n, // \u2705\n  cancel_transfer_from_savings: 1n << 34n, // ?\n  custom_binary: 1n << 35n, // ?\n  decline_voting_rights: 1n << 36n, // ?\n  reset_account: 1n << 37n, // ?\n  set_reset_account: 1n << 38n, // ?\n  claim_reward_balance: 1n << 39n, // \u2705\n  delegate_vesting_shares: 1n << 40n, // \u2705\n  account_create_with_delegation: 1n << 41n, // \u2705\n  witness_set_properties: 1n << 42n, // \u2705\n  account_update2: 1n << 43n, // \u2705\n  create_proposal: 1n << 44n, // \u2705\n  update_proposal_votes: 1n << 45n, // \u2705\n  remove_proposal: 1n << 46n, // ?\n  update_proposal: 1n << 47n, // ?\n  collateralized_convert: 1n << 48n, // \u2705\n  recurrent_transfer: 1n << 49n, // \u2705\n\n  // \u2500\u2500 Virtual operations (bits 50+) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  fill_convert_request: 1n << 50n, // \u2705\n  author_reward: 1n << 51n, // \u2705\n  curation_reward: 1n << 52n, // \u2705\n  comment_reward: 1n << 53n, // \u2705\n  liquidity_reward: 1n << 54n, // ?\n  interest: 1n << 55n, // \u2705\n  fill_vesting_withdraw: 1n << 56n, // \u2705\n  fill_order: 1n << 57n, // \u2705\n  shutdown_witness: 1n << 58n, // ?\n  fill_transfer_from_savings: 1n << 59n, // \u2705\n  hardfork: 1n << 60n, // ?\n  comment_payout_update: 1n << 61n, // \u2705\n  return_vesting_delegation: 1n << 62n, // \u2705\n  comment_benefactor_reward: 1n << 63n, // \u2705\n\n  // \u2500\u2500 High-word virtual ops \u2014 contribute to operation_filter_high \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  producer_reward: 1n << 64n, // ?\n  clear_null_account_balance: 1n << 65n, // ?\n  proposal_pay: 1n << 66n, // \u2705\n  sps_fund: 1n << 67n, // ?\n  hardfork_hive: 1n << 68n, // ?\n  hardfork_hive_restore: 1n << 69n, // ?\n  delayed_voting: 1n << 70n, // \u2705\n  consolidate_treasury_balance: 1n << 71n, // ?\n  effective_comment_vote: 1n << 72n, // \u2705\n  ineffective_delete_comment: 1n << 73n, // ?\n  sps_convert: 1n << 74n, // ?\n  expired_account_notification: 1n << 75n, // ?\n  changed_recovery_account: 1n << 76n, // \u2705\n  transfer_to_vesting_completed: 1n << 77n, // \u2705\n  pow_reward: 1n << 78n, // ?\n  vesting_shares_split: 1n << 79n, // ?\n  account_created: 1n << 80n, // \u2705\n  fill_collateralized_convert_request: 1n << 81n, // \u2705\n  system_warning: 1n << 82n, // ?\n  fill_recurrent_transfer: 1n << 83n, // \u2705\n  failed_recurrent_transfer: 1n << 84n, // \u2705\n  limit_order_cancelled: 1n << 85n, // \u2705\n  producer_missed: 1n << 86n, // \u2705\n  proposal_fee: 1n << 87n, // \u2705\n  collateralized_convert_immediate_conversion: 1n << 88n, // \u2705\n  escrow_approved: 1n << 89n, // ?\n  escrow_rejected: 1n << 90n, // ?\n  proxy_cleared: 1n << 91n, // \u2705\n  declined_voting_rights: 1n << 92n, // ?\n} as const;\n\nexport type OpFilterKey = keyof typeof OP;\n\n/**\n * Combines one or more OP bitmasks into the [low, high] BigInt pair expected\n * by condenser_api.get_account_history params 4 and 5.\n *\n * @example\n * ```ts\n * import { OP, opFilter } from '@srbde/pollen'\n *\n * const [low, high] = opFilter(OP.fill_order)\n * const history = await client.call(\n *   'condenser_api', 'get_account_history',\n *   ['myaccount', -1, 1000, low, high]\n * )\n * ```\n */\nexport function opFilter(...ops: bigint[]): [bigint, bigint] {\n  const mask = ops.reduce((a, b) => a | b, 0n);\n  return [\n    mask & 0xffffffffffffffffn, // bits 0\u201363  \u2192 operation_filter_low\n    mask >> 64n, // bits 64+   \u2192 operation_filter_high\n  ];\n}\n", "import { BinaryReader } from \"../utils.js\";\nimport { PublicKey } from \"../crypto.js\";\n\n/**\n * Function signature for reading one Hive protocol value from a binary reader.\n *\n * @param reader - Source binary reader.\n * @returns The decoded protocol value.\n *\n * @remarks\n * Deserializers mirror the serializer registry for the limited binary payloads\n * Pollen needs to decode, currently focused on encrypted memo envelopes. Inputs\n * are native `Uint8Array` bytes or an existing {@link BinaryReader}; no Node\n * `Buffer` wrapper is required.\n *\n * @example\n * ```ts\n * const memo = types.EncryptedMemoD(bytes)\n * console.log(memo.from.toString())\n * ```\n */\nexport type Deserializer = (reader: BinaryReader) => unknown;\n\nconst PublicKeyDeserializer = (reader: BinaryReader) => {\n  const bytes = reader.readBytes(33);\n  return PublicKey.fromBuffer(bytes);\n};\n\nconst UInt64Deserializer = (reader: BinaryReader) => reader.readUint64();\n\nconst UInt32Deserializer = (reader: BinaryReader) => reader.readUint32();\n\nconst BinaryDeserializer = (reader: BinaryReader) => {\n  return reader.readBytes(reader.readVarint32());\n};\n\nconst BufferDeserializer =\n  (keyDeserializers: [string, Deserializer][]) => (buffer: Uint8Array | BinaryReader) => {\n    const reader =\n      typeof (buffer as BinaryReader).readBytes === \"function\"\n        ? (buffer as BinaryReader)\n        : new BinaryReader(buffer as Uint8Array);\n    const obj: Record<string, unknown> = {};\n    for (const [key, deserializer] of keyDeserializers) {\n      try {\n        obj[key] = deserializer(reader);\n      } catch (error: unknown) {\n        if (error instanceof Error) {\n          error.message = `${key}: ${error.message}`;\n          throw error;\n        }\n        throw new Error(`${key}: ${String(error)}`);\n      }\n    }\n    return obj;\n  };\n\nconst EncryptedMemoDeserializer: Deserializer = BufferDeserializer([\n  [\"from\", PublicKeyDeserializer],\n  [\"to\", PublicKeyDeserializer],\n  [\"nonce\", UInt64Deserializer],\n  [\"check\", UInt32Deserializer],\n  [\"encrypted\", BinaryDeserializer],\n]);\n\n/**\n * Hive protocol deserializer registry.\n *\n * @remarks\n * The exported registry intentionally stays small. Pollen primarily receives\n * JSON from RPC nodes, but encrypted memos arrive as binary payloads nested\n * inside base58 strings and need a dedicated decoder.\n *\n * @example\n * ```ts\n * const decoded = types.EncryptedMemoD(bytes)\n * console.log(decoded.nonce.toString())\n * ```\n */\nexport const types = {\n  EncryptedMemoD: EncryptedMemoDeserializer,\n};\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\n\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg<T> = T extends BigInt64Array\n  ? BigInt64Array\n  : T extends BigUint64Array\n    ? BigUint64Array\n    : T extends Float32Array\n      ? Float32Array\n      : T extends Float64Array\n        ? Float64Array\n        : T extends Int16Array\n          ? Int16Array\n          : T extends Int32Array\n            ? Int32Array\n            : T extends Int8Array\n              ? Int8Array\n              : T extends Uint16Array\n                ? Uint16Array\n                : T extends Uint32Array\n                  ? Uint32Array\n                  : T extends Uint8ClampedArray\n                    ? Uint8ClampedArray\n                    : T extends Uint8Array\n                      ? Uint8Array\n                      : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet<T> = T extends BigInt64Array\n  ? ReturnType<typeof BigInt64Array.of>\n  : T extends BigUint64Array\n    ? ReturnType<typeof BigUint64Array.of>\n    : T extends Float32Array\n      ? ReturnType<typeof Float32Array.of>\n      : T extends Float64Array\n        ? ReturnType<typeof Float64Array.of>\n        : T extends Int16Array\n          ? ReturnType<typeof Int16Array.of>\n          : T extends Int32Array\n            ? ReturnType<typeof Int32Array.of>\n            : T extends Int8Array\n              ? ReturnType<typeof Int8Array.of>\n              : T extends Uint16Array\n                ? ReturnType<typeof Uint16Array.of>\n                : T extends Uint32Array\n                  ? ReturnType<typeof Uint32Array.of>\n                  : T extends Uint8ClampedArray\n                    ? ReturnType<typeof Uint8ClampedArray.of>\n                    : T extends Uint8Array\n                      ? ReturnType<typeof Uint8Array.of>\n                      : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg<T> =\n  | T\n  | ([TypedArg<T>] extends [never]\n      ? T extends (...args: infer A) => infer R\n        ? ((...args: { [K in keyof A]: TRet<A[K]> }) => TArg<R>) & {\n            [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;\n          }\n        : T extends [infer A, ...infer R]\n          ? [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n          : T extends readonly [infer A, ...infer R]\n            ? readonly [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n            : T extends (infer A)[]\n              ? TArg<A>[]\n              : T extends readonly (infer A)[]\n                ? readonly TArg<A>[]\n                : T extends Promise<infer A>\n                  ? Promise<TArg<A>>\n                  : T extends object\n                    ? { [K in keyof T]: TArg<T[K]> }\n                    : T\n      : TypedArg<T>);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet<T> = T extends unknown\n  ? T &\n      ([TypedRet<T>] extends [never]\n        ? T extends (...args: infer A) => infer R\n          ? ((...args: { [K in keyof A]: TArg<A[K]> }) => TRet<R>) & {\n              [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;\n            }\n          : T extends [infer A, ...infer R]\n            ? [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n            : T extends readonly [infer A, ...infer R]\n              ? readonly [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n              : T extends (infer A)[]\n                ? TRet<A>[]\n                : T extends readonly (infer A)[]\n                  ? readonly TRet<A>[]\n                  : T extends Promise<infer A>\n                    ? Promise<TRet<A>>\n                    : T extends object\n                      ? { [K in keyof T]: TRet<T[K]> }\n                      : T\n        : TypedRet<T>)\n  : never;\n\n/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - Value to inspect.\n * @returns `true` when the value is a Uint8Array view, including Node's `Buffer`.\n * @example\n * Guards a value before treating it as raw key material.\n *\n * ```ts\n * isBytes(new Uint8Array());\n * ```\n */\nexport function isBytes(a: unknown): a is Uint8Array {\n  // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy /\n  // cross-realm cases. The fallback still requires a real ArrayBuffer view\n  // so plain JSON-deserialized `{ constructor: ... }`\n  // spoofing is rejected, and `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n  return (\n    a instanceof Uint8Array ||\n    (ArrayBuffer.isView(a) &&\n      a.constructor.name === 'Uint8Array' &&\n      'BYTES_PER_ELEMENT' in a &&\n      a.BYTES_PER_ELEMENT === 1)\n  );\n}\n\n/**\n * Asserts something is boolean.\n * @param b - Value to validate.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validates a boolean option before branching on it.\n *\n * ```ts\n * abool(true);\n * ```\n */\nexport function abool(b: boolean): void {\n  if (typeof b !== 'boolean') throw new TypeError(`boolean expected, not ${b}`);\n}\n\n/**\n * Asserts something is a non-negative safe integer.\n * @param n - Value to validate.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validates a non-negative length or counter.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport function anumber(n: number): void {\n  if (typeof n !== 'number') throw new TypeError('number expected, got ' + typeof n);\n  if (!Number.isSafeInteger(n) || n < 0)\n    throw new RangeError('positive integer expected, got ' + n);\n}\n\n/**\n * Asserts something is Uint8Array.\n * @param value - Value to validate.\n * @param length - Expected byte length.\n * @param title - Optional label used in error messages.\n * @returns The validated byte array.\n * On Node, `Buffer` is accepted too because it is a Uint8Array view.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument lengths. {@link RangeError}\n * @example\n * Validates a fixed-length nonce or key buffer.\n *\n * ```ts\n * abytes(new Uint8Array([1, 2]), 2);\n * ```\n */\nexport function abytes(\n  value: TArg<Uint8Array>,\n  length?: number,\n  title: string = ''\n): TRet<Uint8Array> {\n  const bytes = isBytes(value);\n  const len = value?.length;\n  const needsLen = length !== undefined;\n  if (!bytes || (needsLen && len !== length)) {\n    const prefix = title && `\"${title}\" `;\n    const ofLen = needsLen ? ` of length ${length}` : '';\n    const got = bytes ? `length=${len}` : `type=${typeof value}`;\n    const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;\n    if (!bytes) throw new TypeError(message);\n    throw new RangeError(message);\n  }\n  return value as TRet<Uint8Array>;\n}\n\n/**\n * Asserts a hash- or MAC-like instance has not been destroyed or finished.\n * @param instance - Stateful instance to validate.\n * @param checkFinished - Whether to reject finished instances.\n * When `false`, only `destroyed` is checked.\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Guards against calling `update()` or `digest()` on a finished hash.\n *\n * ```ts\n * aexists({ destroyed: false, finished: false });\n * ```\n */\nexport function aexists(instance: any, checkFinished = true): void {\n  if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n  if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/**\n * Asserts output is a properly-sized byte array.\n * @param out - Output buffer to validate.\n * @param instance - Hash-like instance providing `outputLen`.\n * This is the relaxed `digestInto()`-style contract: output must be at least `outputLen`,\n * unlike one-shot cipher helpers elsewhere in the repo that often require exact lengths.\n * @throws On wrong argument types. {@link TypeError}\n * @param onlyAligned - Whether `out` must be 4-byte aligned for zero-allocation word views.\n * @throws On wrong output buffer lengths. {@link RangeError}\n * @throws On wrong output buffer alignment. {@link Error}\n * @example\n * Verifies that a caller-provided output buffer is large enough.\n *\n * ```ts\n * aoutput(new Uint8Array(16), { outputLen: 16 });\n * ```\n */\nexport function aoutput(out: any, instance: any, onlyAligned = false): void {\n  abytes(out, undefined, 'output');\n  const min = instance.outputLen;\n  if (out.length < min) {\n    throw new RangeError('digestInto() expects output buffer of length at least ' + min);\n  }\n  if (onlyAligned && !isAligned32(out)) throw new Error('invalid output, must be aligned');\n}\n\n/** One-shot hash helper with `.create()`. */\nexport type IHash = {\n  (data: string | TArg<Uint8Array>): TRet<Uint8Array>;\n  /** Input block size in bytes. */\n  blockLen: number;\n  /** Digest size in bytes. */\n  outputLen: number;\n  /** Creates a fresh incremental hash instance of the same algorithm. */\n  create: any;\n};\n\n/** One-shot MAC helper with `.create()`. */\nexport type CMac<H extends IHash2 = IHash2, A extends any[] = []> = {\n  (msg: TArg<Uint8Array>, key: TArg<Uint8Array>): TRet<Uint8Array>;\n  /** Input block size in bytes. */\n  blockLen: number;\n  /** Digest size in bytes. */\n  outputLen: number;\n  /**\n   * Creates a fresh incremental MAC instance of the same algorithm.\n   * @param key - MAC key bytes.\n   * @param args - Additional constructor arguments, when the MAC wrapper needs them.\n   * @returns Fresh incremental MAC instance.\n   */\n  create(key: TArg<Uint8Array>, ...args: A): H;\n};\n\n/** Generic type encompassing 8/16/32-bit typed arrays, but not 64-bit. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n  Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/**\n * Casts a typed-array view to Uint8Array.\n * @param arr - Typed-array view to reinterpret.\n * @returns Uint8Array view over the same bytes.\n * @example\n * Views 32-bit words as raw bytes without copying.\n *\n * ```ts\n * u8(new Uint32Array([1]));\n * ```\n */\nexport function u8(arr: TArg<TypedArray>): TRet<Uint8Array> {\n  return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength) as TRet<Uint8Array>;\n}\n\n/**\n * Casts a typed-array view to Uint32Array.\n * @param arr - Typed-array view to reinterpret.\n * @returns Uint32Array view over the same bytes. Callers are expected to provide a\n * 4-byte-aligned offset; trailing `1..3` bytes are silently dropped.\n * @example\n * Views a byte buffer as 32-bit words for block processing.\n *\n * ```ts\n * u32(new Uint8Array(4));\n * ```\n */\nexport function u32(arr: TArg<TypedArray>): TRet<Uint32Array> {\n  return new Uint32Array(\n    arr.buffer,\n    arr.byteOffset,\n    Math.floor(arr.byteLength / 4)\n  ) as TRet<Uint32Array>;\n}\n\n/**\n * Zeroizes typed arrays in place.\n * Warning: JS provides no guarantees.\n * @param arrays - Arrays to wipe.\n * @example\n * Wipes a temporary key buffer after use.\n *\n * ```ts\n * const bytes = new Uint8Array([1]);\n * clean(bytes);\n * ```\n */\nexport function clean(...arrays: TArg<TypedArray[]>): void {\n  for (let i = 0; i < arrays.length; i++) {\n    arrays[i].fill(0);\n  }\n}\n\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - Typed-array view to wrap.\n * @returns DataView over the same bytes.\n * @example\n * Creates an endian-aware view for length encoding.\n *\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr: TArg<TypedArray>): DataView {\n  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/**\n * Whether the current platform is little-endian.\n * Most are; some IBM systems are not.\n */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n  new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/**\n * Reverses byte order of one 32-bit word.\n * @param word - Unsigned 32-bit word to swap.\n * @returns The same word with bytes reversed.\n * @example\n * Swaps a big-endian word into little-endian byte order.\n *\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport const byteSwap = (word: number): number =>\n  ((word << 24) & 0xff000000) |\n  ((word << 8) & 0xff0000) |\n  ((word >>> 8) & 0xff00) |\n  ((word >>> 24) & 0xff);\n\n/**\n * Normalizes one 32-bit word to the little-endian representation expected by cipher cores.\n * @param n - Unsigned 32-bit word to normalize.\n * @returns Little-endian normalized word on big-endian hosts, else the input word unchanged.\n * @example\n * Normalizes a host-endian word before passing it into an ARX/AES core.\n *\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE: (n: number) => number = isLE\n  ? (n: number) => n\n  : (n: number) => byteSwap(n) >>> 0;\n\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - Uint32Array whose words should be swapped.\n * @returns The same array after in-place byte swapping.\n * @example\n * Swaps every 32-bit word in a word-view buffer.\n *\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport const byteSwap32 = (arr: TArg<Uint32Array>): TRet<Uint32Array> => {\n  for (let i = 0; i < arr.length; i++) arr[i] = byteSwap(arr[i]);\n  return arr as TRet<Uint32Array>;\n};\n\n/**\n * Normalizes a Uint32Array view to the little-endian representation expected by cipher cores.\n * @param u - Word view to normalize in place.\n * @returns Little-endian normalized word view.\n * @example\n * Normalizes a word-view buffer before block processing.\n *\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE: (u: TArg<Uint32Array>) => TRet<Uint32Array> = isLE\n  ? (u: TArg<Uint32Array>) => u as TRet<Uint32Array>\n  : byteSwap32;\n\n// Built-in hex conversion:\n// {@link https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex | caniuse entry}\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n  // @ts-ignore\n  typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n  i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @param bytes - Bytes to encode.\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Formats ciphertext bytes for logs or test vectors.\n *\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes: TArg<Uint8Array>): string {\n  abytes(bytes);\n  // @ts-ignore\n  if (hasHexBuiltin) return bytes.toHex();\n  // pre-caching improves the speed 6x\n  let hex = '';\n  for (let i = 0; i < bytes.length; i++) {\n    hex += hexes[bytes[i]];\n  }\n  return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n  if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n  if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n  if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n  return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - Hexadecimal string to decode.\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On malformed hexadecimal input. {@link RangeError}\n * @example\n * Parses a hex test vector into bytes.\n *\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex: string): TRet<Uint8Array> {\n  if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n  if (hasHexBuiltin) {\n    try {\n      return (Uint8Array as any).fromHex(hex);\n    } catch (error) {\n      if (error instanceof SyntaxError) throw new RangeError(error.message);\n      throw error;\n    }\n  }\n  const hl = hex.length;\n  const al = hl / 2;\n  if (hl % 2) throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n  const array = new Uint8Array(al);\n  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n    const n1 = asciiToBase16(hex.charCodeAt(hi));\n    const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n    if (n1 === undefined || n2 === undefined) {\n      const char = hex[hi] + hex[hi + 1];\n      throw new RangeError(\n        'hex string expected, got non-hex character \"' + char + '\" at index ' + hi\n      );\n    }\n    array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n  }\n  return array as TRet<Uint8Array>;\n}\n\n// Used in micro\n/**\n * Converts a big-endian hex string into bigint.\n * @param hex - Hexadecimal string without `0x`.\n * @returns Parsed bigint value. The empty string is treated as `0n`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Parses a big-endian field element or counter from hex.\n *\n * ```ts\n * hexToNumber('ff');\n * ```\n */\nexport function hexToNumber(hex: string): bigint {\n  if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n  return BigInt(hex === '' ? '0' : '0x' + hex); // Big Endian\n}\n\n// Used in ff1\n// BE: Big Endian, LE: Little Endian\n/**\n * Converts big-endian bytes into bigint.\n * @param bytes - Big-endian bytes.\n * @returns Parsed bigint value. Empty input is treated as `0n`.\n * @throws On invalid byte input passed to the internal hex conversion. {@link TypeError}\n * @example\n * Reads a big-endian integer from serialized bytes.\n *\n * ```ts\n * bytesToNumberBE(new Uint8Array([1, 0]));\n * ```\n */\nexport function bytesToNumberBE(bytes: TArg<Uint8Array>): bigint {\n  return hexToNumber(bytesToHex(bytes));\n}\n\n// Used in micro, ff1\n/**\n * Converts a number into big-endian bytes of fixed length.\n * @param n - Number to encode.\n * @param len - Output length in bytes.\n * @returns Big-endian bytes padded to `len`.\n * Validation is indirect through `hexToBytes(...)`, so negative values, `len = 0`,\n * and values that do not fit surface through the downstream hex parser instead of a\n * dedicated range guard here.\n * @throws On wrong argument types. {@link TypeError}\n * @throws If the requested output length cannot represent the encoded value. {@link RangeError}\n * @example\n * Encodes a counter as fixed-width big-endian bytes.\n *\n * ```ts\n * numberToBytesBE(1, 2);\n * ```\n */\nexport function numberToBytesBE(n: number | bigint, len: number): TRet<Uint8Array> {\n  // Reject coercible non-numeric inputs before string/hex conversion changes behavior.\n  if (typeof n === 'number') anumber(n);\n  else if (typeof n !== 'bigint') throw new TypeError(`number or bigint expected, got ${typeof n}`);\n  anumber(len);\n  return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n\n// Global symbols, but ts doesn't see them:\n// {@link https://github.com/microsoft/TypeScript/issues/31535 | TypeScript issue 31535}\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @param str - String to encode.\n * @returns UTF-8 bytes in a detached fresh Uint8Array copy.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encodes application text before encryption or MACing.\n *\n * ```ts\n * utf8ToBytes('abc'); // new Uint8Array([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str: string): TRet<Uint8Array> {\n  if (typeof str !== 'string') throw new TypeError('string expected');\n  return new Uint8Array(new TextEncoder().encode(str)) as TRet<Uint8Array>; // {@link https://bugzil.la/1681809 | Firefox bug 1681809}\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @param bytes - UTF-8 bytes.\n * @returns Decoded string. Input validation is delegated to `TextDecoder`, and malformed\n * UTF-8 is replacement-decoded instead of rejected.\n * @example\n * Decodes UTF-8 plaintext back into a string.\n *\n * ```ts\n * bytesToUtf8(new Uint8Array([97, 98, 99])); // 'abc'\n * ```\n */\nexport function bytesToUtf8(bytes: TArg<Uint8Array>): string {\n  return new TextDecoder().decode(bytes);\n}\n\n/**\n * Checks if two U8A use same underlying buffer and overlaps.\n * This is invalid and can corrupt data.\n * @param a - First byte view.\n * @param b - Second byte view.\n * @returns `true` when the views overlap in memory.\n * @example\n * Detects whether two slices alias the same backing buffer.\n *\n * ```ts\n * overlapBytes(new Uint8Array(4), new Uint8Array(4));\n * ```\n */\nexport function overlapBytes(a: TArg<Uint8Array>, b: TArg<Uint8Array>): boolean {\n  // Zero-length views cannot overwrite anything, even if their offset sits inside another range.\n  if (!a.byteLength || !b.byteLength) return false;\n  return (\n    a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy\n    a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end\n    b.byteOffset < a.byteOffset + a.byteLength // b starts before a end\n  );\n}\n\n/**\n * If input and output overlap and input starts before output, we will overwrite end of input before\n * we start processing it, so this is not supported for most ciphers\n * (except chacha/salsa, which were designed for this)\n * @param input - Input bytes.\n * @param output - Output bytes.\n * @throws If the output view would overwrite unread input bytes. {@link Error}\n * @example\n * Rejects an in-place layout that would overwrite unread input bytes.\n *\n * ```ts\n * complexOverlapBytes(new Uint8Array(4), new Uint8Array(4));\n * ```\n */\nexport function complexOverlapBytes(input: TArg<Uint8Array>, output: TArg<Uint8Array>): void {\n  // This is very cursed. It works somehow, but I'm completely unsure,\n  // reasoning about overlapping aligned windows is very hard.\n  if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)\n    throw new Error('complex overlap of input and output is not supported');\n}\n\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - Byte arrays to concatenate.\n * @returns Combined byte array.\n * @throws On wrong argument types inside the byte-array list. {@link TypeError}\n * @example\n * Builds a `nonce || ciphertext` style buffer.\n *\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays: TArg<Uint8Array[]>): TRet<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 as TRet<Uint8Array>;\n}\n\n// Used in ARX only\ntype EmptyObj = {};\n/**\n * Merges user options into defaults.\n * @param defaults - Default option values.\n * @param opts - User-provided overrides.\n * @returns Combined options object.\n * The merge mutates `defaults` in place and returns the same object.\n * @throws If options are missing or not an object. {@link Error}\n * @example\n * Applies user overrides to the default cipher options.\n *\n * ```ts\n * checkOpts({ rounds: 20 }, { rounds: 8 });\n * ```\n */\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/**\n * Compares two byte arrays in kinda constant time once lengths already match.\n * @param a - First byte array.\n * @param b - Second byte array.\n * @returns `true` when the arrays contain the same bytes. Different lengths still return early.\n * @example\n * Compares an expected authentication tag with the received one.\n *\n * ```ts\n * equalBytes(new Uint8Array([1]), new Uint8Array([1]));\n * ```\n */\nexport function equalBytes(a: TArg<Uint8Array>, b: TArg<Uint8Array>): boolean {\n  if (a.length !== b.length) return false;\n  let diff = 0;\n  for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n  return diff === 0;\n}\n\n// TODO: remove\n/** Incremental hash interface used internally. */\nexport interface IHash2 {\n  /** Bytes processed per compression block. */\n  blockLen: number;\n  /** Bytes produced by the final digest. */\n  outputLen: number;\n  /**\n   * Absorbs one more chunk into the hash state.\n   * @param buf - Data chunk to hash.\n   * @returns The same hash instance for chaining.\n   */\n  update(buf: string | TArg<Uint8Array>): this;\n  /**\n   * Writes the final digest into a caller-provided buffer.\n   * @param buf - Destination buffer for the digest bytes.\n   * @returns Nothing. Implementations write into `buf` in place.\n   */\n  digestInto(buf: TArg<Uint8Array>): void;\n  /**\n   * Finalizes the hash and returns a fresh digest buffer.\n   * @returns Digest bytes.\n   */\n  digest(): TRet<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  destroy(): void;\n}\n\n/**\n * Wraps a keyed MAC constructor into a one-shot helper with `.create()`.\n * @param keyLen - Valid probe-key length used to read static metadata once.\n * The probe key is only used for `outputLen` / `blockLen`, so callers with several valid key sizes\n * can pass any representative size as long as those values stay fixed.\n * @param macCons - Keyed MAC constructor or factory.\n * @param fromMsg - Optional adapter that derives extra constructor args from the one-shot message.\n * @returns Callable MAC helper with `.create()`.\n */\nexport function wrapMacConstructor<H extends IHash2, A extends any[] = []>(\n  keyLen: number,\n  macCons: TArg<(key: Uint8Array, ...args: A) => H>,\n  fromMsg?: TArg<(msg: Uint8Array) => A>\n): TRet<CMac<H, A>> {\n  const mac = macCons as (key: TArg<Uint8Array>, ...args: A) => H;\n  const getArgs = (fromMsg || (() => [] as unknown as A)) as (msg: TArg<Uint8Array>) => A;\n  const macC: any = (msg: TArg<Uint8Array>, key: TArg<Uint8Array>): TRet<Uint8Array> =>\n    mac(key, ...getArgs(msg))\n      .update(msg)\n      .digest();\n  const tmp = mac(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0)));\n  macC.outputLen = tmp.outputLen;\n  macC.blockLen = tmp.blockLen;\n  macC.create = (key: TArg<Uint8Array>, ...args: A) => mac(key, ...args);\n  return macC as TRet<CMac<H, A>>;\n}\n\n// This will allow to re-use with composable things like packed & base encoders\n// Also, we probably can make tags composable\n\n/** Sync cipher: takes byte array and returns byte array. */\nexport type Cipher = {\n  /**\n   * Encrypts plaintext bytes.\n   * @param plaintext - Data to encrypt.\n   * @returns Ciphertext bytes.\n   */\n  encrypt(plaintext: TArg<Uint8Array>): TRet<Uint8Array>;\n  /**\n   * Decrypts ciphertext bytes.\n   * @param ciphertext - Data to decrypt.\n   * @returns Plaintext bytes.\n   */\n  decrypt(ciphertext: TArg<Uint8Array>): TRet<Uint8Array>;\n};\n\n/** Async cipher e.g. from built-in WebCrypto. */\nexport type AsyncCipher = {\n  /**\n   * Encrypts plaintext bytes.\n   * @param plaintext - Data to encrypt.\n   * @returns Promise resolving to ciphertext bytes.\n   */\n  encrypt(plaintext: TArg<Uint8Array>): Promise<TRet<Uint8Array>>;\n  /**\n   * Decrypts ciphertext bytes.\n   * @param ciphertext - Data to decrypt.\n   * @returns Promise resolving to plaintext bytes.\n   */\n  decrypt(ciphertext: TArg<Uint8Array>): Promise<TRet<Uint8Array>>;\n};\n\n/** Cipher with `output` argument which can optimize by doing 1 less allocation. */\nexport type CipherWithOutput = Cipher & {\n  /**\n   * Encrypts plaintext bytes into an optional caller-provided buffer.\n   * @param plaintext - Data to encrypt.\n   * @param output - Optional destination buffer.\n   * @returns Ciphertext bytes.\n   */\n  encrypt(plaintext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array>;\n  /**\n   * Decrypts ciphertext bytes into an optional caller-provided buffer.\n   * @param ciphertext - Data to decrypt.\n   * @param output - Optional destination buffer.\n   * @returns Plaintext bytes.\n   */\n  decrypt(ciphertext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array>;\n};\n\n/**\n * Params are outside of return type, so it is accessible before calling constructor.\n * If function support multiple nonceLength's, we return the best one.\n */\nexport type CipherParams = {\n  /** Cipher block size in bytes. */\n  blockSize: number;\n  /** Nonce length in bytes when the cipher uses a fixed nonce size. */\n  nonceLength?: number;\n  /** Authentication-tag length in bytes for AEAD modes. */\n  tagLength?: number;\n  /** Whether nonce length is variable at runtime. */\n  varSizeNonce?: boolean;\n};\n/**\n * ARX AEAD cipher, like salsa or chacha.\n * @param key - Secret key bytes.\n * @param nonce - Nonce bytes.\n * @param AAD - Optional associated data.\n * @returns Cipher instance with caller-managed output buffers.\n */\nexport type ARXCipher = ((\n  key: TArg<Uint8Array>,\n  nonce: TArg<Uint8Array>,\n  AAD?: TArg<Uint8Array>\n) => CipherWithOutput) & {\n  blockSize: number;\n  nonceLength: number;\n  tagLength: number;\n};\n/**\n * Cipher constructor signature.\n * @param key - Secret key bytes.\n * @param args - Additional constructor arguments, such as nonce or IV.\n * @returns Cipher instance.\n */\nexport type CipherCons<T extends any[]> = (key: TArg<Uint8Array>, ...args: T) => Cipher;\n/**\n * Wraps a cipher: validates args, ensures encrypt() can only be called once.\n * Used internally by the exported cipher constructors.\n * Output-buffer support is inferred from the wrapped `encrypt` / `decrypt`\n * arity (`fn.length === 2`), and tag-bearing constructors are expected to use\n * `args[1]` for optional AAD.\n * @__NO_SIDE_EFFECTS__\n * @param params - Static cipher metadata. See {@link CipherParams}.\n * @param constructor - Cipher constructor.\n * @returns Wrapped constructor with validation.\n */\nexport const wrapCipher = <C extends CipherCons<any>, P extends CipherParams>(\n  params: P,\n  constructor: C\n): C & P => {\n  function wrappedCipher(key: TArg<Uint8Array>, ...args: any[]): TRet<CipherWithOutput> {\n    // Validate key\n    abytes(key, undefined, 'key');\n\n    // Validate nonce if nonceLength is present\n    if (params.nonceLength !== undefined) {\n      const nonce = args[0];\n      abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, 'nonce');\n    }\n\n    // Validate AAD if tagLength present\n    const tagl = params.tagLength;\n    if (tagl && args[1] !== undefined) abytes(args[1], undefined, 'AAD');\n\n    const cipher = constructor(key, ...args);\n    const checkOutput = (fnLength: number, output?: TArg<Uint8Array>) => {\n      if (output !== undefined) {\n        if (fnLength !== 2) throw new Error('cipher output not supported');\n        abytes(output, undefined, 'output');\n      }\n    };\n    // Create wrapped cipher with validation and single-use encryption\n    let called = false;\n    const wrCipher = {\n      encrypt(data: TArg<Uint8Array>, output?: TArg<Uint8Array>) {\n        if (called) throw new Error('cannot encrypt() twice with same key + nonce');\n        called = true;\n        abytes(data);\n        checkOutput(cipher.encrypt.length, output);\n        return (cipher as CipherWithOutput).encrypt(data, output);\n      },\n      decrypt(data: TArg<Uint8Array>, output?: TArg<Uint8Array>) {\n        abytes(data);\n        if (tagl && data.length < tagl)\n          throw new Error('\"ciphertext\" expected length bigger than tagLength=' + tagl);\n        checkOutput(cipher.decrypt.length, output);\n        return (cipher as CipherWithOutput).decrypt(data, output);\n      },\n    };\n\n    return wrCipher as TRet<CipherWithOutput>;\n  }\n\n  Object.assign(wrappedCipher, params);\n  return wrappedCipher as C & P;\n};\n\n/**\n * Represents a Salsa or ChaCha xor stream.\n * @param key - Secret key bytes.\n * @param nonce - Nonce bytes.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Optional starting block counter.\n * @returns Output bytes.\n */\nexport type XorStream = (\n  key: TArg<Uint8Array>,\n  nonce: TArg<Uint8Array>,\n  data: TArg<Uint8Array>,\n  output?: TArg<Uint8Array>,\n  counter?: number\n) => TRet<Uint8Array>;\n\n/**\n * By default, returns u8a of length.\n * When out is available, it checks it for validity and uses it.\n * @param expectedLength - Required output length.\n * @param out - Optional destination buffer.\n * @param onlyAligned - Whether `out` must be 4-byte aligned.\n * @returns Output buffer ready for writing.\n * @throws On wrong argument types. {@link TypeError}\n * @throws If the provided output buffer has the wrong size or alignment. {@link Error}\n * @example\n * Reuses a caller-provided output buffer when lengths match.\n *\n * ```ts\n * getOutput(16, new Uint8Array(16));\n * ```\n */\nexport function getOutput(\n  expectedLength: number,\n  out?: TArg<Uint8Array>,\n  onlyAligned = true\n): TRet<Uint8Array> {\n  if (out === undefined) return new Uint8Array(expectedLength) as TRet<Uint8Array>;\n  // Keep Buffer/cross-realm Uint8Array support here instead of trusting a shape-compatible object.\n  abytes(out, undefined, 'output');\n  if (out.length !== expectedLength)\n    throw new Error(\n      '\"output\" expected Uint8Array of length ' + expectedLength + ', got: ' + out.length\n    );\n  if (onlyAligned && !isAligned32(out)) throw new Error('invalid output, must be aligned');\n  return out as TRet<Uint8Array>;\n}\n\n/**\n * Encodes data and AAD bit lengths into a 16-byte buffer.\n * @param dataLength - Data length in bits.\n * @param aadLength - AAD length in bits.\n * The serialized block is still `aadLength || dataLength`, matching GCM/Poly1305\n * conventions even though the helper parameter order is `(dataLength, aadLength)`.\n * @param isLE - Whether to encode lengths as little-endian.\n * @returns 16-byte length block.\n * @throws On wrong argument types passed to the endian validator. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Builds the length block appended by GCM and Poly1305.\n *\n * ```ts\n * u64Lengths(16, 8, true);\n * ```\n */\nexport function u64Lengths(dataLength: number, aadLength: number, isLE: boolean): TRet<Uint8Array> {\n  // Reject coercible non-number lengths like '10' and true before BigInt(...) accepts them.\n  anumber(dataLength);\n  anumber(aadLength);\n  abool(isLE);\n  const num = new Uint8Array(16);\n  const view = createView(num);\n  view.setBigUint64(0, BigInt(aadLength), isLE);\n  view.setBigUint64(8, BigInt(dataLength), isLE);\n  return num as TRet<Uint8Array>;\n}\n\n/**\n * Checks whether a byte array is aligned to a 4-byte offset.\n * @param bytes - Byte array to inspect.\n * @returns `true` when the view is 4-byte aligned.\n * @example\n * Checks whether a buffer can be safely viewed as Uint32Array.\n *\n * ```ts\n * isAligned32(new Uint8Array(4));\n * ```\n */\nexport function isAligned32(bytes: TArg<Uint8Array>): boolean {\n  return bytes.byteOffset % 4 === 0;\n}\n\n/**\n * Copies bytes into a new Uint8Array.\n * @param bytes - Bytes to copy.\n * @returns Copied byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Copies input into an aligned Uint8Array before block processing.\n *\n * ```ts\n * copyBytes(new Uint8Array([1, 2]));\n * ```\n */\nexport function copyBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array> {\n  // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n  // because callers use it at byte-validation boundaries before mutating the detached copy.\n  return Uint8Array.from(abytes(bytes)) as TRet<Uint8Array>;\n}\n\n/**\n * Cryptographically secure PRNG.\n * Uses internal OS-level `crypto.getRandomValues`.\n * @param bytesLength - Number of bytes to produce.\n * Validation is delegated to `Uint8Array(bytesLength)` and `getRandomValues`, so\n * non-integers, negative lengths, and oversize requests surface backend/runtime errors.\n * @returns Random byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the runtime does not expose `crypto.getRandomValues`. {@link Error}\n * @example\n * Generates a fresh nonce or key.\n *\n * ```ts\n * randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32): TRet<Uint8Array> {\n  // Validate upfront so fractional / coercible lengths do not silently\n  // truncate through Uint8Array().\n  anumber(bytesLength);\n  const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n  if (typeof cr?.getRandomValues !== 'function')\n    throw new Error('crypto.getRandomValues must be defined');\n  return cr.getRandomValues(new Uint8Array(bytesLength)) as TRet<Uint8Array>;\n}\n\n/**\n * The pseudorandom number generator doesn't wipe current state:\n * instead, it generates new one based on previous state + entropy.\n * Not reseed/rekey, since AES CTR DRBG does rekey on each randomBytes,\n * which is in fact `reseed`, since it changes counter too.\n */\nexport interface PRG {\n  /**\n   * Mixes fresh entropy into the current generator state.\n   * @param seed - Entropy bytes to absorb.\n   */\n  addEntropy(seed: TArg<Uint8Array>): void;\n  /**\n   * Produces a requested number of pseudorandom bytes.\n   * @param bytesLength - Number of bytes to generate.\n   * @returns Random byte array.\n   */\n  randomBytes(bytesLength: number): TRet<Uint8Array>;\n  /** Destroys the generator state. */\n  clean(): void;\n}\n\n/** Removes the nonce argument from a cipher constructor type. */\nexport type RemoveNonce<T extends (...args: any) => any> = T extends (\n  arg0: any,\n  arg1: any,\n  ...rest: infer R\n) => infer Ret\n  ? (key: TArg<Uint8Array>, ...args: R) => Ret\n  : never;\n/**\n * Cipher constructor that requires a nonce argument.\n * @param key - Secret key bytes.\n * @param nonce - Nonce bytes.\n * @param args - Additional cipher-specific arguments.\n * @returns Cipher instance.\n */\nexport type CipherWithNonce = ((\n  key: TArg<Uint8Array>,\n  nonce: TArg<Uint8Array>,\n  ...args: any[]\n) => Cipher | AsyncCipher) & {\n  nonceLength: number;\n};\n\n/**\n * Uses CSPRNG for nonce, nonce injected in ciphertext.\n * For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and\n * prepended to encrypted ciphertext. For `decrypt`, first `nonceBytes` of ciphertext\n * are treated as nonce. The wrapper always allocates a fresh `nonce || ciphertext`\n * buffer on encrypt and intentionally does not support caller-provided destination buffers.\n * Too-short decrypt inputs are split into short/empty nonce views and then delegated\n * to the wrapped cipher instead of being rejected here first.\n *\n * NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha\n * should be limited to `2**23` (8M) messages to get a collision chance of\n * `2**-50`. Stretching to `2**32` (4B) messages would raise that chance to\n * `2**-33`, still negligible but creeping up.\n * @param fn - Cipher constructor that expects a nonce.\n * @param randomBytes_ - Random-byte source used for nonce generation.\n * @returns Cipher constructor that prepends the nonce to ciphertext.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On invalid nonce lengths observed at wrapper construction or use. {@link RangeError}\n * @example\n * Prepends a fresh random nonce to every ciphertext.\n *\n * ```ts\n * import { gcm } from '@noble/ciphers/aes.js';\n * import { managedNonce, randomBytes } from '@noble/ciphers/utils.js';\n * const wrapped = managedNonce(gcm);\n * const key = randomBytes(16);\n * const ciphertext = wrapped(key).encrypt(new Uint8Array([1, 2, 3]));\n * wrapped(key).decrypt(ciphertext);\n * ```\n */\nexport function managedNonce<T extends CipherWithNonce>(\n  fn: T,\n  randomBytes_: typeof randomBytes = randomBytes\n): TRet<RemoveNonce<T>> {\n  const { nonceLength } = fn;\n  anumber(nonceLength);\n  const addNonce = (\n    nonce: TArg<Uint8Array>,\n    ciphertext: TArg<Uint8Array>,\n    plaintext: TArg<Uint8Array>\n  ) => {\n    const out = concatBytes(nonce, ciphertext);\n    // Wrapped ciphers may alias caller plaintext on encrypt(); never zero\n    // caller-owned buffers here.\n    if (!overlapBytes(plaintext, ciphertext)) ciphertext.fill(0);\n    return out;\n  };\n  // NOTE: we cannot support DST here, it would be mistake:\n  // - we don't know how much dst length cipher requires\n  // - nonce may unalign dst and break everything\n  // - we create new u8a anyway (concatBytes)\n  // - previously we passed all args to cipher, but that was mistake!\n  const res = ((key: TArg<Uint8Array>, ...args: any[]): any => ({\n    encrypt(plaintext: TArg<Uint8Array>) {\n      abytes(plaintext);\n      const nonce = randomBytes_(nonceLength);\n      const encrypted = fn(key, nonce, ...args).encrypt(plaintext);\n      // @ts-ignore\n      if (encrypted instanceof Promise)\n        return encrypted.then((ct) => addNonce(nonce, ct, plaintext));\n      return addNonce(nonce, encrypted, plaintext);\n    },\n    decrypt(ciphertext: TArg<Uint8Array>) {\n      abytes(ciphertext);\n      const nonce = ciphertext.subarray(0, nonceLength);\n      const decrypted = ciphertext.subarray(nonceLength);\n      return fn(key, nonce, ...args).decrypt(decrypted);\n    },\n  })) as RemoveNonce<T> & { blockSize?: number; tagLength?: number };\n  // Auto-nonce wrappers still preserve the wrapped payload geometry.\n  if ('blockSize' in fn) res.blockSize = (fn as any).blockSize;\n  if ('tagLength' in fn) res.tagLength = (fn as any).tagLength;\n  return res as TRet<RemoveNonce<T>>;\n}\n\n/** `Uint8Array.of()` return type helper for TS 5.9. */\nexport type Uint8ArrayBuffer = TRet<Uint8Array>;\n", "/**\n * {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard | AES}\n * a.k.a. Advanced Encryption Standard\n * is a variant of Rijndael block cipher, standardized by NIST in 2001.\n * We provide the fastest available pure JS implementation.\n *\n * `cipher = encrypt(block, key)`\n *\n * Data is split into 128-bit blocks.\n * Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:\n * 1. **S-box**, table substitution\n * 2. **Shift rows**, cyclic shift left of all rows of data array\n * 3. **Mix columns**, multiplying every column by fixed polynomial\n * 4. **Add round key**, round_key xor i-th column of array\n *\n * Check out\n * {@link https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf | FIPS-197},\n * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST 800-38G},\n * and {@link https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf | original proposal}.\n * @module\n */\nimport { ghash, polyval } from './_polyval.ts';\n// prettier-ignore\nimport {\n  abytes, anumber, aoutput,\n  byteSwap,\n  clean, complexOverlapBytes, concatBytes,\n  copyBytes, createView, equalBytes, getOutput, isAligned32,\n  isLE,\n  overlapBytes,\n  swap32IfBE,\n  swap8IfBE,\n  u32, u64Lengths, u8, wrapCipher, wrapMacConstructor,\n  type Cipher, type CipherWithOutput,\n  type CMac, type IHash2,\n  type PRG, type TArg, type TRet, type Uint8ArrayBuffer\n} from './utils.ts';\n\nconst BLOCK_SIZE = 16;\n// AES operates on 16-byte blocks, i.e. 4 32-bit words.\nconst BLOCK_SIZE32 = 4;\n// Shared zero block (`0^128`) used by GCM's `H = CIPH_K(0^128)` / J0 scratch\n// and by CMAC / SIV helpers; callers take `.slice()` before mutating it.\nconst EMPTY_BLOCK = /* @__PURE__ */ new Uint8Array(BLOCK_SIZE);\n// RFC 5297 \u00A72.1 / \u00A72.4: S2V uses `<one> = 0^127 || 1` for the `n = 0` special case.\nconst ONE_BLOCK = /* @__PURE__ */ Uint8Array.from([\n  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,\n]);\nconst POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8\n// Validates plain AES key sizes only; AES-SIV's doubled-key contract is checked elsewhere.\nfunction validateKeyLength(key: TArg<Uint8Array>) {\n  if (![16, 24, 32].includes(key.length))\n    throw new Error('\"aes key\" expected Uint8Array of length 16/24/32, got length=' + key.length);\n}\n\n// TODO: remove multiplication, binary ops only\n// Doubles one GF(2^8) field element; callers are expected to stay in byte range.\n// FIPS 197 upd1 \u00A74.3 equation (4.5): XTIMES(b) left-shifts by one and, when\n// b7=1, reduces by m(x); using POLY=0x11b here yields the same byte result\n// as XORing with {1b} after the shift.\nfunction mul2(n: number) {\n  return (n << 1) ^ (POLY & -(n >> 7));\n}\n\n// Shift-and-add multiplication in GF(2^8); callers are expected to pass byte values.\n// FIPS 197 upd1 \u00A74.3 equation (4.7): general products are XORs of repeated\n// XTIMES() multiples, e.g. {57}\u2022{13} = {57}\u2295{ae}\u2295{07}.\nfunction mul(a: number, b: number) {\n  let res = 0;\n  for (; b > 0; b >>= 1) {\n    // Usual shift-and-add step in GF(2^8), not a scalar-multiplication 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/**\n * Increments a counter block with wrap around.\n * AES call sites here currently use the big-endian branch, but the helper supports both layouts.\n * NIST SP 800-38A Appendix B.1 and SP 800-38D \u00A76.2 increment the\n * least-significant/rightmost bits.\n * `isLE=false` matches that standard counter-block layout, while `isLE=true`\n * is a generic extension for non-AES callers.\n * The implementation keeps a 32-bit bitwise carry path, so `carry` is capped at `0xffffff00`;\n * larger values throw instead of silently overflowing before the next-byte propagation step.\n */\n// Keep the helper explicitly typed so `--isolatedDeclarations` can expose it\n// through the test-only `__TESTS` export without inference errors.\nconst incBytes: (data: TArg<Uint8Array>, isLE: boolean, carry?: number) => void = (\n  data: TArg<Uint8Array>,\n  isLE: boolean,\n  carry: number = 1\n): void => {\n  // Keep `carry + byte <= 0xffffffff` so the `| 0` / `>>> 8` path below\n  // never truncates a real carry bit.\n  if (!Number.isSafeInteger(carry) || carry > 0xffffff00)\n    throw new Error('incBytes: wrong carry ' + carry);\n  abytes(data);\n  for (let i = 0; i < data.length; i++) {\n    const pos = !isLE ? data.length - 1 - i : i;\n    carry = (carry + (data[pos] & 0xff)) | 0;\n    data[pos] = carry & 0xff;\n    carry >>>= 8;\n  }\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  const t = new Uint8Array(256);\n  // Repeated multiplication by {03} walks all 255 nonzero field elements\n  // once, so t[255 - i] is the multiplicative inverse of t[i] for the\n  // affine step.\n  for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x)) t[i] = x;\n  const box = new Uint8Array(256);\n  // FIPS 197 upd1 \u00A75.1.1: SBOX({00}) = {63} because the inverse step leaves\n  // {00} at {00}, then the affine transform xors in c = {63}.\n  box[0] = 0x63;\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  clean(t);\n  return box;\n})();\n\n// FIPS 197 upd1 \u00A75.3.2: INVSBOX() is derived from SBOX() by swapping input\n// and output roles (Table 6).\n// `indexOf` is only used once at module init, so the quadratic setup cost stays off hot paths.\nconst invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));\n\n// FIPS 197 upd1 \u00A75.2: ROTWORD([a0,a1,a2,a3]) = [a1,a2,a3,a0]; with this LE\n// word packing that is a right rotate by 8 bits.\nconst rotr32_8 = (n: number) => (n << 24) | (n >>> 8);\n// LE T-table helper: rotates one precomputed word by one byte so T1/T2/T3\n// reuse T0's substitution/mix result in the other byte lanes.\nconst rotl32_8 = (n: number) => (n << 8) | (n >>> 24);\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: TArg<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  // Pre-xor adjacent lanes so apply0123/applySbox can fetch two substituted\n  // byte lanes per lookup in the LE round layout.\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\n// Forward round precompute: the packed word stores the MIXCOLUMNS row\n// [{02},{01},{01},{03}] in LE byte-lane order, and the returned `sbox2`\n// is also reused by key expansion and the final round.\nconst tableEncoding = /* @__PURE__ */ genTtable(\n  sbox,\n  (s: number) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2)\n);\n// Inverse round precompute: the packed word stores the INVMIXCOLUMNS row\n// [{0e},{09},{0d},{0b}] in LE byte-lane order, and the tables are reused\n// by decrypt() and expandKeyDecLE().\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\n// FIPS 197 upd1 \u00A75.2 Table 5: left-most bytes of Rcon[j] = x^(j-1), generated by repeated XTIMES().\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\n/** Forward AES key expansion used across ECB/CBC/CTR/GCM/CMAC/KW-style paths. */\nfunction expandKeyLE(key: TArg<Uint8Array>): TRet<Uint32Array> {\n  abytes(key);\n  const len = key.length;\n  validateKeyLength(key);\n  const { sbox2 } = tableEncoding;\n  const toClean = [];\n  // Copy on BE or misaligned inputs so the LE word normalization below never\n  // mutates caller key bytes in place.\n  if (!isLE || !isAligned32(key)) toClean.push((key = copyBytes(key)));\n  const k32 = swap32IfBE(u32(key));\n  const Nk = k32.length;\n  // `applySbox` normally reads one byte lane from each argument; repeating\n  // `n` across all four lanes turns it into SUBWORD(n).\n  const subByte = (n: number) => applySbox(sbox2, n, n, n, n);\n  // AES key sizes are 16/24/32 bytes, so len + 28 yields the 44/52/60\n  // schedule words from FIPS 197 \u00A75.2 / Table 3.\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  clean(...toClean);\n  return xk as TRet<Uint32Array>;\n}\n\nfunction expandKeyDecLE(key: TArg<Uint8Array>): TRet<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  // Local decrypt() walks round keys forward from xk[0], so reverse the\n  // encryption round-key blocks first before applying the equivalent-inverse\n  // middle-round transform.\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  clean(encKey);\n  // Apply InvMixColumn to the reversed round keys using the same LE sbox2\n  // packing as the forward path.\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 as TRet<Uint32Array>;\n}\n\n// Apply tables\nfunction apply0123(\n  T01: TArg<Uint32Array>,\n  T23: TArg<Uint32Array>,\n  s0: number,\n  s1: number,\n  s2: number,\n  s3: number\n) {\n  // `T01` takes the low byte lane from `s0` plus the next lane from `s1`;\n  // `T23` does the same for `s2`/`s3`.\n  // Equivalent to `T0[s0&0xff] ^ T1[(s1>>>8)&0xff] ^ T2[(s2>>>16)&0xff] ^\n  // T3[s3>>>24]`, but with two merged-table fetches.\n  return (\n    T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^\n    T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]\n  );\n}\n\nfunction applySbox(sbox2: TArg<Uint16Array>, s0: number, s1: number, s2: number, s3: number) {\n  // `sbox2` packs two substituted byte lanes at a time in the same LE\n  // layout used by the round code.\n  // Equivalent to `SBOX(byte0(s0)) | SBOX(byte1(s1))<<8 |\n  // SBOX(byte2(s2))<<16 | SBOX(byte3(s3))<<24`.\n  return (\n    sbox2[(s0 & 0xff) | (s1 & 0xff00)] |\n    (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16)\n  );\n}\n\nfunction encrypt(\n  xk: TArg<Uint32Array>,\n  s0: number,\n  s1: number,\n  s2: number,\n  s3: number\n): { 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  // `xk` has Nr+1 round-key blocks, so after the initial AddRoundKey and the\n  // final S-box-only round there are Nr-1 full table/MixColumns rounds left.\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\n// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different\nfunction decrypt(\n  xk: TArg<Uint32Array>,\n  s0: number,\n  s1: number,\n  s2: number,\n  s3: number\n): {\n  s0: number;\n  s1: number;\n  s2: number;\n  s3: number;\n} {\n  const { sbox2, T01, T23 } = tableDecoding;\n  let k = 0;\n  ((s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]));\n  // With `expandKeyDecLE()` the round keys are already reversed and middle\n  // rounds are InvMixColumns-adjusted, so this loop follows the equivalent\n  // inverse cipher order directly.\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  // Final equivalent-inverse round omits InvMixColumns, so use inverse\n  // S-box lanes in InvShiftRows order.\n  const t0: number = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);\n  const t1: number = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);\n  const t2: number = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);\n  const t3: number = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);\n  return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n\nfunction ctrCounter(\n  xk: TArg<Uint32Array>,\n  nonce: TArg<Uint8Array>,\n  src: TArg<Uint8Array>,\n  dst?: TArg<Uint8Array>\n): TRet<Uint8Array> {\n  abytes(nonce, BLOCK_SIZE, 'nonce');\n  abytes(src);\n  const srcLen = src.length;\n  dst = getOutput(srcLen, dst);\n  complexOverlapBytes(src, dst);\n  // Internal helper: mutate `nonce` in place as the live counter block so\n  // each encrypted block uses the next CTR value.\n  const ctr = nonce;\n  const c32 = u32(ctr);\n  const src32 = u32(src);\n  const dst32 = u32(dst);\n  // Fill block (empty, ctr=0)\n  let { s0, s1, s2, s3 } = encrypt(\n    xk,\n    swap8IfBE(c32[0]),\n    swap8IfBE(c32[1]),\n    swap8IfBE(c32[2]),\n    swap8IfBE(c32[3])\n  );\n  // process blocks\n  for (let i = 0; i + 4 <= src32.length; i += 4) {\n    dst32[i + 0] = src32[i + 0] ^ swap8IfBE(s0);\n    dst32[i + 1] = src32[i + 1] ^ swap8IfBE(s1);\n    dst32[i + 2] = src32[i + 2] ^ swap8IfBE(s2);\n    dst32[i + 3] = src32[i + 3] ^ swap8IfBE(s3);\n    incBytes(ctr, false, 1); // Full 128 bit counter with wrap around\n    ({ s0, s1, s2, s3 } = encrypt(\n      xk,\n      swap8IfBE(c32[0]),\n      swap8IfBE(c32[1]),\n      swap8IfBE(c32[2]),\n      swap8IfBE(c32[3])\n    ));\n  }\n  // NIST SP 800-38A CTR mode uses the leading `u` bits of the next output\n  // block for the final short 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    swap32IfBE(b32);\n    const buf = u8(b32);\n    for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];\n    clean(b32);\n  }\n  // Unsafe mutable-counter API only advances whole blocks. Callers that want to\n  // resume after consuming part of this block must re-run from the same counter\n  // with left-padding and strip the already-consumed prefix themselves.\n  return dst as TRet<Uint8Array>;\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.\n// Unsafe 32-bit CTR helper: mutates `nonce` in place, expects aligned `src`/`dst`,\n// and uses `isLE` to choose which 32-bit counter word is incremented.\nfunction ctr32(\n  xk: TArg<Uint32Array>,\n  isLE: boolean,\n  nonce: TArg<Uint8Array>,\n  src: TArg<Uint8Array>,\n  dst?: TArg<Uint8Array>\n): TRet<Uint8Array> {\n  abytes(nonce, BLOCK_SIZE, 'nonce');\n  abytes(src);\n  dst = getOutput(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  // NIST SP 800-38D GCTR increments the rightmost 32 bits of J0, while\n  // RFC 8452 AES-GCM-SIV increments the first 32 bits as a little-endian u32.\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(\n    xk,\n    swap8IfBE(c32[0]),\n    swap8IfBE(c32[1]),\n    swap8IfBE(c32[2]),\n    swap8IfBE(c32[3])\n  );\n  // process blocks\n  for (let i = 0; i + 4 <= src32.length; i += 4) {\n    dst32[i + 0] = src32[i + 0] ^ swap8IfBE(s0);\n    dst32[i + 1] = src32[i + 1] ^ swap8IfBE(s1);\n    dst32[i + 2] = src32[i + 2] ^ swap8IfBE(s2);\n    dst32[i + 3] = src32[i + 3] ^ swap8IfBE(s3);\n    ctrNum = (ctrNum + 1) >>> 0; // u32 wrap\n    view.setUint32(ctrPos, ctrNum, isLE);\n    ({ s0, s1, s2, s3 } = encrypt(\n      xk,\n      swap8IfBE(c32[0]),\n      swap8IfBE(c32[1]),\n      swap8IfBE(c32[2]),\n      swap8IfBE(c32[3])\n    ));\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    swap32IfBE(b32);\n    const buf = u8(b32);\n    for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];\n    clean(b32);\n  }\n  // Same unsafe contract as ctrCounter(): only full blocks advance the stored\n  // mutable counter state; partial-block continuation is caller-managed.\n  return dst as TRet<Uint8Array>;\n}\n\n/**\n * **CTR** (Counter Mode): turns a block cipher into a stream cipher using a\n * full 16-byte counter block.\n * Efficient and parallelizable. Requires a unique nonce per encryption. Unauthenticated: needs MAC.\n * @param key - AES key bytes.\n * @param nonce - 16-byte counter block, incremented as a full AES block.\n * @returns Cipher instance with `encrypt()` and `decrypt()`.\n * @example\n * Encrypts a short payload with a fresh AES key and counter block.\n *\n * ```ts\n * import { ctr } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const nonce = randomBytes(16);\n * const cipher = ctr(key, nonce);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const ctr: TRet<\n  ((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>) => CipherWithOutput) & {\n    blockSize: number;\n    nonceLength: number;\n  }\n> = /* @__PURE__ */ wrapCipher(\n  { blockSize: 16, nonceLength: 16 },\n  function aesctr(key: TArg<Uint8Array>, nonce: TArg<Uint8Array>): TRet<CipherWithOutput> {\n    function processCtr(buf: TArg<Uint8Array>, dst?: TArg<Uint8Array>): TRet<Uint8Array> {\n      abytes(buf);\n      if (dst !== undefined) {\n        abytes(dst);\n        // Optional output buffers must stay 4-byte aligned because\n        // ctrCounter() reinterprets them as Uint32Array words.\n        if (!isAligned32(dst)) throw new Error('unaligned destination');\n      }\n      const xk = expandKeyLE(key);\n      // Public CTR keeps caller nonce bytes immutable even though ctrCounter()\n      // advances the live 16-byte counter block in place.\n      const n = copyBytes(nonce); // align + avoid changing\n      const toClean = [xk, n];\n      if (!isAligned32(buf)) toClean.push((buf = copyBytes(buf)));\n      const out = ctrCounter(xk, n, buf, dst);\n      clean(...toClean);\n      return out as TRet<Uint8Array>;\n    }\n    return {\n      encrypt: (plaintext: TArg<Uint8Array>, dst?: TArg<Uint8Array>) => processCtr(plaintext, dst),\n      decrypt: (ciphertext: TArg<Uint8Array>, dst?: TArg<Uint8Array>) =>\n        processCtr(ciphertext, dst),\n    } as TRet<CipherWithOutput>;\n  }\n);\n\nfunction validateBlockDecrypt(data: TArg<Uint8Array>) {\n  abytes(data);\n  // ECB/CBC decryption always consumes whole ciphertext blocks; PKCS#7/CMS\n  // padding, when enabled, is removed only after decrypting the final block.\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\n// ECB/CBC core modes operate on whole blocks; `pkcs5` enables the library's\n// PKCS#7/CMS-compatible final-block padding convenience before encryption.\nfunction validateBlockEncrypt(plaintext: TArg<Uint8Array>, pkcs5: boolean, dst?: TArg<Uint8Array>) {\n  abytes(plaintext);\n  let outLen = plaintext.length;\n  const remaining = outLen % BLOCK_SIZE;\n  if (!pkcs5 && remaining !== 0)\n    throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');\n  if (pkcs5) {\n    let left = BLOCK_SIZE - remaining;\n    // RFC 5652 pads even already-aligned inputs, so a full extra block is\n    // appended when the plaintext length is already a multiple of 16 bytes.\n    if (!left) left = BLOCK_SIZE; // if no bytes left, create empty padding block\n    outLen = outLen + left;\n  }\n  dst = getOutput(outLen, dst);\n  complexOverlapBytes(plaintext, dst);\n  // Copy on BE or misaligned inputs so u32()/swap32IfBE() normalization never\n  // mutates caller plaintext bytes in place before ECB/CBC processing.\n  if (!isLE || !isAligned32(plaintext)) plaintext = copyBytes(plaintext);\n  const b = u32(plaintext);\n  swap32IfBE(b);\n  const o = u32(dst);\n  return { b, o, out: dst };\n}\n\n// `pkcs5` is the historical option name; for AES's 16-byte block this is the\n// generic PKCS#7/CMS-style block-padding rule on decrypt.\nfunction validatePKCS(data: TArg<Uint8Array>, pkcs5: boolean): TRet<Uint8Array> {\n  if (!pkcs5) return data as TRet<Uint8Array>;\n\n  const len = data.length;\n  // RFC 5652 pads even empty / already-aligned inputs, so a valid padded\n  // ECB/CBC ciphertext is never empty when PKCS#7/CMS unpadding is enabled.\n  // AES-CBC/ECB ciphertext should be full blocks before unpadding\n  if (len === 0) throw new Error('aes/pkcs7: empty ciphertext not allowed');\n  const lastByte = data[len - 1];\n  let valid = 1;\n  valid &= ((lastByte - 1) >>> 31) ^ 1; // pad >= 1\n  valid &= ((16 - lastByte) >>> 31) ^ 1; // pad <= 16\n  // Check exactly 16 tail bytes in constant-shape loop\n  // For i < pad: byte must equal pad\n  // For i >= pad: ignore byte\n  for (let i = 0; i < 16; i++) {\n    // const b = data[len - 1 - i];\n    const shouldCheck = (i - lastByte) >>> 31; // 1 if i < pad else 0\n    const eq = (data[len - 1 - i] ^ lastByte) === 0 ? 1 : 0; // 1 if equal\n    valid &= eq | (shouldCheck ^ 1); // pass if equal OR not checked\n  }\n\n  // if (invalidLen) throw new Error('aes/pkcs7: ciphertext length must be multiple of 16');\n  if (!valid) throw new Error('aes/pkcs7: wrong padding');\n  return data.subarray(0, len - lastByte) as TRet<Uint8Array>;\n}\n\n// ECB/CBC callers only pass the final short block here, so `left.length` is\n// 0..15 and the helper always emits exactly one padded 16-byte block.\nfunction padPCKS(left: TArg<Uint8Array>): TRet<Uint32Array> {\n  const tmp = new Uint8Array(16);\n  const tmp32 = u32(tmp);\n  tmp.set(left);\n  const paddingByte = BLOCK_SIZE - left.length;\n  // RFC 5652 \u00A76.3 fills the whole suffix with the padding length byte:\n  // e.g. `aa 0f..0f` for a 1-byte tail, or `10..10` for a full extra block.\n  for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++) tmp[i] = paddingByte;\n  return tmp32;\n}\n\n/** Options for ECB and CBC. */\nexport type BlockOpts = {\n  /** Disable the library's PKCS#7 padding/unpadding layer and require exact-block inputs. */\n  disablePadding?: boolean;\n};\n\n/**\n * **ECB** (Electronic Codebook): Deterministic encryption; identical plaintext blocks yield\n * identical ciphertexts. Not secure due to pattern leakage.\n * See {@link https://words.filippo.io/the-ecb-penguin/ | the AES Penguin}.\n * @param key - AES key bytes.\n * @param opts - Padding options. See {@link BlockOpts}.\n * @returns Cipher instance with `encrypt()` and `decrypt()`.\n * @example\n * Shows the basic ECB encrypt call shape with a fresh key; avoid ECB in new designs.\n *\n * ```ts\n * import { ecb } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const cipher = ecb(key);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const ecb: TRet<\n  ((key: TArg<Uint8Array>, opts?: BlockOpts) => CipherWithOutput) & {\n    blockSize: number;\n  }\n> = /* @__PURE__ */ wrapCipher(\n  { blockSize: 16 },\n  function aesecb(key: TArg<Uint8Array>, opts: BlockOpts = {}): TRet<CipherWithOutput> {\n    const pkcs5 = !opts.disablePadding;\n    return {\n      encrypt(plaintext: TArg<Uint8Array>, dst?: TArg<Uint8Array>): TRet<Uint8Array> {\n        const { b, o, out: _out } = validateBlockEncrypt(plaintext, pkcs5, 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 (pkcs5) {\n          const tmp32 = padPCKS(plaintext.subarray(i * 4));\n          swap32IfBE(tmp32);\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        swap32IfBE(o);\n        clean(xk);\n        return _out as TRet<Uint8Array>;\n      },\n      decrypt(ciphertext: TArg<Uint8Array>, dst?: TArg<Uint8Array>): TRet<Uint8Array> {\n        validateBlockDecrypt(ciphertext);\n        const xk = expandKeyDecLE(key);\n        dst = getOutput(ciphertext.length, dst);\n        const toClean: (Uint8Array | Uint32Array)[] = [xk];\n        complexOverlapBytes(ciphertext, dst);\n        // Copy on BE or misaligned ciphertext so u32()/swap32IfBE()\n        // normalization never mutates caller bytes in place before decrypt().\n        if (!isLE || !isAligned32(ciphertext)) toClean.push((ciphertext = copyBytes(ciphertext)));\n        const b = u32(ciphertext);\n        const o = u32(dst);\n        swap32IfBE(b);\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        swap32IfBE(o);\n        clean(...toClean);\n        return validatePKCS(dst, pkcs5) as TRet<Uint8Array>;\n      },\n    } as TRet<CipherWithOutput>;\n  }\n);\n\n/**\n * **CBC** (Cipher Block Chaining): Each plaintext block is XORed with the\n * previous block of ciphertext before encryption.\n * Hard to use: requires proper padding and an unpredictable IV. Unauthenticated: needs MAC.\n * @param key - AES key bytes.\n * @param iv - 16-byte unpredictable initialization vector.\n * @param opts - Padding options. See {@link BlockOpts}.\n * @returns Cipher instance with `encrypt()` and `decrypt()`.\n * @example\n * Encrypts a padded message with a fresh key and 16-byte IV.\n *\n * ```ts\n * import { cbc } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const iv = randomBytes(16);\n * const cipher = cbc(key, iv);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const cbc: TRet<\n  ((key: TArg<Uint8Array>, iv: TArg<Uint8Array>, opts?: BlockOpts) => CipherWithOutput) & {\n    blockSize: number;\n    nonceLength: number;\n  }\n> = /* @__PURE__ */ wrapCipher(\n  { blockSize: 16, nonceLength: 16 },\n  function aescbc(\n    key: TArg<Uint8Array>,\n    iv: TArg<Uint8Array>,\n    opts: BlockOpts = {}\n  ): TRet<CipherWithOutput> {\n    const pkcs5 = !opts.disablePadding;\n    return {\n      encrypt(plaintext: TArg<Uint8Array>, dst?: TArg<Uint8Array>): TRet<Uint8Array> {\n        const xk = expandKeyLE(key);\n        const { b, o, out: _out } = validateBlockEncrypt(plaintext, pkcs5, dst);\n        let _iv = iv;\n        const toClean: (Uint8Array | Uint32Array)[] = [xk];\n        // Copy on BE or misaligned inputs so IV normalization and the mutable\n        // local chaining state never write back into caller IV bytes.\n        if (!isLE || !isAligned32(_iv)) toClean.push((_iv = copyBytes(_iv)));\n        const n32 = u32(_iv);\n        swap32IfBE(n32);\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 (pkcs5) {\n          const tmp32 = padPCKS(plaintext.subarray(i * 4));\n          swap32IfBE(tmp32);\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        swap32IfBE(o);\n        clean(...toClean);\n        return _out as TRet<Uint8Array>;\n      },\n      decrypt(ciphertext: TArg<Uint8Array>, dst?: TArg<Uint8Array>): TRet<Uint8Array> {\n        validateBlockDecrypt(ciphertext);\n        const xk = expandKeyDecLE(key);\n        let _iv = iv;\n        const toClean: (Uint8Array | Uint32Array)[] = [xk];\n        // Copy on BE or misaligned inputs so IV normalization and the mutable\n        // local chaining state never write back into caller IV bytes.\n        if (!isLE || !isAligned32(_iv)) toClean.push((_iv = copyBytes(_iv)));\n        const n32 = u32(_iv);\n        swap32IfBE(n32);\n        dst = getOutput(ciphertext.length, dst);\n        complexOverlapBytes(ciphertext, dst);\n        // Copy on BE or misaligned ciphertext so u32()/swap32IfBE()\n        // normalization never mutates caller bytes in place before decrypt().\n        if (!isLE || !isAligned32(ciphertext)) toClean.push((ciphertext = copyBytes(ciphertext)));\n        const b = u32(ciphertext);\n        const o = u32(dst);\n        swap32IfBE(b);\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        swap32IfBE(o);\n        clean(...toClean);\n        return validatePKCS(dst, pkcs5) as TRet<Uint8Array>;\n      },\n    } as TRet<CipherWithOutput>;\n  }\n);\n\n/**\n * CFB (CFB-128): Cipher Feedback Mode with 128-bit segments. The input for the\n * block cipher is the previous cipher output.\n * Unauthenticated: needs MAC.\n * @param key - AES key bytes.\n * @param iv - 16-byte unpredictable initialization vector.\n * @returns Cipher instance with `encrypt()` and `decrypt()`.\n * @example\n * Encrypts a short message with feedback mode and a fresh key/IV pair.\n *\n * ```ts\n * import { cfb } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const iv = randomBytes(16);\n * const cipher = cfb(key, iv);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const cfb: TRet<\n  ((key: TArg<Uint8Array>, iv: TArg<Uint8Array>) => CipherWithOutput) & {\n    blockSize: number;\n    nonceLength: number;\n  }\n> = /* @__PURE__ */ wrapCipher(\n  { blockSize: 16, nonceLength: 16 },\n  function aescfb(key: TArg<Uint8Array>, iv: TArg<Uint8Array>): TRet<CipherWithOutput> {\n    function processCfb(\n      src: TArg<Uint8Array>,\n      isEncrypt: boolean,\n      dst?: TArg<Uint8Array>\n    ): TRet<Uint8Array> {\n      abytes(src);\n      const srcLen = src.length;\n      dst = getOutput(srcLen, dst);\n      // CFB feeds back previous ciphertext, so overlapping src/dst could\n      // overwrite bytes that are still needed as the next feedback block.\n      if (overlapBytes(src, dst)) throw new Error('overlapping src and dst not supported.');\n      const xk = expandKeyLE(key);\n      let _iv = iv;\n      const toClean: (Uint8Array | Uint32Array)[] = [xk];\n      // Copy on BE or misaligned inputs so u32()/swap32IfBE() normalization\n      // never mutates caller IV/src bytes in place before CFB processing.\n      if (!isLE || !isAligned32(_iv)) toClean.push((_iv = copyBytes(_iv)));\n      if (!isLE || !isAligned32(src)) toClean.push((src = copyBytes(src)));\n      const src32 = u32(src);\n      const dst32 = u32(dst);\n      // NIST SP 800-38A \u00A76.3 feeds back the previous ciphertext segment in\n      // both directions: encrypt reuses freshly written dst words, decrypt\n      // reuses the source ciphertext words.\n      const next32 = isEncrypt ? dst32 : src32;\n      const n32 = u32(_iv);\n      swap32IfBE(src32);\n      swap32IfBE(n32);\n      // prettier-ignore\n      let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n      for (let i = 0; i + 4 <= src32.length; ) {\n        const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3);\n        dst32[i + 0] = src32[i + 0] ^ e0;\n        dst32[i + 1] = src32[i + 1] ^ e1;\n        dst32[i + 2] = src32[i + 2] ^ e2;\n        dst32[i + 3] = src32[i + 3] ^ e3;\n        ((s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]));\n      }\n      // leftovers (less than block)\n      const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n      if (start < srcLen) {\n        // Byte-oriented API: for a final short tail, reuse the next CFB-128\n        // output block and XOR only the needed prefix. RFC 3826 \u00A73.1.3 /\n        // \u00A73.1.4 describes the same no-padding rule at bit granularity for a\n        // final r<=128 segment.\n        ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n        const tmp = new Uint32Array([s0, s1, s2, s3]);\n        swap32IfBE(tmp);\n        const buf = u8(tmp);\n        for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];\n        clean(buf);\n      }\n      swap32IfBE(dst32);\n      clean(...toClean);\n      return dst as TRet<Uint8Array>;\n    }\n    return {\n      encrypt: (plaintext: TArg<Uint8Array>, dst?: TArg<Uint8Array>) =>\n        processCfb(plaintext, true, dst),\n      decrypt: (ciphertext: TArg<Uint8Array>, dst?: TArg<Uint8Array>) =>\n        processCfb(ciphertext, false, dst),\n    } as TRet<CipherWithOutput>;\n  }\n);\n\n// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen\n// `data` is the payload covered by the polynomial MAC: ciphertext for GCM,\n// plaintext for GCM-SIV. Keep AAD/data/length as separate updates because\n// GHASH/POLYVAL pad each call to block boundaries, so the chunks must match the\n// spec-defined segments instead of arbitrary concatenation boundaries.\nfunction computeTag(\n  fn: typeof ghash,\n  isLE: boolean,\n  key: TArg<Uint8Array>,\n  data: TArg<Uint8Array>,\n  AAD?: TArg<Uint8Array>\n): TRet<Uint8Array> {\n  const aadLength = AAD ? AAD.length : 0;\n  const h = fn.create(key, data.length + aadLength);\n  if (AAD) h.update(AAD);\n  // u64Lengths() takes (dataBits, aadBits) but still serializes the final\n  // block as len(AAD) || len(data), matching both GCM and GCM-SIV.\n  const num = u64Lengths(8 * data.length, 8 * aadLength, isLE);\n  h.update(data);\n  h.update(num);\n  const res = h.digest();\n  clean(num);\n  return res;\n}\n\n/**\n * **GCM** (Galois/Counter Mode): Combines CTR mode with polynomial MAC. Efficient and widely used.\n * Not perfect:\n * a) conservative key wear-out is `2**32` (4B) msgs.\n * b) key wear-out under random nonces is even smaller: `2**23` (8M) messages for `2**-50` chance.\n * c) MAC can be forged: see Poly1305 documentation.\n * @param key - AES key bytes.\n * @param nonce - Nonce bytes (12 recommended, minimum 8; other lengths use GHASH J0 derivation).\n * @param AAD - Additional authenticated data.\n * @returns AEAD cipher instance with a fixed 16-byte tag.\n * @example\n * Encrypts and authenticates plaintext with a fresh key and 12-byte nonce.\n *\n * ```ts\n * import { gcm } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const nonce = randomBytes(12);\n * const cipher = gcm(key, nonce);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const gcm: TRet<\n  ((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => Cipher) & {\n    blockSize: number;\n    nonceLength: number;\n    tagLength: number;\n    varSizeNonce: true;\n  }\n> = /* @__PURE__ */ wrapCipher(\n  { blockSize: 16, nonceLength: 12, tagLength: 16, varSizeNonce: true },\n  function aesgcm(\n    key: TArg<Uint8Array>,\n    nonce: TArg<Uint8Array>,\n    AAD?: TArg<Uint8Array>\n  ): TRet<Cipher> {\n    // SP 800-38D lets implementations narrow supported IV lengths.\n    // This wrapper intentionally requires at least 8 bytes; OpenSSL accepts shorter IVs too.\n    // 12-byte nonces take the fast path; other allowed lengths use GHASH to derive J0.\n    if (nonce.length < 8) throw new Error('aes/gcm: invalid nonce length');\n    const tagLength = 16;\n    function _computeTag(\n      authKey: TArg<Uint8Array>,\n      tagMask: TArg<Uint8Array>,\n      data: TArg<Uint8Array>\n    ): TRet<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      // NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces\n      if (nonce.length === 12) {\n        counter.set(nonce);\n      } else {\n        const nonceLen = EMPTY_BLOCK.slice();\n        const view = createView(nonceLen);\n        view.setBigUint64(8, BigInt(nonce.length * 8), false);\n        // GHASH.update() pads each call to 16 bytes, so\n        // update(nonce).update(nonceLen) realizes\n        // IV || 0^s || 0^64 || [len(IV)]_64 for non-96-bit nonces.\n        // ghash(nonce || u64be(0) || u64be(nonceLen*8))\n        const g = ghash.create(authKey).update(nonce).update(nonceLen);\n        g.digestInto(counter); // digestInto doesn't trigger '.destroy'\n        g.destroy();\n      }\n      // GCTR_K(J0, 0^128) = E_K(J0); reusing ctr32() here extracts that tag\n      // mask and leaves `counter` advanced to inc32(J0) for payload GCTR.\n      const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);\n      return { xk, authKey, counter, tagMask };\n    }\n    return {\n      encrypt(plaintext: TArg<Uint8Array>): TRet<Uint8Array> {\n        const { xk, authKey, counter, tagMask } = deriveKeys();\n        const out = new Uint8Array(plaintext.length + tagLength);\n        const toClean: (Uint8Array | Uint32Array)[] = [xk, authKey, counter, tagMask];\n        if (!isAligned32(plaintext)) toClean.push((plaintext = copyBytes(plaintext)));\n        ctr32(xk, false, counter, plaintext, out.subarray(0, plaintext.length));\n        const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));\n        toClean.push(tag);\n        out.set(tag, plaintext.length);\n        clean(...toClean);\n        return out as TRet<Uint8Array>;\n      },\n      decrypt(ciphertext: TArg<Uint8Array>): TRet<Uint8Array> {\n        const { xk, authKey, counter, tagMask } = deriveKeys();\n        const toClean: (Uint8Array | Uint32Array)[] = [xk, authKey, tagMask, counter];\n        if (!isAligned32(ciphertext)) toClean.push((ciphertext = copyBytes(ciphertext)));\n        const data = ciphertext.subarray(0, -tagLength);\n        const passedTag = ciphertext.subarray(-tagLength);\n        const tag = _computeTag(authKey, tagMask, data);\n        toClean.push(tag);\n        // NIST SP 800-38D \u00A77.2 permits equivalent step orderings; verify the\n        // tag before CTR so unauthenticated plaintext is never materialized.\n        if (!equalBytes(tag, passedTag)) {\n          clean(...toClean);\n          throw new Error('aes/gcm: invalid ghash tag');\n        }\n        const out = ctr32(xk, false, counter, data);\n        clean(...toClean);\n        return out as TRet<Uint8Array>;\n      },\n    } as TRet<Cipher>;\n  }\n);\n\nconst limit = (name: string, min: number, max: number) => (value: number) => {\n  // Current AES-SIV/GCM-SIV callers pass protocol limits from RFC 8452 / RFC 5297,\n  // not arbitrary library-preference bounds.\n  // Callers feed Uint8Array.length values here, so safe-integer rejection\n  // does not exclude any representable input even when an RFC bound is larger.\n  if (!Number.isSafeInteger(value) || min > value || value > max) {\n    const minmax = '[' + min + '..' + max + ']';\n    throw new Error('' + name + ': expected value in range ' + minmax + ', got ' + value);\n  }\n};\n\n/**\n * **SIV** (Synthetic IV): GCM with nonce-misuse resistance.\n * Repeating nonces reveal only the fact plaintexts are identical.\n * Also suffers from GCM issues: key wear-out limits & MAC forging.\n * See {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}.\n * RFC 8452 defines 16-byte and 32-byte AES keys for this mode.\n * This implementation also accepts 24-byte AES-192 keys as a local\n * extension; see the inline comment next to `validateKeyLength(key)` below\n * for the exact scope note.\n * @param key - AES key bytes.\n * @param nonce - 12-byte nonce.\n * @param AAD - Additional authenticated data.\n * @returns AEAD cipher instance.\n * @example\n * Encrypts and authenticates plaintext with a fresh key and nonce, while tolerating reuse.\n *\n * ```ts\n * import { gcmsiv } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const nonce = randomBytes(12);\n * const cipher = gcmsiv(key, nonce);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const gcmsiv: TRet<\n  ((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => Cipher) & {\n    blockSize: number;\n    nonceLength: number;\n    tagLength: number;\n    varSizeNonce: true;\n  }\n> = /* @__PURE__ */ wrapCipher(\n  { blockSize: 16, nonceLength: 12, tagLength: 16, varSizeNonce: true },\n  function aessiv(\n    key: TArg<Uint8Array>,\n    nonce: TArg<Uint8Array>,\n    AAD?: TArg<Uint8Array>\n  ): TRet<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(key);\n    // RFC 8452 only standardizes 16-byte and 32-byte key-generating keys.\n    // The accepted 24-byte path is a local AES-192 extension outside the RFC-defined AEADs.\n    validateKeyLength(key);\n    NONCE_LIMIT(nonce.length);\n    if (AAD !== undefined) AAD_LIMIT(AAD.length);\n    function deriveKeys() {\n      const xk = expandKeyLE(key);\n      const encKey = new Uint8Array(key.length);\n      const authKey = new Uint8Array(16);\n      const toClean: (Uint8Array | Uint32Array)[] = [xk, encKey];\n      let _nonce = nonce;\n      // Copy on BE or misaligned nonce so u32()/swap32IfBE() normalization\n      // never mutates caller nonce bytes before RFC 8452 key derivation.\n      if (!isLE || !isAligned32(_nonce)) toClean.push((_nonce = copyBytes(_nonce)));\n      const n32 = u32(_nonce);\n      swap32IfBE(n32);\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        swap32IfBE(d32);\n      }\n      const res = { authKey, encKey: expandKeyLE(encKey) };\n      // Cleanup\n      clean(...toClean);\n      return res;\n    }\n    function _computeTag(\n      encKey: TArg<Uint32Array>,\n      authKey: TArg<Uint8Array>,\n      data: TArg<Uint8Array>\n    ): TRet<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      swap32IfBE(t32);\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      swap32IfBE(t32);\n      return tag;\n    }\n    // actual decrypt/encrypt of message.\n    function processSiv(\n      encKey: TArg<Uint32Array>,\n      tag: TArg<Uint8Array>,\n      input: TArg<Uint8Array>\n    ): TRet<Uint8Array> {\n      let block = copyBytes(tag);\n      // RFC 8452 \u00A74 / \u00A75 use the tag with the highest bit of the last byte\n      // forced to one as the initial AES-CTR counter block.\n      block[15] |= 0x80; // Force highest bit\n      const res = ctr32(encKey, true, block, input);\n      // Cleanup\n      clean(block);\n      return res;\n    }\n    return {\n      encrypt(plaintext: TArg<Uint8Array>): TRet<Uint8Array> {\n        PLAIN_LIMIT(plaintext.length);\n        const { encKey, authKey } = deriveKeys();\n        const tag = _computeTag(encKey, authKey, plaintext);\n        const toClean: (Uint8Array | Uint32Array)[] = [encKey, authKey, tag];\n        if (!isAligned32(plaintext)) toClean.push((plaintext = copyBytes(plaintext)));\n        const out = new Uint8Array(plaintext.length + tagLength);\n        out.set(tag, plaintext.length);\n        out.set(processSiv(encKey, tag, plaintext));\n        // Cleanup\n        clean(...toClean);\n        return out as TRet<Uint8Array>;\n      },\n      decrypt(ciphertext: TArg<Uint8Array>): TRet<Uint8Array> {\n        CIPHER_LIMIT(ciphertext.length);\n        const tag = ciphertext.subarray(-tagLength);\n        const { encKey, authKey } = deriveKeys();\n        const toClean: (Uint8Array | Uint32Array)[] = [encKey, authKey];\n        if (!isAligned32(ciphertext)) toClean.push((ciphertext = copyBytes(ciphertext)));\n        const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));\n        const expectedTag = _computeTag(encKey, authKey, plaintext);\n        toClean.push(expectedTag);\n        // RFC 8452 \u00A75: plaintext is unauthenticated here and MUST NOT be\n        // returned until the expected-tag check completes successfully.\n        if (!equalBytes(tag, expectedTag)) {\n          clean(...toClean);\n          throw new Error('invalid polyval tag');\n        }\n        // Cleanup\n        clean(...toClean);\n        return plaintext as TRet<Uint8Array>;\n      },\n    } as TRet<Cipher>;\n  }\n);\n\nfunction isBytes32(a: unknown): a is Uint32Array {\n  // Plain `instanceof Uint32Array` is too strict for cross-realm expanded-key views.\n  // This is only a best-effort unsafe-export guard, not a provenance proof for `expandKeyLE`.\n  return (\n    a instanceof Uint32Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint32Array')\n  );\n}\n\n// Unsafe single-block helpers: mutate `block` in place and require its 16-byte\n// Uint8Array view to be 4-byte aligned because `u32(block)` reinterprets it.\nfunction encryptBlock(xk: TArg<Uint32Array>, block: TArg<Uint8Array>): TRet<Uint8Array> {\n  abytes(block, 16, 'block');\n  if (!isBytes32(xk)) throw new Error('_encryptBlock accepts result of expandKeyLE');\n  const b32 = u32(block);\n  swap32IfBE(b32);\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  swap32IfBE(b32);\n  return block as TRet<Uint8Array>;\n}\n\nfunction decryptBlock(xk: TArg<Uint32Array>, block: TArg<Uint8Array>): TRet<Uint8Array> {\n  abytes(block, 16, 'block');\n  if (!isBytes32(xk)) throw new Error('_decryptBlock accepts result of expandKeyLE');\n  const b32 = u32(block);\n  swap32IfBE(b32);\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  swap32IfBE(b32);\n  return block as TRet<Uint8Array>;\n}\n\n/**\n * AES-W (base for AESKW/AESKWP).\n * Specs:\n * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf | SP800-38F},\n * {@link https://www.rfc-editor.org/rfc/rfc3394 | RFC 3394},\n * {@link https://www.rfc-editor.org/rfc/rfc5649 | RFC 5649}.\n * Shared core mutates `out` in place; callers are responsible for prepending\n * the right IV/AIV and checking the recovered value after decrypt.\n */\nconst AESW = {\n  /*\n  High-level pseudocode:\n  ```\n  A: u64 = IV\n  out = []\n  for (let i=0, ctr = 0; i<6; i++) {\n    for (const chunk of chunks(plaintext, 8)) {\n      A ^= swapEndianess(ctr++)\n      [A, res] = chunks(encrypt(A || chunk), 8);\n      out ||= res\n    }\n  }\n  out = A || out\n  ```\n  Decrypt is the same, but reversed.\n  */\n  encrypt(kek: TArg<Uint8Array>, out: TArg<Uint8Array>) {\n    // Current implementation keeps RFC 3394/5649 `t` in a u32-shaped counter,\n    // so the shared core caps plaintext below 4 GiB even though the specs allow more.\n    if (out.length >= 2 ** 32) throw new Error('plaintext should be less than 4gb');\n    const xk = expandKeyLE(kek);\n    // 16-byte `S = A || P[1]` is the RFC 5649 KWP special case for n=1;\n    // KW callers never reach it because KW requires at least two plaintext semiblocks.\n    if (out.length === 16) encryptBlock(xk, out);\n    else {\n      const o32 = u32(out);\n      swap32IfBE(o32);\n      // prettier-ignore\n      let a0 = o32[0], a1 = o32[1]; // A\n      for (let j = 0, ctr = 1; j < 6; j++) {\n        for (let pos = 2; pos < o32.length; pos += 2, ctr++) {\n          const { s0, s1, s2, s3 } = encrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n          // A = MSB(64, B) ^ t where t = (n*j)+i. Under the 32-bit length cap\n          // above, `t` fits in the low half of `[t]_64`, so xor only the low\n          // 32 bits of A after converting `ctr` to network order.\n          ((a0 = s0), (a1 = s1 ^ byteSwap(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3));\n        }\n      }\n      ((o32[0] = a0), (o32[1] = a1)); // out = A || out\n      swap32IfBE(o32);\n    }\n    xk.fill(0);\n  },\n  decrypt(kek: TArg<Uint8Array>, out: TArg<Uint8Array>) {\n    // Same implementation cap on the recovered plaintext length after\n    // removing the 8-byte A/IV prefix.\n    if (out.length - 8 >= 2 ** 32) throw new Error('ciphertext should be less than 4gb');\n    const xk = expandKeyDecLE(kek);\n    const chunks = out.length / 8 - 1; // first chunk is IV\n    // `n = 2` semiblocks is the RFC 5649 KWP special case; KW ciphertexts\n    // always have at least three semiblocks and therefore use the W^-1 loop.\n    if (chunks === 1) decryptBlock(xk, out);\n    else {\n      const o32 = u32(out);\n      swap32IfBE(o32);\n      // prettier-ignore\n      let a0 = o32[0], a1 = o32[1]; // A\n      for (let j = 0, ctr = chunks * 6; j < 6; j++) {\n        for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) {\n          a1 ^= byteSwap(ctr);\n          const { s0, s1, s2, s3 } = decrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n          ((a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3));\n        }\n      }\n      ((o32[0] = a0), (o32[1] = a1));\n      swap32IfBE(o32);\n    }\n    xk.fill(0);\n  },\n};\n\n// RFC 3394 \u00A72.2.3.1 / NIST SP 800-38F Algorithm 3 / Algorithm 4: KW prepends\n// the default 64-bit ICV1 and unwrap must verify the same value.\nconst AESKW_IV = /* @__PURE__ */ new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6\n\n/**\n * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.\n * Reduces block size from 16 to 8 bytes.\n * Plaintext must be a non-empty multiple of 8 bytes with minimum 16 bytes.\n * 8-byte inputs use aeskwp.\n * Wrapped ciphertext must be a multiple of 8 bytes with minimum 24 bytes.\n * For padded version, use aeskwp.\n * See {@link https://www.rfc-editor.org/rfc/rfc3394/ | RFC 3394} and\n * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf | NIST SP 800-38F}.\n * @param kek - AES key-encryption key.\n * @returns Key-wrap cipher instance.\n * As with other `wrapCipher(...)` wrappers, `encrypt()` is single-use per\n * instance.\n * @example\n * Wraps a 128-bit content-encryption key with a fresh key-encryption key.\n *\n * ```ts\n * import { aeskw } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const kek = randomBytes(16);\n * const cek = randomBytes(16);\n * const wrap = aeskw(kek);\n * wrap.encrypt(cek);\n * ```\n */\nexport const aeskw: TRet<\n  ((kek: TArg<Uint8Array>) => Cipher) & {\n    blockSize: number;\n  }\n> = /* @__PURE__ */ wrapCipher(\n  { blockSize: 8 },\n  (kek: TArg<Uint8Array>): TRet<Cipher> =>\n    ({\n      encrypt(plaintext: TArg<Uint8Array>): TRet<Uint8Array> {\n        if (!plaintext.length || plaintext.length % 8 !== 0)\n          throw new Error('invalid plaintext length');\n        // RFC 3394 / NIST SP 800-38F define KW only for >=2 plaintext\n        // semiblocks; the 1-semiblock case belongs to RFC 5649 KWP.\n        if (plaintext.length === 8)\n          throw new Error('8-byte keys not allowed in AESKW, use AESKWP instead');\n        const out = concatBytes(AESKW_IV, plaintext);\n        AESW.encrypt(kek, out);\n        return out;\n      },\n      decrypt(ciphertext: TArg<Uint8Array>): TRet<Uint8Array> {\n        // ciphertext must be at least 24 bytes and a multiple of 8 bytes\n        // 24 because should have at least two block (1 iv + 2).\n        // Replace with 16 to enable '8-byte keys'\n        if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8)\n          throw new Error('invalid ciphertext length');\n        // AESW.decrypt() mutates its buffer in place, so keep caller ciphertext\n        // immutable across the unwrap, ICV1 check, and IV scrubbing below.\n        const out = copyBytes(ciphertext);\n        AESW.decrypt(kek, out);\n        if (!equalBytes(out.subarray(0, 8), AESKW_IV)) throw new Error('integrity check failed');\n        out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n        return out.subarray(8) as TRet<Uint8Array>;\n      },\n    }) as TRet<Cipher>\n);\n\n/*\nWe don't support 8-byte keys. The rabbit hole:\n\n- Wycheproof says: \"NIST SP 800-38F does not define the wrapping of 8 byte keys.\n  RFC 3394 Section 2  on the other hand specifies that 8 byte keys are wrapped\n  by directly encrypting one block with AES.\"\n    - {@link https://github.com/C2SP/wycheproof/blob/master/doc/key_wrap.md | Wycheproof key-wrap note}\n    - \"RFC 3394 specifies in Section 2, that the input for the key wrap\n      algorithm must be at least two blocks and otherwise the constant\n      field and key are simply encrypted with ECB as a single block\"\n- What RFC 3394 actually says (in Section 2):\n    - \"Before being wrapped, the key data is parsed into n blocks of 64 bits.\n      The only restriction the key wrap algorithm places on n is that n be\n      at least two\"\n    - \"For key data with length less than or equal to 64 bits, the constant\n      field used in this specification and the key data form a single\n      128-bit codebook input making this key wrap unnecessary.\"\n- Which means \"assert(n >= 2)\" and \"use something else for 8 byte keys\"\n- NIST SP800-38F actually prohibits 8-byte in \"5.3.1 Mandatory Limits\".\n  It states that plaintext for KW should be \"2 to 2^54 -1 semiblocks\".\n- So, where does \"directly encrypt single block with AES\" come from?\n    - Not RFC 3394. Pseudocode of key wrap in 2.2 explicitly uses\n      loop of 6 for any code path\n    - There is a weird W3C spec:\n      {@link https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/Overview.html#kw-aes128 | XML Encryption AES key-wrap section}\n    - This spec is outdated, as admitted by Wycheproof authors\n    - There is RFC 5649 for padded key wrap, which is padding construction on\n      top of AESKW. In '4.1.2' it says: \"If the padded plaintext contains exactly\n      eight octets, then prepend the AIV as defined in Section 3 above to P[1] and\n      encrypt the resulting 128-bit block using AES in ECB mode [Modes] with key\n      K (the KEK).  In this case, the output is two 64-bit blocks C[0] and C[1]:\"\n    - Browser subtle crypto is actually crashes on wrapping keys less than 16 bytes:\n      `Error: error:1C8000E6:Provider routines::invalid input length]\n       { opensslErrorStack: [ 'error:030000BD:digital envelope routines::update error' ]`\n\nIn the end, seems like a bug in Wycheproof.\nThe 8-byte check can be easily disabled inside of AES_W.\n*/\n\n// RFC 5649 \u00A73 / NIST SP 800-38F Algorithm 5 / Algorithm 6: KWP uses ICV2 as\n// the high 32 bits of the AIV; the low 32 bits carry the MLI in network order.\nconst AESKWP_IV = 0xa65959a6; // single u32le value\n\n/**\n * AES-KW, but with padding and allows random keys.\n * Uses the RFC 5649 alternative initial value; the second u32 stores the\n * 32-bit MLI in network order.\n * Wrapped ciphertext must be at least 16 bytes; malformed lengths are\n * rejected during AIV/padding checks.\n * See {@link https://www.rfc-editor.org/rfc/rfc5649 | RFC 5649}.\n * @param kek - AES key-encryption key.\n * @returns Padded key-wrap cipher instance.\n * @example\n * Wraps a short key blob using the padded variant and a fresh key-encryption key.\n *\n * ```ts\n * import { aeskwp } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const kek = randomBytes(16);\n * const wrap = aeskwp(kek);\n * wrap.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const aeskwp: TRet<\n  ((kek: TArg<Uint8Array>) => Cipher) & {\n    blockSize: number;\n  }\n> = /* @__PURE__ */ wrapCipher(\n  { blockSize: 8 },\n  (kek: TArg<Uint8Array>): TRet<Cipher> =>\n    ({\n      encrypt(plaintext: TArg<Uint8Array>): TRet<Uint8Array> {\n        if (!plaintext.length) throw new Error('invalid plaintext length');\n        const padded = Math.ceil(plaintext.length / 8) * 8;\n        const out = new Uint8Array(8 + padded);\n        out.set(plaintext, 8);\n        const out32 = u32(out);\n        out32[0] = swap8IfBE(AESKWP_IV);\n        // RFC 5649 \u00A73: the low 32 bits of the AIV carry the octet-length MLI in\n        // network order, even though this buffer is addressed through LE u32s.\n        out32[1] = swap8IfBE(byteSwap(plaintext.length));\n        AESW.encrypt(kek, out);\n        return out as TRet<Uint8Array>;\n      },\n      decrypt(ciphertext: TArg<Uint8Array>): TRet<Uint8Array> {\n        // 16 because should have at least one block\n        if (ciphertext.length < 16) throw new Error('invalid ciphertext length');\n        // AESW.decrypt() mutates its buffer in place, so keep caller ciphertext\n        // immutable across the unwrap, AIV checks, and IV scrubbing below.\n        const out = copyBytes(ciphertext);\n        const o32 = u32(out);\n        AESW.decrypt(kek, out);\n        const len = byteSwap(swap8IfBE(o32[1])) >>> 0;\n        const padded = Math.ceil(len / 8) * 8;\n        if (swap8IfBE(o32[0]) !== AESKWP_IV || out.length - 8 !== padded)\n          throw new Error('integrity check failed');\n        // RFC 5649 \u00A73 / NIST SP 800-38F Algorithm 6: recovered padding length\n        // must be in [0,7], and every recovered pad octet must be zero.\n        for (let i = len; i < padded; i++)\n          if (out[8 + i] !== 0) throw new Error('integrity check failed');\n        out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n        return out.subarray(8, 8 + len) as TRet<Uint8Array>;\n      },\n    }) as TRet<Cipher>\n);\n\nclass _AesCtrDRBG implements PRG {\n  readonly blockLen: number;\n  private key: TRet<Uint8Array>;\n  private nonce: TRet<Uint8Array>;\n  private state: TRet<Uint8Array>;\n  private reseedCnt: number;\n  constructor(keyLen: number, seed: TArg<Uint8Array>, personalization?: TArg<Uint8Array>) {\n    this.blockLen = ctr.blockSize;\n    const keyLenBytes = keyLen / 8;\n    const nonceLen = 16;\n    // Store the full seedlen state as key || V so CTR_DRBG_Update-style steps\n    // can rewrite the entire internal state in place.\n    this.state = new Uint8Array(keyLenBytes + nonceLen) as TRet<Uint8Array>;\n    this.key = this.state.subarray(0, keyLenBytes) as TRet<Uint8Array>;\n    this.nonce = this.state.subarray(keyLenBytes, keyLenBytes + nonceLen) as TRet<Uint8Array>;\n    this.reseedCnt = 1;\n    // Keep the stored counter one step ahead of SP 800-90A's formal V so\n    // ctr(key, nonce) uses the next counter block directly.\n    incBytes(this.nonce, false, 1);\n    this.addEntropy(seed, personalization);\n  }\n  private update(data?: TArg<Uint8Array>) {\n    // cannot re-use state here, because we will wipe current key\n    ctr(this.key, this.nonce).encrypt(new Uint8Array(this.state.length), this.state);\n    if (data) {\n      abytes(data);\n      // CTR_DRBG without a derivation function pads shorter additional_input\n      // with zeros to seedlen, so XOR only the provided prefix here.\n      for (let i = 0; i < data.length; i++) this.state[i] ^= data[i];\n    }\n    // Keep storing V+1 so the next ctr(key, nonce) call starts from the\n    // spec's post-update counter state.\n    incBytes(this.nonce, false, 1);\n  }\n  // Optional `info` is additional input XORed into the reseed block and is\n  // limited to the internal state width.\n  addEntropy(seed: TArg<Uint8Array>, info?: TArg<Uint8Array>): void {\n    abytes(seed, this.state.length, 'seed');\n    // Copy caller entropy before XORing in personalization/additional input,\n    // then wipe the mixed seed material after CTR_DRBG_Update consumes it.\n    const _seed = seed.slice();\n    if (info) {\n      abytes(info);\n      if (info.length > _seed.length) throw new Error('info length is too big');\n      for (let i = 0; i < info.length; i++) _seed[i] ^= info[i];\n    }\n    this.update(_seed);\n    _seed.fill(0);\n    this.reseedCnt = 1;\n  }\n  // Optional `info` is additional input for the pre/post-update steps; bytes\n  // SP 800-90A Rev. 1 CTR_DRBG without a derivation function limits\n  // additional_input to seedlen, which is exactly this internal state width.\n  randomBytes(len: number, info?: TArg<Uint8Array>): TRet<Uint8Array> {\n    anumber(len);\n    // SP 800-90A Table 3 caps AES CTR_DRBG requests at 2^16 bits = 65536 bytes.\n    if (len > 2 ** 16) throw new Error('requested output is too big');\n    // The spec allows generate while reseed_counter == reseed_interval and increments afterwards.\n    if (this.reseedCnt > 2 ** 48) throw new Error('entropy exhausted');\n    if (info) {\n      abytes(info);\n      if (info.length > this.state.length) throw new Error('info length is too big');\n      this.update(info);\n    }\n    const res = new Uint8Array(len);\n    ctr(this.key, this.nonce).encrypt(res, res);\n    incBytes(this.nonce, false, Math.ceil(len / this.blockLen));\n    this.update(info);\n    this.reseedCnt++;\n    return res as TRet<Uint8Array>;\n  }\n  // Zeroes the current state and resets the counter, but does not make the\n  // instance unusable: later calls continue from the zeroed state.\n  clean(): void {\n    // `key` and `nonce` alias this backing buffer, so one fill wipes the full\n    // secret state in place.\n    this.state.fill(0);\n    this.reseedCnt = 0;\n  }\n}\n\n/**\n * Factory for AES-CTR DRBG instances.\n * @param seed - Initial entropy input.\n * @param personalization - Optional personalization string mixed into the state.\n * @returns Seeded AES-CTR DRBG instance.\n */\nexport type AesCtrDrbg = (\n  seed: TArg<Uint8Array>,\n  personalization?: TArg<Uint8Array>\n) => TRet<_AesCtrDRBG>;\n\n// Internal helper for the exported 128-bit and 256-bit aliases; other key\n// lengths are not validated here.\nconst createAesDrbg: (keyLen: number) => TRet<AesCtrDrbg> = (keyLen) => {\n  return (seed, personalization = undefined) =>\n    new _AesCtrDRBG(keyLen, seed, personalization) as TRet<_AesCtrDRBG>;\n};\n\n/**\n * AES-CTR DRBG 128-bit - CSPRNG (cryptographically secure pseudorandom number generator).\n * It's best to limit usage to non-production, non-critical cases: for example, test-only.\n * @param seed - Initial 32-byte entropy input.\n * @param personalization - Optional personalization string.\n * @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes.\n * @example\n * Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it.\n *\n * ```ts\n * import { rngAesCtrDrbg128 } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(32);\n * const prg = rngAesCtrDrbg128(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const rngAesCtrDrbg128: TRet<AesCtrDrbg> = /* @__PURE__ */ createAesDrbg(128);\n/**\n * AES-CTR DRBG 256-bit - CSPRNG (cryptographically secure pseudorandom number generator).\n * It's best to limit usage to non-production, non-critical cases: for example, test-only.\n * @param seed - Initial 48-byte entropy input.\n * @param personalization - Optional personalization string.\n * @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes.\n * @example\n * Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it.\n *\n * ```ts\n * import { rngAesCtrDrbg256 } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(48);\n * const prg = rngAesCtrDrbg256(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const rngAesCtrDrbg256: TRet<AesCtrDrbg> = /* @__PURE__ */ createAesDrbg(256);\n\n//#region CMAC\n\n/**\n * Left-shift by one bit and conditionally XOR with 0x87:\n * ```\n * if MSB(L) is equal to 0\n * then    K1 := L << 1;\n * else    K1 := (L << 1) XOR const_Rb;\n * ```\n *\n * Specs:\n * {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.3 | RFC 4493 Section 2.3},\n * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.3 | RFC 5297 Section 2.3}\n *\n * @returns modified `block` (for chaining)\n */\nfunction dbl<T extends Uint8Array>(block: T): T {\n  let carry = 0;\n\n  // Left shift by 1 bit\n  for (let i = BLOCK_SIZE - 1; i >= 0; i--) {\n    const newCarry = (block[i] & 0x80) >>> 7;\n    block[i] = (block[i] << 1) | carry;\n    carry = newCarry;\n  }\n\n  // XOR with 0x87 if there was a carry from the most significant bit\n  if (carry) {\n    // RFC 4493 \u00A72.3 / RFC 5297 \u00A72.1: 0x87 is const_Rb for doubling in the\n    // CMAC/S2V finite field with primitive polynomial x^128 + x^7 + x^2 + x + 1.\n    block[BLOCK_SIZE - 1] ^= 0x87;\n  }\n\n  return block;\n}\n\n/**\n * `a XOR b`, running in-place on `a`.\n * @param a left operand and output\n * @param b right operand\n * @returns `a` (for chaining)\n */\nfunction xorBlock<T extends TArg<Uint8Array>>(a: T, b: TArg<Uint8Array>): T {\n  if (a.length !== b.length) throw new Error('xorBlock: blocks must have same length');\n  for (let i = 0; i < a.length; i++) {\n    a[i] = a[i] ^ b[i];\n  }\n  return a;\n}\n\n/**\n * xorend as defined in\n * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.1 | RFC 5297 Section 2.1}.\n *\n * ```\n * leftmost(A, len(A)-len(B)) || (rightmost(A, len(B)) xor B)\n * ```\n *\n * Mutates `a` in place so the left prefix stays untouched and only the\n * rightmost `len(B)` bytes are xored with `b`.\n */\nfunction xorend<T extends TArg<Uint8Array>>(a: T, b: TArg<Uint8Array>): T {\n  if (b.length > a.length) {\n    throw new Error('xorend: len(B) must be less than or equal to len(A)');\n  }\n  // keep leftmost part of `a` unchanged\n  // and xor only the rightmost part:\n  const offset = a.length - b.length;\n  for (let i = 0; i < b.length; i++) {\n    a[offset + i] = a[offset + i] ^ b[i];\n  }\n  return a;\n}\n\n/**\n * Internal CMAC class.\n */\nclass _CMAC implements IHash2 {\n  readonly blockLen: number = BLOCK_SIZE;\n  readonly outputLen: number = BLOCK_SIZE;\n  // CMAC can only decide between `K1` and `K2` once the true final block is known,\n  // so updates process older blocks eagerly but keep one pending block buffered.\n  private buffer: Uint8Array;\n  private pos: number;\n  private finished: boolean;\n  private destroyed: boolean;\n  private k1: Uint8Array;\n  private k2: Uint8Array;\n  private x: Uint8Array;\n  private xk: Uint32Array;\n\n  constructor(key: TArg<Uint8Array>) {\n    abytes(key);\n    validateKeyLength(key);\n    this.xk = expandKeyLE(key);\n    this.buffer = new Uint8Array(BLOCK_SIZE);\n    this.pos = 0;\n    this.finished = false;\n    this.destroyed = false;\n    this.x = new Uint8Array(BLOCK_SIZE);\n    // L = AES_encrypt(K, const_Zero)\n    const L = new Uint8Array(BLOCK_SIZE);\n    encryptBlock(this.xk, L);\n    // Generate subkeys K1 and K2 from the main key according to\n    // {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.3 | RFC 4493 Section 2.3}\n    // K1\n    this.k1 = dbl(L);\n    this.k2 = dbl(new Uint8Array(this.k1));\n  }\n\n  private process(data: TArg<Uint8Array>): void {\n    // RFC 4493 \u00A72.4 step 6 loop body: Y := X XOR M_i; X := AES-128(K, Y).\n    xorBlock(this.x, data);\n    encryptBlock(this.xk, this.x);\n  }\n\n  update(data: TArg<Uint8Array>): this {\n    if (this.destroyed) throw new Error('Hash instance has been destroyed');\n    if (this.finished) throw new Error('Hash#digest() has already been called');\n    abytes(data);\n    let pos = 0;\n    if (this.pos) {\n      const take = Math.min(BLOCK_SIZE - this.pos, data.length);\n      this.buffer.set(data.subarray(0, take), this.pos);\n      this.pos += take;\n      pos = take;\n      if (this.pos === BLOCK_SIZE && pos < data.length) {\n        this.process(this.buffer);\n        this.pos = 0;\n      }\n    }\n    // Keep one complete block buffered: an exact 16-byte tail may still be\n    // M_n, and digestInto() must decide there whether RFC 4493 uses K1 or K2.\n    while (pos + BLOCK_SIZE < data.length) {\n      this.process(data.subarray(pos, pos + BLOCK_SIZE));\n      pos += BLOCK_SIZE;\n    }\n    if (pos < data.length) {\n      this.buffer.set(data.subarray(pos), 0);\n      this.pos = data.length - pos;\n    }\n    return this;\n  }\n\n  // See {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.4 | RFC 4493 Section 2.4}.\n  digestInto(out: TArg<Uint8Array>): void {\n    if (this.destroyed) throw new Error('Hash instance has been destroyed');\n    if (this.finished) throw new Error('Hash#digest() has already been called');\n    // `digestInto(out)` is the no-allocation fast path, so AES block re-use below\n    // requires a 32-bit-aligned caller buffer instead of hidden temp copies.\n    aoutput(out, this, true);\n    this.finished = true;\n    // `digestInto()` accepts out.length >= outputLen, so only the first block stores the tag.\n    const view = out.subarray(0, this.outputLen);\n    let last = new Uint8Array(BLOCK_SIZE);\n    if (this.pos === BLOCK_SIZE) {\n      // M_last := M_n XOR K1;\n      last.set(this.buffer);\n      xorBlock(last, this.k1);\n    } else {\n      // M_last := padding(M_n) XOR K2;\n      //\n      // [...] padding(x) is the concatenation of x and a single '1',\n      // followed by the minimum number of '0's, so that the total length is\n      // equal to 128 bits.\n      last.set(this.buffer.subarray(0, this.pos));\n      last[this.pos] = 0x80; // single '1' bit\n      xorBlock(last, this.k2);\n    }\n    view.set(this.x); // X := AES_CBC(K, M_1..M_{n-1})\n    xorBlock(view, last); // Y := X XOR M_last\n    encryptBlock(this.xk, view); // T := AES-128(K, Y)\n    clean(last);\n  }\n\n  digest(): Uint8ArrayBuffer {\n    const { buffer, outputLen } = this;\n    this.digestInto(buffer);\n    // Copy out before destroy() wipes the internal digest buffer in place.\n    const res = buffer.slice(0, outputLen);\n    this.destroy();\n    return res;\n  }\n\n  destroy(): void {\n    const { buffer, destroyed, x, xk, k1, k2 } = this;\n    if (destroyed) return;\n    this.destroyed = true;\n    // Wipe the buffered tail, chaining value, expanded AES key, and both CMAC subkeys.\n    clean(buffer, x, xk, k1, k2);\n  }\n}\n\n/**\n * AES-CMAC (Cipher-based Message Authentication Code).\n * Specs: {@link https://www.rfc-editor.org/rfc/rfc4493.html | RFC 4493}.\n * @param msg - Message bytes to authenticate.\n * @param key - AES key bytes.\n * @returns 16-byte authentication tag. `cmac.create(...)` follows the same incremental MAC shape as\n * the other keyed helpers in this repo, including `blockLen`,\n * `outputLen`, `digestInto()` and `destroy()`.\n * @example\n * Authenticates a message with AES-CMAC and a fresh key.\n *\n * ```ts\n * import { cmac } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * cmac(new Uint8Array(), key);\n * ```\n */\n// The 16-byte probe key is only used to read static metadata; runtime CMAC\n// still accepts AES-128/192/256 keys.\nexport const cmac: TRet<CMac<_CMAC>> = /* @__PURE__ */ wrapMacConstructor(\n  16,\n  (key: TArg<Uint8Array>) => new _CMAC(key)\n);\n\n/**\n * S2V (Synthetic Initialization Vector) function as described in\n * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.4 | RFC 5297 Section 2.4}.\n *\n * ```\n * S2V(K, S1, ..., Sn) {\n *   if n = 0 then\n *     return V = AES-CMAC(K, <one>)\n *   fi\n *   D = AES-CMAC(K, <zero>)\n *   for i = 1 to n-1 do\n *     D = dbl(D) xor AES-CMAC(K, Si)\n *   done\n *   if len(Sn) >= 128 then\n *     T = Sn xorend D\n *   else\n *     T = dbl(D) xor pad(Sn)\n *   fi\n *   return V = AES-CMAC(K, T)\n * }\n * ```\n *\n * S2V takes a key and a vector of strings S1, S2, ..., Sn and returns a 128-bit string.\n * The S2V function is used to generate a synthetic IV for AES-SIV.\n *\n * @param key - AES key (128, 192, or 256 bits)\n * @param strings - Array of byte arrays to process\n * @returns 128-bit synthetic IV\n */\nfunction s2v(key: TArg<Uint8Array>, strings: TArg<Uint8Array[]>): TRet<Uint8Array> {\n  validateKeyLength(key);\n  const len = strings.length;\n  if (len > 127) {\n    // RFC 5297 \u00A77 only proves S2V secure for at most 127 components; SIV\n    // spends one of those on the plaintext, leaving at most 126 AAD inputs.\n    throw new Error('s2v: number of input strings must be less than or equal to 127');\n  }\n\n  if (len === 0) return cmac(ONE_BLOCK, key);\n\n  // D = AES-CMAC(K, <zero>)\n  let d = cmac(EMPTY_BLOCK, key);\n\n  // for i = 1 to n-1 do\n  //   D = dbl(D) xor AES-CMAC(K, Si)\n  for (let i = 0; i < len - 1; i++) {\n    dbl(d);\n    const cmacResult = cmac(strings[i], key);\n    xorBlock(d, cmacResult);\n    clean(cmacResult);\n  }\n\n  const s_n = strings[len - 1];\n  // Earlier components are validated through cmac(...); validate the final one explicitly because\n  // the Uint8Array.from()/set() paths below would otherwise coerce array-like inputs silently.\n  abytes(s_n);\n  let t: Uint8Array;\n\n  // if len(Sn) >= 128 then\n  if (s_n.byteLength >= BLOCK_SIZE) {\n    // T = Sn xorend D\n    t = xorend(Uint8Array.from(s_n), d);\n  } else {\n    // pad(Sn):\n    const paddedSn = new Uint8Array(BLOCK_SIZE);\n    paddedSn.set(s_n);\n    paddedSn[s_n.length] = 0x80; // padding: 0x80 followed by zeros\n\n    // T = dbl(D) xor pad(Sn)\n    t = xorBlock(dbl(d), paddedSn);\n    clean(paddedSn);\n  }\n\n  // V = AES-CMAC(K, T)\n  const result = cmac(t, key);\n  clean(d, t);\n  return result;\n}\n\n/**\n * Use `gcmsiv` or `aessiv`.\n * @returns Never; always throws with the migration hint.\n * @throws If called; `siv()` is a removed v1 alias. {@link Error}\n * @example\n * `siv()` was removed in v2; use `gcmsiv()` for nonce-based SIV instead.\n *\n * ```ts\n * import { gcmsiv } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const nonce = randomBytes(12);\n * const cipher = gcmsiv(key, nonce);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const siv: () => never = () => {\n  throw new Error('\"siv\" from v1 is now \"gcmsiv\"');\n};\n\n/**\n * **SIV**: Synthetic Initialization Vector (SIV) Authenticated Encryption\n * Nonce is derived from the plaintext and AAD using the S2V function.\n * Supports at most 126 AAD components. RFC 5297 nonce-based use is expressed by\n * passing the nonce as the final AAD component before the plaintext.\n * See {@link https://datatracker.ietf.org/doc/html/rfc5297.html | RFC 5297}.\n * @param key - 32-byte, 48-byte, or 64-byte key.\n * @param AAD - Additional authenticated data chunks (up to 126).\n * @returns AEAD cipher instance.\n * @example\n * Authenticates and encrypts plaintext with a fresh key without requiring unique nonces.\n *\n * ```ts\n * import { aessiv } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const cipher = aessiv(key);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const aessiv: TRet<\n  ((key: TArg<Uint8Array>, ...AAD: TArg<Uint8Array[]>) => Cipher) & {\n    blockSize: number;\n    tagLength: number;\n  }\n> = /* @__PURE__ */ wrapCipher(\n  { blockSize: 16, tagLength: 16 },\n  function aessiv(key: TArg<Uint8Array>, ...AAD: TArg<Uint8Array[]>): TRet<Cipher> {\n    // From RFC 5297: Section 6.1, 6.2, 6.3:\n    const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 132);\n    const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 132 + 16);\n    if (AAD.length > 126) {\n      // RFC 5297 \u00A72.6 / \u00A72.7 / \u00A77: SIV passes the plaintext as the last S2V\n      // component, so callers only get 126 associated-data components.\n      throw new Error('\"AAD\" number of elements must be less than or equal to 126');\n    }\n    AAD.forEach((aad) => abytes(aad));\n    abytes(key);\n    if (![32, 48, 64].includes(key.length))\n      throw new Error('\"aes key\" expected Uint8Array of length 32/48/64, got length=' + key.length);\n\n    // The key is split into equal halves, K1 = leftmost(K, len(K)/2) and\n    // K2 = rightmost(K, len(K)/2).  K1 is used for S2V and K2 is used for CTR.\n    // This borrows caller key/AAD buffers by reference; mutating them after\n    // construction changes future encrypt/decrypt results.\n    const k1 = key.subarray(0, key.length / 2);\n    const k2 = key.subarray(key.length / 2);\n\n    return {\n      // {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.6 | RFC 5297 Section 2.6}\n      encrypt(plaintext: TArg<Uint8Array>): TRet<Uint8Array> {\n        PLAIN_LIMIT(plaintext.length);\n\n        const v = s2v(k1, [...AAD, plaintext]);\n\n        // clear out the 31st and 63rd (rightmost) bit:\n        const q = Uint8Array.from(v);\n        q[8] &= 0x7f;\n        q[12] &= 0x7f;\n\n        // encrypt:\n        const c = ctr(k2, q).encrypt(plaintext);\n\n        return concatBytes(v, c);\n      },\n      // {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.7 | RFC 5297 Section 2.7}\n      decrypt(ciphertext: TArg<Uint8Array>): TRet<Uint8Array> {\n        CIPHER_LIMIT(ciphertext.length);\n        const v = ciphertext.subarray(0, BLOCK_SIZE);\n        const c = ciphertext.subarray(BLOCK_SIZE);\n\n        // clear out the 31st and 63rd (rightmost) bit:\n        const q = Uint8Array.from(v);\n        q[8] &= 0x7f;\n        q[12] &= 0x7f;\n\n        // decrypt:\n        const p = ctr(k2, q).decrypt(c);\n\n        // verify tag:\n        const t = s2v(k1, [...AAD, p]);\n\n        if (equalBytes(t, v)) {\n          return p as TRet<Uint8Array>;\n        } else {\n          throw new Error('invalid siv tag');\n        }\n      },\n    } as TRet<Cipher>;\n  }\n);\n//#endregion\n\n/**\n * Unsafe low-level internal methods. May change at any time.\n * Callers are expected to use reviewed expanded-key outputs, pass mutable and\n * aligned 16-byte blocks where required, and treat several helpers as in-place\n * mutations of their input buffers or counters.\n */\nexport const unsafe: {\n  expandKeyLE: typeof expandKeyLE;\n  expandKeyDecLE: typeof expandKeyDecLE;\n  encrypt: typeof encrypt;\n  decrypt: typeof decrypt;\n  encryptBlock: typeof encryptBlock;\n  decryptBlock: typeof decryptBlock;\n  ctrCounter: typeof ctrCounter;\n  ctr32: typeof ctr32;\n  dbl: typeof dbl;\n  xorBlock: typeof xorBlock;\n  xorend: typeof xorend;\n  s2v: typeof s2v;\n} = /* @__PURE__ */ Object.freeze({\n  expandKeyLE,\n  expandKeyDecLE,\n  encrypt,\n  decrypt,\n  encryptBlock,\n  decryptBlock,\n  ctrCounter,\n  ctr32,\n  dbl,\n  xorBlock,\n  xorend,\n  s2v,\n});\n\nexport const __TESTS: { incBytes: typeof incBytes } = /* @__PURE__ */ Object.freeze({\n  incBytes: incBytes,\n});\n", "import { cbc } from \"@noble/ciphers/aes.js\";\nimport { randomBytes } from \"@noble/hashes/utils.js\";\nimport { PrivateKey, PublicKey } from \"../crypto.js\";\nimport { BinaryReader, BinaryWriter } from \"../utils.js\";\nimport { sha256 as nobleSha256, sha512 as nobleSha512 } from \"@noble/hashes/sha2.js\";\n\n/**\n * Encrypts a binary memo payload with Hive memo key agreement.\n *\n * @param private_key - Sender memo private key.\n * @param public_key - Recipient memo public key.\n * @param message - Serialized plaintext memo bytes.\n * @param nonce - Optional nonce string for deterministic tests.\n * @returns Nonce, ciphertext, and checksum for an encrypted memo envelope.\n *\n * @remarks\n * The AES key is derived from the secp256k1 shared secret and nonce, matching\n * Hive's encrypted memo convention. Application code should normally use\n * `Memo.encode`, which handles string framing and base58 packaging.\n *\n * @example\n * ```ts\n * const encrypted = encrypt(senderMemoKey, recipientMemoPublicKey, memoBytes)\n * ```\n */\nexport const encrypt = (\n  private_key: PrivateKey,\n  public_key: PublicKey,\n  message: Uint8Array,\n  nonce: string | bigint = uniqueNonce(),\n): { nonce: bigint; message: Uint8Array; checksum: number } =>\n  crypt(private_key, public_key, nonce, message);\n\n/**\n * Decrypts a binary memo payload with Hive memo key agreement.\n *\n * @param private_key - Recipient or sender memo private key.\n * @param public_key - Counterparty memo public key.\n * @param nonce - Memo nonce from the encrypted envelope.\n * @param message - Ciphertext bytes.\n * @param checksum - Shared-secret checksum from the encrypted envelope.\n * @returns Decrypted memo bytes.\n *\n * @throws Error\n * Thrown when the checksum does not match the derived shared secret.\n *\n * @example\n * ```ts\n * const plaintext = decrypt(memoKey, otherMemoPublicKey, nonce, encrypted, check)\n * ```\n */\nexport const decrypt = (\n  private_key: PrivateKey,\n  public_key: PublicKey,\n  nonce: string | bigint,\n  message: Uint8Array,\n  checksum: number,\n): Uint8Array => crypt(private_key, public_key, nonce, message, checksum).message;\n\n/**\n * Encrypts or decrypts memo bytes using Hive's shared-secret derivation.\n *\n * @param private_key - Local memo private key.\n * @param public_key - Counterparty memo public key.\n * @param nonce - Memo nonce as a decimal string or native `bigint`.\n * @param message - Plaintext bytes when encrypting, ciphertext bytes when\n * decrypting.\n * @param checksum - Shared-secret checksum when decrypting. Omit when\n * encrypting.\n * @returns Normalized nonce, transformed bytes, and checksum.\n *\n * @remarks\n * The nonce is written with `BinaryWriter.writeUint64`, so native `bigint`\n * values travel through the same little-endian byte engine used by transaction\n * serialization. The AES key material is derived with Noble SHA-512 rather than\n * Node-specific hash wrappers.\n *\n * @throws Error\n * Thrown when a supplied checksum does not match the derived shared secret.\n */\nconst crypt = (\n  private_key: PrivateKey,\n  public_key: PublicKey,\n  nonce: string | bigint,\n  message: Uint8Array,\n  checksum?: number,\n): {\n  nonce: bigint;\n  message: Uint8Array;\n  checksum: number;\n} => {\n  const nonceL = BigInt(nonce.toString());\n  const S = private_key.get_shared_secret(public_key);\n\n  const writer = new BinaryWriter();\n  writer.writeUint64(nonceL);\n  writer.writeBytes(S);\n  const ebuf = writer.getBuffer();\n\n  const encryption_key = nobleSha512(ebuf);\n  const iv = encryption_key.slice(32, 48);\n  const tag = encryption_key.slice(0, 32);\n\n  // check if first 64 bit of sha256 hash treated as uint64_t truncated to 32 bits.\n  const check = nobleSha256(encryption_key).slice(0, 4);\n  const reader = new BinaryReader(check);\n  const check32 = reader.readUint32();\n\n  let result: Uint8Array;\n  if (checksum) {\n    if (check32 !== checksum) {\n      throw new Error(\"Invalid key\");\n    }\n    result = cryptoJsDecrypt(message, tag, iv);\n  } else {\n    result = cryptoJsEncrypt(message, tag, iv);\n  }\n  return {\n    checksum: check32,\n    message: result,\n    nonce: nonceL,\n  };\n};\n\n/**\n * Encrypts raw bytes with AES-256-CBC.\n *\n * @param message - Plaintext bytes.\n * @param key - 32-byte AES key.\n * @param iv - 16-byte initialization vector.\n * @returns Ciphertext bytes.\n */\nconst cryptoJsEncrypt = (message: Uint8Array, key: Uint8Array, iv: Uint8Array): Uint8Array => {\n  return cbc(key, iv).encrypt(message);\n};\n\n/**\n * Decrypts raw bytes with AES-256-CBC.\n *\n * @param message - Ciphertext bytes.\n * @param key - 32-byte AES key.\n * @param iv - 16-byte initialization vector.\n * @returns Plaintext bytes.\n */\nconst cryptoJsDecrypt = (message: Uint8Array, key: Uint8Array, iv: Uint8Array): Uint8Array => {\n  return cbc(key, iv).decrypt(message);\n};\n\n/**\n * Generates a unique 64-bit memo nonce.\n *\n * @returns A native `bigint` nonce.\n *\n * @remarks\n * The high bits come from current time and the low bits from cryptographic\n * entropy, producing the unsigned 64-bit value expected by Hive memo envelopes.\n */\nconst uniqueNonce = () => {\n  const entropy = randomBytes(2);\n  let long = BigInt(Date.now());\n  long = (long << 16n) | BigInt((entropy[0] << 8) | entropy[1]);\n  return long;\n};\n", "import { base58 as bs58 } from \"@scure/base\";\nimport { types } from \"./chain/deserializer.js\";\nimport { Types } from \"./chain/serializer.js\";\nimport { PrivateKey, PublicKey } from \"./crypto.js\";\nimport * as Aes from \"./helpers/aes.js\";\nimport { BinaryReader, BinaryWriter } from \"./utils.js\";\n\n/**\n * Encodes a Hive memo, encrypting messages that begin with `#`.\n *\n * @param private_key - Sender memo private key, either as a {@link PrivateKey}\n * instance or WIF string.\n * @param public_key - Recipient memo public key, either as a {@link PublicKey}\n * instance or Hive public-key string.\n * @param memo - Plain memo text. Only values beginning with `#` are encrypted;\n * unprefixed memos are returned unchanged.\n * @param testNonce - Optional deterministic nonce used by tests.\n * @returns The original plaintext memo or a `#`-prefixed encrypted memo payload.\n *\n * @remarks\n * Pollen serializes the memo with its binary writer before AES-CBC encryption so\n * Unicode text and Hive's encrypted memo structure round-trip consistently.\n *\n * @throws Error\n * Thrown when the runtime cannot support memo encryption or key conversion\n * fails.\n *\n * @example\n * ```ts\n * const encrypted = Memo.encode(senderMemoKey, recipientMemoPublicKey, '#hello nectar')\n * ```\n */\nconst encode = (\n  private_key: PrivateKey | string,\n  public_key: PublicKey | string,\n  memo: string,\n  testNonce?: string,\n): string => {\n  if (!memo.startsWith(\"#\")) {\n    return memo;\n  }\n  memo = memo.substring(1);\n  checkEncryption();\n  private_key = toPrivateObj(private_key);\n  public_key = toPublicObj(public_key);\n\n  const writer = new BinaryWriter();\n  writer.writeString(memo);\n  const memoBuffer = writer.getBuffer();\n\n  const { nonce, message, checksum } = Aes.encrypt(private_key, public_key, memoBuffer, testNonce);\n\n  const writer2 = new BinaryWriter();\n  Types.EncryptedMemo(writer2, {\n    check: checksum,\n    encrypted: message,\n    from: private_key.createPublic(),\n    nonce,\n    to: public_key,\n  });\n  const data = writer2.getBuffer();\n  return \"#\" + bs58.encode(data);\n};\n\n/**\n * Decodes a Hive memo, decrypting messages that begin with `#`.\n *\n * @param private_key - Recipient or sender memo private key, either as a\n * {@link PrivateKey} instance or WIF string.\n * @param memo - Memo text or encrypted memo payload.\n * @returns The original memo text. Encrypted memos remain `#`-prefixed after\n * decryption to preserve Hive memo semantics.\n *\n * @remarks\n * The decryptor determines the counterparty public key from the encrypted memo\n * envelope, derives the AES key through the memo shared secret, and supports\n * legacy payloads that were not length-prefixed.\n *\n * @throws Error\n * Thrown when the runtime cannot support memo encryption, the key is invalid,\n * or AES checksum validation fails.\n *\n * @example\n * ```ts\n * const plaintext = Memo.decode(recipientMemoKey, encryptedMemo)\n * console.log(plaintext)\n * ```\n */\nconst decode = (private_key: PrivateKey | string, memo: string): string => {\n  if (!memo.startsWith(\"#\")) {\n    return memo;\n  }\n  memo = memo.substring(1);\n  checkEncryption();\n  private_key = toPrivateObj(private_key);\n  const decodedMemo = bs58.decode(memo);\n  const memoBuffer: any = types.EncryptedMemoD(new BinaryReader(decodedMemo));\n  const { from, to, nonce, check, encrypted } = memoBuffer;\n  const pubkey = private_key.createPublic().toString();\n  const otherpub =\n    pubkey === new PublicKey(from.key).toString() ? new PublicKey(to.key) : new PublicKey(from.key);\n\n  const decrypted = Aes.decrypt(private_key, otherpub, nonce, encrypted, check);\n  const reader = new BinaryReader(decrypted);\n  try {\n    return \"#\" + reader.readString();\n  } catch (e: any) {\n    // Sender did not length-prefix the memo\n    return \"#\" + new TextDecoder().decode(decrypted);\n  }\n};\n\nlet encodeTest: boolean | undefined;\nconst checkEncryption: any = () => {\n  if (encodeTest === undefined) {\n    let plaintext: string | undefined;\n    encodeTest = true; // prevent infinate looping\n    try {\n      const wif = \"5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw\";\n      const pubkey = \"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA\";\n      const cyphertext = encode(wif, pubkey, \"#memo\u7231\");\n      plaintext = decode(wif, cyphertext);\n    } catch (e: any) {\n      throw new Error(e.message || String(e));\n    } finally {\n      encodeTest = plaintext === \"#memo\u7231\";\n    }\n  }\n  if (encodeTest === false) {\n    throw new Error(\"This environment does not support encryption.\");\n  }\n};\n\nconst toPrivateObj = (o: any): PrivateKey =>\n  o ? (o.key ? o : PrivateKey.fromString(o)) : o; /* null or undefined*/\nconst toPublicObj = (o: any): PublicKey =>\n  o ? (o.key ? o : PublicKey.fromString(o)) : o; /* null or undefined*/\n\n/**\n * Hive encrypted memo helper.\n *\n * @remarks\n * `Memo` exposes the two operations most applications need: encode before\n * broadcasting a transfer memo and decode after reading a transfer memo from\n * account history. The helper follows Hive's convention that only memos\n * beginning with `#` are encrypted.\n *\n * @example\n * ```ts\n * import { Memo } from '@srbde/pollen'\n *\n * const encrypted = Memo.encode(senderMemoKey, recipientMemoPublicKey, '#for your eyes')\n * const plaintext = Memo.decode(recipientMemoKey, encrypted)\n * ```\n */\nexport const Memo =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AAaL,CAAW,EACtC,IAAMmB,EAAcF,GAAK,OAAOf,CAAI,EAC9BO,EAAkBW,GAAM,eAAe,IAAIC,GAAaF,CAAW,CAAC,EACpE,CAAE,KAAAG,EAAM,GAAAC,EAAI,MAAAb,EAAO,MAAAc,EAAO,UAAAC,CAAU,EAAIhB,EAExCiB,EADS1B,EAAY,aAAa,EAAE,SAAS,IAEtC,IAAI2B,GAAUL,EAAK,GAAG,EAAE,SAAS,EAAI,IAAIK,GAAUJ,EAAG,GAAG,EAAI,IAAII,GAAUL,EAAK,GAAG,EAE1FM,EAAgBC,GAAQ7B,EAAa0B,EAAUhB,EAAOe,EAAWD,CAAK,EACtEM,EAAS,IAAIT,GAAaO,CAAS,EACzC,GAAI,CACF,MAAO,IAAME,EAAO,WAAW,CACjC,MAAiB,CAEf,MAAO,IAAM,IAAI,YAAY,EAAE,OAAOF,CAAS,CACjD,CACF,EAEIG,GACE3B,GAAuB,IAAM,CACjC,GAAI2B,KAAe,OAAW,CAC5B,IAAIC,EACJD,GAAa,GACb,GAAI,CACF,IAAME,EAAM,sDAENC,EAAanC,GAAOkC,EADX,wDACwB,aAAQ,EAC/CD,EAAYd,GAAOe,EAAKC,CAAU,CACpC,OAAS,EAAQ,CACf,MAAM,IAAI,MAAM,EAAE,SAAW,OAAO,CAAC,CAAC,CACxC,QAAE,CACAH,GAAaC,IAAc,aAC7B,CACF,CACA,GAAID,KAAe,GACjB,MAAM,IAAI,MAAM,+CAA+C,CAEnE,EAEM1B,GAAgB8B,GACpBA,IAAKA,EAAE,IAAMA,EAAIC,GAAW,WAAWD,CAAC,GACpC7B,GAAe6B,GACnBA,IAAKA,EAAE,IAAMA,EAAIR,GAAU,WAAWQ,CAAC,GAmB5BE,GAAO,CAClB,OAAAnB,GACA,OAAAnB,EACF",
  "names": ["utils_exports", "__export", "BinaryReader", "BinaryWriter", "assert", "buildWitnessUpdateOp", "bytesEqual", "concat", "copy", "exponentialBackoffWithJitter", "fromHex", "iteratorStream", "makeBitMaskFilter", "operationOrders", "retryingFetch", "sleep", "toHex", "PollenError", "_PollenError", "message", "info", "RPCError", "_RPCError", "SerializationError", "_SerializationError", "version_default", "BlockchainMode", "Blockchain", "client", "mode", "props", "options", "current", "seen", "sleep", "iteratorStream", "num", "operations", "operation", "Authority", "_Authority", "weight_threshold", "account_auths", "key_auths", "value", "PublicKey", "Asset", "_Asset", "amount", "symbol", "string", "expectedSymbol", "amountString", "value", "a", "b", "assert", "other", "factor", "divisor", "Price", "_Price", "base", "quote", "asset", "BroadcastAPI", "client", "comment", "key", "op", "options", "ops", "vote", "data", "assert", "username", "metadata", "creator", "prefix", "owner", "active", "posting", "memo_key", "ownerKey", "PrivateKey", "Authority", "activeKey", "postingKey", "PublicKey", "fee", "delegation", "symbol", "Asset", "chainProps", "creationFee", "claim_op", "create_op", "delegate_op", "operations", "props", "ref_block_num", "blockIdBytes", "fromHex", "ref_block_prefix", "tx", "transaction", "cryptoUtils", "trxId", "result", "method", "params", "DatabaseAPI", "client", "method", "params", "path", "Price", "account", "from", "limit", "blockNum", "onlyVirtual", "by", "query", "usernames", "txId", "filter", "stx", "HivemindAPI", "client", "method", "params", "options", "account", "AccountByKeyAPI", "client", "method", "params", "keys", "key", "HBD_NAI", "HIVE_NAI", "MarketHistoryAPI", "client", "method", "params", "HexBuffer", "_HexBuffer", "buffer", "value", "fromHex", "encoding", "toHex", "getVestingSharePrice", "props", "totalVestingFund", "Asset", "totalVestingShares", "Price", "getVests", "account", "subtract_delegated", "add_received", "vests", "vests_delegated", "vests_received", "withdraw_rate", "already_withdrawn", "withdraw_vests", "RCAPI", "client", "method", "params", "usernames", "username", "rc_account", "account", "max_mana", "getVests", "current_mana", "last_update_time", "delta", "percentage", "TransactionStatusAPI", "client", "method", "params", "transaction_id", "expiration", "NodeHealthTracker", "options", "node", "state", "api", "retryAfterSeconds", "delayMs", "apiState", "headBlock", "now", "allNodes", "healthy", "unhealthy", "snapshot", "apiFailures", "failure", "DEFAULT_CHAIN_ID", "fromHex", "DEFAULT_ADDRESS_PREFIX", "Client", "_Client", "address", "options", "assert", "defaultBackoff", "NodeHealthTracker", "DatabaseAPI", "BroadcastAPI", "MarketHistoryAPI", "Blockchain", "RCAPI", "HivemindAPI", "AccountByKeyAPI", "TransactionStatusAPI", "opts", "copy", "bootstrapNodes", "accounts", "meta", "api", "method", "params", "isBroadcast", "request", "serializeRpcBody", "version_default", "fetchTimeout", "tries", "response", "currentAddress", "retryingFetch", "formatValue", "value", "data", "message", "top", "topData", "formatStr", "parsedMessage", "lastIdx", "startIdx", "endIdx", "key", "unformattedData", "item", "rpcCode", "RPCError", "toHex", "v", "k", "exponentialBackoffWithJitter", "isBytes", "a", "isArrayOf", "isString", "arr", "item", "astr", "label", "input", "anumber", "n", "aArr", "astrArr", "isArrayOf", "anumArr", "chain", "args", "id", "a", "wrap", "b", "c", "encode", "x", "decode", "alphabet", "letters", "lettersA", "len", "indexes", "l", "digits", "letter", "i", "join", "separator", "from", "to", "convertRadix", "data", "from", "to", "aArr", "pos", "res", "digits", "d", "anumber", "dlen", "carry", "done", "i", "digit", "fromCarry", "digitBase", "div", "rounded", "radix", "num", "anumber", "_256", "bytes", "isBytes", "convertRadix", "digits", "anumArr", "genBase58", "abc", "chain", "radix", "alphabet", "join", "base58", "isBytes", "a", "anumber", "n", "title", "prefix", "abytes", "value", "length", "bytes", "len", "needsLen", "ofLen", "got", "message", "ahash", "h", "anumber", "aexists", "instance", "checkFinished", "aoutput", "out", "abytes", "min", "clean", "arrays", "i", "createView", "arr", "rotr", "word", "shift", "rotl", "hasHexBuiltin", "hexes", "_", "i", "bytesToHex", "bytes", "abytes", "hex", "asciis", "asciiToBase16", "ch", "hexToBytes", "error", "hl", "al", "array", "ai", "hi", "n1", "n2", "char", "concatBytes", "arrays", "sum", "i", "a", "abytes", "res", "pad", "createHasher", "hashCons", "info", "hashC", "msg", "opts", "tmp", "randomBytes", "bytesLength", "anumber", "cr", "oidNist", "suffix", "Chi", "a", "b", "c", "Maj", "HashMD", "blockLen", "outputLen", "padOffset", "isLE", "createView", "data", "aexists", "abytes", "view", "buffer", "len", "pos", "take", "dataView", "out", "aoutput", "clean", "i", "oview", "outLen", "state", "res", "to", "length", "finished", "destroyed", "SHA256_IV", "SHA512_IV", "Rho160", "Id160", "_", "i", "Pi160", "idxLR", "res", "j", "k", "idxL", "idxR", "shifts160", "shiftsL160", "idx", "shiftsR160", "Kl160", "Kr160", "ripemd_f", "group", "x", "y", "z", "BUF_160", "_RIPEMD160", "HashMD", "h0", "h1", "h2", "h3", "h4", "view", "offset", "al", "ar", "bl", "br", "cl", "cr", "dl", "dr", "el", "er", "rGroup", "hbl", "hbr", "rl", "rr", "sl", "sr", "tl", "rotl", "tr", "clean", "ripemd160", "createHasher", "U32_MASK64", "_32n", "fromBig", "n", "le", "split", "lst", "len", "Ah", "Al", "h", "l", "shrSH", "h", "_l", "s", "shrSL", "l", "rotrSH", "rotrSL", "rotrBH", "rotrBL", "add", "Ah", "Al", "Bh", "Bl", "l", "add3L", "Cl", "add3H", "low", "Ch", "add4L", "Dl", "add4H", "Dh", "add5L", "El", "add5H", "Eh", "SHA256_K", "SHA256_W", "SHA2_32B", "HashMD", "outputLen", "A", "B", "C", "D", "E", "F", "G", "H", "view", "offset", "i", "W15", "W2", "s0", "rotr", "s1", "sigma1", "T1", "Chi", "T2", "Maj", "clean", "_SHA256", "SHA256_IV", "K512", "split", "n", "SHA512_Kh", "SHA512_Kl", "SHA512_W_H", "SHA512_W_L", "SHA2_64B", "HashMD", "outputLen", "Ah", "Al", "Bh", "Bl", "Ch", "Cl", "Dh", "Dl", "Eh", "El", "Fh", "Fl", "Gh", "Gl", "Hh", "Hl", "view", "offset", "i", "W15h", "W15l", "s0h", "rotrSH", "shrSH", "s0l", "rotrSL", "shrSL", "W2h", "W2l", "s1h", "rotrBH", "s1l", "rotrBL", "SUMl", "add4L", "SUMh", "add4H", "sigma1h", "sigma1l", "CHIh", "CHIl", "T1ll", "add5L", "T1h", "add5H", "T1l", "sigma0h", "sigma0l", "MAJh", "MAJl", "add", "All", "add3L", "add3H", "clean", "_SHA512", "SHA512_IV", "sha256", "createHasher", "_SHA256", "oidNist", "sha512", "createHasher", "_SHA512", "oidNist", "abytes", "value", "length", "title", "anumber", "bytesToHex", "concatBytes", "arrays", "hexToBytes", "hex", "isBytes", "randomBytes", "bytesLength", "_0n", "_1n", "abool", "prefix", "abignumber", "n", "isPosBig", "asafenumber", "numberToHexUnpadded", "num", "hexToNumber", "bytesToNumberBE", "bytes", "bytesToNumberLE", "copyBytes", "numberToBytesBE", "len", "numberToBytesLE", "copyBytes", "bytes", "abytes", "isPosBig", "n", "_0n", "inRange", "min", "max", "aInRange", "title", "bitLen", "len", "_1n", "bitMask", "n", "_1n", "createHmacDrbg", "hashLen", "qByteLen", "hmacFn", "anumber", "u8n", "len", "NULL", "byte0", "byte1", "_maxDrbgIters", "v", "k", "i", "reset", "msgs", "concatBytes", "reseed", "seed", "gen", "out", "sl", "pred", "res", "validateObject", "object", "fields", "optFields", "checkField", "fieldName", "expectedType", "isOpt", "val", "current", "iter", "f", "_0n", "_1n", "_2n", "_3n", "_4n", "_5n", "_7n", "_8n", "_9n", "_16n", "mod", "a", "b", "result", "pow2", "x", "power", "modulo", "_0n", "res", "invert", "number", "a", "mod", "b", "y", "_1n", "u", "v", "q", "r", "m", "n", "assertIsSquare", "Fp", "root", "F", "sqrt3mod4", "p1div4", "_4n", "sqrt5mod8", "p5div8", "_5n", "_8n", "n2", "_2n", "nv", "i", "sqrt9mod16", "P", "Fp_", "Field", "tn", "tonelliShanks", "c1", "c2", "c3", "c4", "_7n", "_16n", "tv1", "tv2", "tv3", "tv4", "e1", "e2", "e3", "_3n", "Q", "S", "Z", "_Fp", "FpLegendre", "cc", "Q1div2", "M", "c", "t", "R", "t_tmp", "exponent", "FpSqrt", "_9n", "FIELD_FIELDS", "validateField", "field", "initial", "opts", "map", "val", "validateObject", "asafenumber", "_1n", "FpPow", "Fp", "num", "power", "F", "_0n", "p", "d", "FpInvertBatch", "nums", "passZero", "inverted", "multipliedAcc", "acc", "i", "invertedAcc", "FpLegendre", "Fp", "n", "F", "p1mod2", "_1n", "_2n", "powered", "yes", "zero", "no", "nLength", "n", "nBitLength", "anumber", "_0n", "bits", "bitLen", "_nBitLength", "nByteLength", "FIELD_SQRT", "_Field", "_1n", "ORDER", "opts", "_nbitLength", "num", "mod", "lhs", "rhs", "power", "FpPow", "invert", "sqrt", "FpSqrt", "numberToBytesLE", "numberToBytesBE", "bytes", "skipValidation", "abytes", "allowedLengths", "BYTES", "isLE", "modFromBytes", "padded", "scalar", "bytesToNumberLE", "bytesToNumberBE", "lst", "FpInvertBatch", "a", "b", "condition", "abool", "Field", "getFieldBytesLength", "fieldOrder", "_1n", "bitLength", "bitLen", "getMinHashLength", "length", "mapHashToField", "key", "isLE", "abytes", "len", "fieldLen", "minLen", "num", "bytesToNumberLE", "bytesToNumberBE", "reduced", "mod", "numberToBytesLE", "numberToBytesBE", "_0n", "_1n", "negateCt", "condition", "item", "neg", "normalizeZ", "c", "points", "invertedZs", "FpInvertBatch", "p", "i", "validateW", "W", "bits", "calcWOpts", "scalarBits", "windows", "windowSize", "maxNumber", "mask", "bitMask", "shiftBy", "calcOffsets", "n", "window", "wOpts", "wbits", "nextN", "_1n", "offsetStart", "offset", "isZero", "isNeg", "isNegF", "pointPrecomputes", "pointWindowSizes", "getW", "P", "assert0", "n", "_0n", "wNAF", "Point", "bits", "elm", "p", "d", "_1n", "point", "W", "windows", "windowSize", "calcWOpts", "points", "base", "window", "i", "precomputes", "f", "wo", "nextN", "offset", "isZero", "isNeg", "isNegF", "offsetF", "calcOffsets", "negateCt", "acc", "item", "transform", "comp", "scalar", "prev", "validateW", "mulEndoUnsafe", "k1", "k2", "p1", "p2", "createField", "order", "field", "isLE", "validateField", "Field", "createCurveFields", "type", "CURVE", "curveOpts", "FpFnLE", "p", "val", "_0n", "Fp", "Fn", "params", "createKeygen", "randomSecretKey", "getPublicKey", "seed", "secretKey", "_HMAC", "hash", "key", "ahash", "abytes", "blockLen", "pad", "clean", "buf", "aexists", "out", "aoutput", "to", "oHash", "iHash", "finished", "destroyed", "outputLen", "hmac", "hmac_", "message", "divNearest", "num", "den", "_2n", "_splitEndoScalar", "k", "basis", "n", "aInRange", "_0n", "a1", "b1", "a2", "b2", "c1", "c2", "k1", "k2", "k1neg", "k2neg", "MAX_NUM", "bitMask", "bitLen", "_1n", "validateSigFormat", "format", "validateSigOpts", "opts", "def", "validateObject", "optsn", "optName", "abool", "DERErr", "m", "DER", "tag", "data", "E", "asafenumber", "dataLen", "len", "numberToHexUnpadded", "lenLen", "abytes", "pos", "first", "isLong", "length", "lengthBytes", "b", "v", "abignumber", "hex", "bytesToNumberBE", "bytes", "int", "tlv", "seqBytes", "seqLeftBytes", "rBytes", "rLeftBytes", "sBytes", "sLeftBytes", "sig", "rs", "ss", "seq", "_3n", "_4n", "weierstrass", "params", "extraOpts", "validated", "createCurveFields", "Fp", "Fn", "CURVE", "cofactor", "CURVE_ORDER", "endo", "allowInfinityPoint", "lengths", "getWLengths", "assertCompressionIsSupported", "pointToBytes", "_c", "point", "isCompressed", "x", "y", "bx", "hasEvenY", "concatBytes", "pprefix", "pointFromBytes", "comp", "uncomp", "head", "tail", "y2", "weierstrassEquation", "sqrtError", "err", "evenY", "L", "isValidXY", "encodePoint", "decodePoint", "x2", "x3", "left", "right", "_4a3", "_27b2", "acoord", "title", "banZero", "aprjpoint", "other", "Point", "splitEndoScalarN", "finishEndo", "endoBeta", "k1p", "k2p", "negateCt", "X", "Y", "Z", "p", "P", "hexToBytes", "windowSize", "isLazy", "wnaf", "X1", "Y1", "Z1", "X2", "Y2", "Z2", "U1", "U2", "a", "b3", "X3", "Y3", "Z3", "t0", "t1", "t2", "t3", "t4", "t5", "scalar", "fake", "mul", "normalizeZ", "k1f", "k2f", "f", "sc", "p1", "p2", "mulEndoUnsafe", "invertedZ", "iz", "is0", "zz", "isTorsionFree", "clearCofactor", "bytesToHex", "bits", "wNAF", "getWLengths", "Fp", "Fn", "ecdh", "Point", "ecdhOpts", "randomBytes_", "randomBytes", "lengths", "getMinHashLength", "isValidSecretKey", "secretKey", "num", "isValidPublicKey", "publicKey", "isCompressed", "comp", "publicKeyUncompressed", "l", "randomSecretKey", "seed", "mapHashToField", "abytes", "getPublicKey", "isProbPub", "item", "allowedLengths", "isBytes", "isPub", "isSec", "getSharedSecret", "secretKeyA", "publicKeyB", "s", "utils", "keygen", "createKeygen", "ecdsa", "hash", "ecdsaOpts", "hash_", "ahash", "validateObject", "hmac", "key", "msg", "CURVE_ORDER", "fnBits", "defaultSigOpts", "hasLargeRecoveryLifts", "_2n", "_1n", "isBiggerThanHalfOrder", "number", "HALF", "validateRS", "title", "assertRecoverableCurve", "validateSigLength", "bytes", "format", "validateSigFormat", "size", "sizer", "Signature", "r", "recovery", "recid", "DER", "L", "hex", "hexToBytes", "messageHash", "radj", "x", "R", "concatBytes", "pprefix", "ir", "h", "bits2int_modN", "u1", "u2", "rb", "sb", "bytesToHex", "bits2int", "bytesToNumberBE", "delta", "ORDER_MASK", "bitMask", "int2octets", "aInRange", "_0n", "validateMsgAndHash", "message", "prehash", "prepSig", "opts", "lowS", "extraEntropy", "validateSigOpts", "h1int", "d", "seedArgs", "e", "m", "k2sig", "kBytes", "k", "ik", "q", "normS", "sign", "createHmacDrbg", "verify", "signature", "end", "sig", "P", "is", "recoverPublicKey", "secp256k1_CURVE", "secp256k1_ENDO", "_2n", "sqrtMod", "y", "P", "secp256k1_CURVE", "_3n", "_6n", "_11n", "_22n", "_23n", "_44n", "_88n", "b2", "b3", "b6", "pow2", "b9", "b11", "b22", "b44", "b88", "b176", "b220", "b223", "t1", "t2", "root", "Fpk1", "Field", "Pointk1", "weierstrass", "secp256k1_ENDO", "secp256k1", "ecdsa", "sha256", "NETWORK_ID", "ripemd160", "input", "data", "sha256", "sha512", "doubleSha256", "encodePublic", "key", "prefix", "checksum", "base58", "concat", "decodePublic", "encodedKey", "assert", "buffer", "checksumVerify", "bytesEqual", "encodePrivate", "decodePrivate", "isCanonicalSignature", "signature", "isWif", "privWif", "wifStr", "bufWif", "privKey", "newChecksum", "PublicKey", "_PublicKey", "DEFAULT_ADDRESS_PREFIX", "k", "point", "secp256k1", "toHex", "err", "wif", "value", "message", "PrivateKey", "_PrivateKey", "seed", "username", "password", "role", "attempts", "sigRaw", "extra", "Signature", "pubKey", "public_key", "S", "_Signature", "recovery", "string", "fromHex", "pubKeyBytes", "transactionDigest", "transaction", "chainId", "DEFAULT_CHAIN_ID", "writer", "BinaryWriter", "Types", "cause", "SerializationError", "transactionData", "signTransaction", "keys", "digest", "signedTransaction", "copy", "generateTrxId", "cryptoUtils", "VoidSerializer", "_buffer", "StringSerializer", "buffer", "data", "Int8Serializer", "Int16Serializer", "Int32Serializer", "Int64Serializer", "UInt8Serializer", "UInt16Serializer", "UInt32Serializer", "UInt64Serializer", "BooleanSerializer", "StaticVariantSerializer", "itemSerializers", "id", "item", "AssetSerializer", "asset", "Asset", "precision", "i", "DateSerializer", "PublicKeySerializer", "PublicKey", "BinarySerializer", "size", "HexBuffer", "len", "VariableBinarySerializer", "FlatMapSerializer", "keySerializer", "valueSerializer", "key", "value", "ArraySerializer", "itemSerializer", "ObjectSerializer", "keySerializers", "serializer", "error", "OptionalSerializer", "AuthoritySerializer", "BeneficiarySerializer", "PriceSerializer", "ProposalUpdateSerializer", "SignedBlockHeaderSerializer", "ChainPropertiesSerializer", "OperationDataSerializer", "operationId", "definitions", "objectSerializer", "OperationSerializers", "OperationSerializer", "operation", "TransactionSerializer", "EncryptedMemoSerializer", "Types", "PRE_CONNECTION_ERRORS", "FAILOVER_ERRORS", "assert", "condition", "message", "toHex", "data", "out", "i", "fromHex", "hex", "concat", "arrays", "totalLength", "acc", "arr", "result", "offset", "bytesEqual", "a", "b", "BinaryWriter", "size", "newBuffer", "value", "val", "low", "high", "view", "bytes", "BinaryReader", "buffer", "shift", "length", "sleep", "ms", "resolve", "iteratorStream", "iterator", "controller", "done", "error", "copy", "object", "isPreConnectionError", "code", "errCode", "shouldFailover", "nextNode", "nodes", "currentIndex", "exponentialBackoffWithJitter", "tries", "baseDelay", "maxDelay", "jitter", "retryingFetch", "currentAddress", "allAddresses", "opts", "timeout", "failoverThreshold", "consoleOnFailover", "backoff", "fetchTimeout", "retryContext", "healthTracker", "api", "isBroadcast", "logFailover", "orderedNodes", "nodeIndex", "totalNodes", "startTime", "nodesTriedInRound", "round", "lastError", "node", "parsedUrl", "err", "formatErr", "response", "retryAfterHeader", "retryAfterSec", "resJson", "statusText", "responseJson", "serialize", "serializer", "writer", "buildWitnessUpdateOp", "owner", "props", "key", "type", "Types", "operationOrders", "makeBitMaskFilter", "allowedOperations", "redFunction", "allowedOperation", "OP", "opFilter", "ops", "mask", "a", "b", "PublicKeyDeserializer", "reader", "bytes", "PublicKey", "UInt64Deserializer", "UInt32Deserializer", "BinaryDeserializer", "BufferDeserializer", "keyDeserializers", "buffer", "BinaryReader", "obj", "key", "deserializer", "error", "EncryptedMemoDeserializer", "types", "isBytes", "a", "abytes", "value", "length", "title", "bytes", "isBytes", "len", "needsLen", "prefix", "ofLen", "got", "message", "u32", "arr", "clean", "arrays", "i", "isLE", "byteSwap", "word", "byteSwap32", "arr", "i", "byteSwap", "swap32IfBE", "isLE", "u", "overlapBytes", "a", "b", "complexOverlapBytes", "input", "output", "wrapCipher", "params", "constructor", "wrappedCipher", "key", "args", "abytes", "nonce", "tagl", "cipher", "checkOutput", "fnLength", "output", "called", "data", "getOutput", "expectedLength", "out", "onlyAligned", "isAligned32", "isAligned32", "bytes", "copyBytes", "abytes", "BLOCK_SIZE", "POLY", "validateKeyLength", "key", "mul2", "n", "mul", "a", "b", "res", "sbox", "i", "x", "mul2", "box", "clean", "invSbox", "_", "j", "rotr32_8", "n", "rotl32_8", "genTtable", "fn", "T0", "T1", "T2", "T3", "T01", "T23", "sbox2", "idx", "tableEncoding", "s", "mul", "tableDecoding", "xPowers", "p", "expandKeyLE", "key", "abytes", "len", "validateKeyLength", "toClean", "isLE", "isAligned32", "copyBytes", "k32", "swap32IfBE", "u32", "Nk", "subByte", "applySbox", "xk", "t", "expandKeyDecLE", "encKey", "w", "apply0123", "s0", "s1", "s2", "s3", "encrypt", "k", "rounds", "t0", "t1", "t2", "t3", "decrypt", "validateBlockDecrypt", "data", "abytes", "BLOCK_SIZE", "validateBlockEncrypt", "plaintext", "pkcs5", "dst", "outLen", "remaining", "left", "getOutput", "complexOverlapBytes", "isLE", "isAligned32", "copyBytes", "b", "u32", "swap32IfBE", "o", "validatePKCS", "len", "lastByte", "valid", "shouldCheck", "eq", "padPCKS", "tmp", "tmp32", "paddingByte", "i", "cbc", "wrapCipher", "key", "iv", "opts", "pkcs5", "plaintext", "dst", "xk", "expandKeyLE", "b", "o", "_out", "validateBlockEncrypt", "_iv", "toClean", "isLE", "isAligned32", "copyBytes", "n32", "u32", "swap32IfBE", "s0", "s1", "s2", "s3", "i", "encrypt", "tmp32", "padPCKS", "clean", "ciphertext", "validateBlockDecrypt", "expandKeyDecLE", "getOutput", "complexOverlapBytes", "ps0", "ps1", "ps2", "ps3", "o0", "o1", "o2", "o3", "decrypt", "validatePKCS", "encrypt", "private_key", "public_key", "message", "nonce", "uniqueNonce", "crypt", "decrypt", "checksum", "nonceL", "S", "writer", "BinaryWriter", "ebuf", "encryption_key", "sha512", "iv", "tag", "check", "sha256", "check32", "BinaryReader", "result", "cryptoJsDecrypt", "cryptoJsEncrypt", "key", "cbc", "entropy", "randomBytes", "long", "encode", "private_key", "public_key", "memo", "testNonce", "checkEncryption", "toPrivateObj", "toPublicObj", "writer", "BinaryWriter", "memoBuffer", "nonce", "message", "checksum", "encrypt", "writer2", "Types", "data", "base58", "decode", "decodedMemo", "types", "BinaryReader", "from", "to", "check", "encrypted", "otherpub", "PublicKey", "decrypted", "decrypt", "reader", "encodeTest", "plaintext", "wif", "cyphertext", "o", "PrivateKey", "Memo"]
}
