{
  "version": 3,
  "sources": ["../src/crypto-error.ts", "../../../node_modules/.bun/multiformats@14.0.3/node_modules/multiformats/src/bytes.ts", "../../../node_modules/.bun/multiformats@14.0.3/node_modules/multiformats/src/vendor/base-x.js", "../../../node_modules/.bun/multiformats@14.0.3/node_modules/multiformats/src/bases/base.ts", "../../../node_modules/.bun/multiformats@14.0.3/node_modules/multiformats/src/bases/base32.ts", "../../../node_modules/.bun/multiformats@14.0.3/node_modules/multiformats/src/bases/base58.ts", "../../../node_modules/.bun/multiformats@14.0.3/node_modules/multiformats/src/bases/base64.ts", "../../common/src/type-utils.ts", "../../common/src/convert.ts", "../../common/src/logger.ts", "../../../node_modules/.bun/multiformats@14.0.3/node_modules/multiformats/src/bases/base36.ts", "../../../node_modules/.bun/multiformats@14.0.3/node_modules/multiformats/src/varint.ts", "../../../node_modules/.bun/multiformats@14.0.3/node_modules/multiformats/src/vendor/varint.js", "../../../node_modules/.bun/multiformats@14.0.3/node_modules/multiformats/src/hashes/digest.ts", "../../../node_modules/.bun/multiformats@14.0.3/node_modules/multiformats/src/cid.ts", "../../common/src/multicodec.ts", "../../common/src/object.ts", "../../common/src/stores.ts", "../../common/src/time.ts", "../src/algorithms/crypto-algorithm.ts", "../../../node_modules/.bun/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/utils.ts", "../../../node_modules/.bun/@noble+curves@2.2.0/node_modules/@noble/curves/src/utils.ts", "../../../node_modules/.bun/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/_md.ts", "../../../node_modules/.bun/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/_u64.ts", "../../../node_modules/.bun/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/sha2.ts", "../../../node_modules/.bun/@noble+curves@2.2.0/node_modules/@noble/curves/src/abstract/modular.ts", "../../../node_modules/.bun/@noble+curves@2.2.0/node_modules/@noble/curves/src/abstract/curve.ts", "../../../node_modules/.bun/@noble+curves@2.2.0/node_modules/@noble/curves/src/abstract/hash-to-curve.ts", "../../../node_modules/.bun/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/hmac.ts", "../../../node_modules/.bun/@noble+curves@2.2.0/node_modules/@noble/curves/src/abstract/weierstrass.ts", "../../../node_modules/.bun/@noble+curves@2.2.0/node_modules/@noble/curves/src/secp256k1.ts", "../src/jose/utils.ts", "../src/primitives/sha256.ts", "../src/jose/jwk.ts", "../src/primitives/secp256k1.ts", "../../../node_modules/.bun/@noble+curves@2.2.0/node_modules/@noble/curves/src/nist.ts", "../src/primitives/secp256r1.ts", "../src/algorithms/ecdsa.ts", "../../../node_modules/.bun/@noble+curves@2.2.0/node_modules/@noble/curves/src/abstract/edwards.ts", "../../../node_modules/.bun/@noble+curves@2.2.0/node_modules/@noble/curves/src/abstract/montgomery.ts", "../../../node_modules/.bun/@noble+curves@2.2.0/node_modules/@noble/curves/src/ed25519.ts", "../src/primitives/ed25519.ts", "../src/algorithms/eddsa.ts", "../src/algorithms/sha-2.ts", "../src/primitives/x25519.ts", "../src/algorithms/x25519.ts", "../src/local-key-manager.ts", "../src/primitives/webcrypto.ts", "../src/utils.ts", "../../../node_modules/.bun/cborg@4.5.8/node_modules/cborg/lib/is.js", "../../../node_modules/.bun/cborg@4.5.8/node_modules/cborg/lib/token.js", "../../../node_modules/.bun/cborg@4.5.8/node_modules/cborg/lib/byte-utils.js", "../../../node_modules/.bun/cborg@4.5.8/node_modules/cborg/lib/bl.js", "../../../node_modules/.bun/cborg@4.5.8/node_modules/cborg/lib/common.js", "../../../node_modules/.bun/cborg@4.5.8/node_modules/cborg/lib/0uint.js", "../../../node_modules/.bun/cborg@4.5.8/node_modules/cborg/lib/1negint.js", "../../../node_modules/.bun/cborg@4.5.8/node_modules/cborg/lib/2bytes.js", "../../../node_modules/.bun/cborg@4.5.8/node_modules/cborg/lib/3string.js", "../../../node_modules/.bun/cborg@4.5.8/node_modules/cborg/lib/4array.js", "../../../node_modules/.bun/cborg@4.5.8/node_modules/cborg/lib/5map.js", "../../../node_modules/.bun/cborg@4.5.8/node_modules/cborg/lib/6tag.js", "../../../node_modules/.bun/cborg@4.5.8/node_modules/cborg/lib/7float.js", "../../../node_modules/.bun/cborg@4.5.8/node_modules/cborg/lib/jump.js", "../../../node_modules/.bun/cborg@4.5.8/node_modules/cborg/lib/encode.js", "../../../node_modules/.bun/cborg@4.5.8/node_modules/cborg/lib/decode.js", "../src/cose/cbor.ts", "../src/cose/cose-key.ts", "../src/cose/cose-sign1.ts", "../src/cose/eat.ts", "../src/primitives/aes-gcm.ts", "../src/algorithms/aes-gcm.ts", "../../../node_modules/.bun/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/src/utils.ts", "../../../node_modules/.bun/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/src/aes.ts", "../src/primitives/aes-kw.ts", "../src/algorithms/aes-kw.ts", "../src/primitives/hkdf.ts", "../src/algorithms/hkdf.ts", "../src/primitives/pbkdf2.ts", "../src/algorithms/pbkdf2.ts", "../src/jose/jwe/header.ts", "../../../node_modules/.bun/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/src/_arx.ts", "../../../node_modules/.bun/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/src/_poly1305.ts", "../../../node_modules/.bun/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/src/chacha.ts", "../src/primitives/xchacha20-poly1305.ts", "../src/primitives/concat-kdf.ts", "../src/jose/jwe/key-management.ts", "../src/jose/jwe/flattened.ts", "../src/jose/jwe/compact.ts", "../src/primitives/aes-ctr.ts"],
  "sourcesContent": ["/**\n * A custom error class for Crypto-related errors.\n */\nexport class CryptoError extends Error {\n  /**\n   * Constructs an instance of CryptoError, a custom error class for handling Crypto-related errors.\n   *\n   * @param code - A {@link CryptoErrorCode} representing the specific type of error encountered.\n   * @param message - A human-readable description of the error.\n   */\n  constructor(public code: CryptoErrorCode, message: string) {\n    super(message);\n    this.name = 'CryptoError';\n\n    // Ensures that instanceof works properly, the correct prototype chain when using inheritance,\n    // and that V8 stack traces (like Chrome, Edge, and Node.js) are more readable and relevant.\n    Object.setPrototypeOf(this, new.target.prototype);\n\n    // Captures the stack trace in V8 engines (like Chrome, Edge, and Node.js).\n    // In non-V8 environments, the stack trace will still be captured.\n    if (Error.captureStackTrace) {\n      Error.captureStackTrace(this, CryptoError);\n    }\n  }\n}\n\n/**\n * An enumeration of possible Crypto error codes.\n */\nexport enum CryptoErrorCode {\n  /** The supplied algorithm identifier is not supported by the implementation. */\n  AlgorithmNotSupported = 'algorithmNotSupported',\n\n  /** The encoding operation (either encoding or decoding) failed. */\n  EncodingError = 'encodingError',\n\n  /** The COSE_Sign1 message does not conform to valid structure. */\n  InvalidCoseSign1 = 'invalidCoseSign1',\n\n  /** The EAT (Entity Attestation Token) is malformed or failed verification. */\n  InvalidEat = 'invalidEat',\n\n  /** The JWE supplied does not conform to valid syntax. */\n  InvalidJwe = 'invalidJwe',\n\n  /** The JWK supplied does not conform to valid syntax. */\n  InvalidJwk = 'invalidJwk',\n\n  /** The requested operation is not supported by the implementation. */\n  OperationNotSupported = 'operationNotSupported',\n}\n", "export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n  return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array<ArrayBuffer> {\n  const hexes = hex.match(/../g)\n  return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n  if (aa === bb) { return true }\n  if (aa.byteLength !== bb.byteLength) {\n    return false\n  }\n\n  for (let ii = 0; ii < aa.byteLength; ii++) {\n    if (aa[ii] !== bb[ii]) {\n      return false\n    }\n  }\n\n  return true\n}\n\n/**\n * Normalize binary input to a plain `Uint8Array` backed by an `ArrayBuffer`.\n *\n * Returns the input itself when it is already a plain `Uint8Array` over an\n * `ArrayBuffer`, otherwise a fresh view (or, for `SharedArrayBuffer`-backed\n * input, a copy) over the same bytes.\n *\n * Throws if input is not a recognised binary type.\n */\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array<ArrayBuffer> {\n  if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {\n    return toArrayBufferBackedArray(o)\n  }\n  if (o instanceof ArrayBuffer) {\n    return new Uint8Array(o)\n  }\n  if (ArrayBuffer.isView(o)) {\n    return toArrayBufferBackedArray(new Uint8Array(o.buffer, o.byteOffset, o.byteLength))\n  }\n  throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n  return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\n/**\n * Convert the passed string into a byte array, constraining each character\n * value to a single byte\n */\nexport function fromString (str: string): Uint8Array<ArrayBuffer> {\n  const output = new Uint8Array(str.length)\n\n  for (let i = 0; i < str.length; i++) {\n    output[i] = str.charCodeAt(i)\n  }\n\n  return output\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\n/**\n * Convert the passed byte array to a string, interpreting each byte as a single\n * character\n */\nexport function toString (b: Uint8Array): string {\n  const len = b.length\n\n  if (len <= MAX_ARGUMENTS_LENGTH) {\n    // @ts-expect-error cannot ordinarily apply a Uint8Array\n    return String.fromCharCode.apply(String, b) // avoid extra subarray()\n  }\n\n  // Decode in chunks to avoid \"call stack size exceeded\".\n  let res = ''\n  let i = 0\n  while (i < len) {\n    res += String.fromCharCode.apply(\n      String,\n      // @ts-expect-error cannot ordinarily apply a Uint8Array\n      b.subarray(i, i += MAX_ARGUMENTS_LENGTH)\n    )\n  }\n  return res\n}\n\nfunction isByteArrayWithArrayBuffer (b?: Uint8Array): b is Uint8Array<ArrayBuffer> {\n  return b?.buffer instanceof ArrayBuffer\n}\n\n/**\n * Ensures `b` is backed by an ArrayBuffer - if not a new Uint8Array will be\n * created and the contents of `b` copied into it.\n */\nexport function toArrayBufferBackedArray (b: Uint8Array): Uint8Array<ArrayBuffer> {\n  if (isByteArrayWithArrayBuffer(b)) {\n    return b\n  }\n\n  return b.slice()\n}\n", "/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n * @param {boolean} [caseInsensitive]\n */\nfunction base (ALPHABET, name, caseInsensitive) {\n  if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n  var BASE_MAP = new Uint8Array(256);\n  for (var j = 0; j < BASE_MAP.length; j++) {\n    BASE_MAP[j] = 255;\n  }\n  for (var i = 0; i < ALPHABET.length; i++) {\n    var x = ALPHABET.charAt(i);\n    var xc = x.charCodeAt(0);\n    if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n    BASE_MAP[xc] = i;\n    // For case-insensitive codecs, map the opposite case to the same index so\n    // differently cased input decodes without errors (multibase spec).\n    if (caseInsensitive) {\n      var xl = x.toLowerCase().charCodeAt(0);\n      var xu = x.toUpperCase().charCodeAt(0);\n      if (xl !== xc) { BASE_MAP[xl] = i; }\n      if (xu !== xc) { BASE_MAP[xu] = i; }\n    }\n  }\n  var BASE = ALPHABET.length;\n  var LEADER = ALPHABET.charAt(0);\n  var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n  var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n  /**\n   * @param {any[] | Iterable<number>} source\n   */\n  function encode (source) {\n    // @ts-ignore\n    if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n      source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n    } else if (Array.isArray(source)) {\n      source = Uint8Array.from(source);\n    }\n    if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n    if (source.length === 0) { return '' }\n        // Skip & count leading zeroes.\n    var zeroes = 0;\n    var length = 0;\n    var pbegin = 0;\n    var pend = source.length;\n    while (pbegin !== pend && source[pbegin] === 0) {\n      pbegin++;\n      zeroes++;\n    }\n        // Allocate enough space in big-endian base58 representation.\n    var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n    var b58 = new Uint8Array(size);\n        // Process the bytes.\n    while (pbegin !== pend) {\n      var carry = source[pbegin];\n            // Apply \"b58 = b58 * 256 + ch\".\n      var i = 0;\n      for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n        carry += (256 * b58[it1]) >>> 0;\n        b58[it1] = (carry % BASE) >>> 0;\n        carry = (carry / BASE) >>> 0;\n      }\n      if (carry !== 0) { throw new Error('Non-zero carry') }\n      length = i;\n      pbegin++;\n    }\n        // Skip leading zeroes in base58 result.\n    var it2 = size - length;\n    while (it2 !== size && b58[it2] === 0) {\n      it2++;\n    }\n        // Translate the result into a string.\n    var str = LEADER.repeat(zeroes);\n    for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n    return str\n  }\n  /**\n   * @param {string | string[]} source\n   */\n  function decodeUnsafe (source) {\n    if (typeof source !== 'string') { throw new TypeError('Expected String') }\n    if (source.length === 0) { return new Uint8Array() }\n    var psz = 0;\n        // Skip leading spaces.\n    if (source[psz] === ' ') { return }\n        // Skip and count leading '1's.\n    var zeroes = 0;\n    var length = 0;\n    while (source[psz] === LEADER) {\n      zeroes++;\n      psz++;\n    }\n        // Allocate enough space in big-endian base256 representation.\n    var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n    var b256 = new Uint8Array(size);\n        // Process the characters.\n    while (source[psz]) {\n            // Decode character\n      var carry = BASE_MAP[source.charCodeAt(psz)];\n            // Invalid character\n      if (carry === 255) { return }\n      var i = 0;\n      for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n        carry += (BASE * b256[it3]) >>> 0;\n        b256[it3] = (carry % 256) >>> 0;\n        carry = (carry / 256) >>> 0;\n      }\n      if (carry !== 0) { throw new Error('Non-zero carry') }\n      length = i;\n      psz++;\n    }\n        // Skip trailing spaces.\n    if (source[psz] === ' ') { return }\n        // Skip leading zeroes in b256.\n    var it4 = size - length;\n    while (it4 !== size && b256[it4] === 0) {\n      it4++;\n    }\n    var vch = new Uint8Array(zeroes + (size - it4));\n    var j = zeroes;\n    while (it4 !== size) {\n      vch[j++] = b256[it4++];\n    }\n    return vch\n  }\n  /**\n   * @param {string | string[]} string\n   */\n  function decode (string) {\n    var buffer = decodeUnsafe(string);\n    if (buffer) { return buffer }\n    throw new Error(`Non-${name} character`)\n  }\n  return {\n    encode: encode,\n    decodeUnsafe: decodeUnsafe,\n    decode: decode\n  }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n", "import { coerce } from '../bytes.ts'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.ts'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array<ArrayBuffer> }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder<Base extends string, Prefix extends string> implements MultibaseEncoder<Prefix>, BaseEncoder {\n  readonly name: Base\n  readonly prefix: Prefix\n  readonly baseEncode: EncodeFn\n\n  constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n    this.name = name\n    this.prefix = prefix\n    this.baseEncode = baseEncode\n  }\n\n  encode (bytes: Uint8Array): Multibase<Prefix> {\n    if (bytes instanceof Uint8Array) {\n      return `${this.prefix}${this.baseEncode(bytes)}`\n    } else {\n      throw Error('Unknown type, must be binary type')\n    }\n  }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder<Base extends string, Prefix extends string> implements MultibaseDecoder<Prefix>, UnibaseDecoder<Prefix>, BaseDecoder {\n  readonly name: Base\n  readonly prefix: Prefix\n  readonly baseDecode: DecodeFn\n  private readonly prefixCodePoint: number\n\n  constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n    this.name = name\n    this.prefix = prefix\n    const prefixCodePoint = prefix.codePointAt(0)\n    /* c8 ignore next 3 */\n    if (prefixCodePoint === undefined) {\n      throw new Error('Invalid prefix character')\n    }\n    this.prefixCodePoint = prefixCodePoint\n    this.baseDecode = baseDecode\n  }\n\n  decode (text: string): Uint8Array<ArrayBuffer> {\n    if (typeof text === 'string') {\n      if (text.codePointAt(0) !== this.prefixCodePoint) {\n        throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n      }\n      return this.baseDecode(text.slice(this.prefix.length))\n    } else {\n      throw Error('Can only multibase decode strings')\n    }\n  }\n\n  or<OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n    return or(this, decoder)\n  }\n}\n\ntype Decoders<Prefix extends string> = Record<Prefix, UnibaseDecoder<Prefix>>\n\nclass ComposedDecoder<Prefix extends string> implements MultibaseDecoder<Prefix>, CombobaseDecoder<Prefix> {\n  readonly decoders: Decoders<Prefix>\n\n  constructor (decoders: Decoders<Prefix>) {\n    this.decoders = decoders\n  }\n\n  or <OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n    return or(this, decoder)\n  }\n\n  decode (input: string): Uint8Array<ArrayBuffer> {\n    const prefix = input[0] as Prefix\n    const decoder = this.decoders[prefix]\n    if (decoder != null) {\n      return decoder.decode(input)\n    } else {\n      throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n    }\n  }\n}\n\nexport function or <L extends string, R extends string> (left: UnibaseDecoder<L> | CombobaseDecoder<L>, right: UnibaseDecoder<R> | CombobaseDecoder<R>): ComposedDecoder<L | R> {\n  return new ComposedDecoder({\n    ...(left.decoders ?? { [(left as UnibaseDecoder<L>).prefix]: left }),\n    ...(right.decoders ?? { [(right as UnibaseDecoder<R>).prefix]: right })\n  } as Decoders<L | R>)\n}\n\nexport class Codec<Base extends string, Prefix extends string> implements MultibaseCodec<Prefix>, MultibaseEncoder<Prefix>, MultibaseDecoder<Prefix>, BaseCodec, BaseEncoder, BaseDecoder {\n  readonly name: Base\n  readonly prefix: Prefix\n  readonly baseEncode: EncodeFn\n  readonly baseDecode: DecodeFn\n  readonly encoder: Encoder<Base, Prefix>\n  readonly decoder: Decoder<Base, Prefix>\n\n  constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n    this.name = name\n    this.prefix = prefix\n    this.baseEncode = baseEncode\n    this.baseDecode = baseDecode\n    this.encoder = new Encoder(name, prefix, baseEncode)\n    this.decoder = new Decoder(name, prefix, baseDecode)\n  }\n\n  encode (input: Uint8Array): string {\n    return this.encoder.encode(input)\n  }\n\n  decode (input: string): Uint8Array<ArrayBuffer> {\n    return this.decoder.decode(input)\n  }\n}\n\nexport function from <Base extends string, Prefix extends string> ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec<Base, Prefix> {\n  return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX <Base extends string, Prefix extends string> ({ name, prefix, alphabet, caseInsensitive = false }: { name: Base, prefix: Prefix, alphabet: string, caseInsensitive?: boolean }): Codec<Base, Prefix> {\n  const { encode, decode } = basex(alphabet, name, caseInsensitive)\n  return from({\n    prefix,\n    name,\n    encode,\n    decode: (text: string): Uint8Array<ArrayBuffer> => coerce(decode(text))\n  })\n}\n\nfunction decode (string: string, alphabetIdx: Record<string, number>, bitsPerChar: number, name: string): Uint8Array<ArrayBuffer> {\n  // Count the padding bytes:\n  let end = string.length\n  while (string[end - 1] === '=') {\n    --end\n  }\n\n  // Allocate the output:\n  const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n  // Parse the data:\n  let bits = 0 // Number of bits currently in the buffer\n  let buffer = 0 // Bits waiting to be written out, MSB first\n  let written = 0 // Next byte to write\n  for (let i = 0; i < end; ++i) {\n    // Read one character from the string:\n    const value = alphabetIdx[string[i]]\n    if (value === undefined) {\n      throw new SyntaxError(`Non-${name} character`)\n    }\n\n    // Append the bits to the buffer:\n    buffer = (buffer << bitsPerChar) | value\n    bits += bitsPerChar\n\n    // Write out some bits if the buffer has a byte's worth:\n    if (bits >= 8) {\n      bits -= 8\n      out[written++] = 0xff & (buffer >> bits)\n    }\n  }\n\n  // Verify that we have received just enough bits:\n  if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n    throw new SyntaxError('Unexpected end of data')\n  }\n\n  return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n  const pad = alphabet[alphabet.length - 1] === '='\n  const mask = (1 << bitsPerChar) - 1\n  let out = ''\n\n  let bits = 0 // Number of bits currently in the buffer\n  let buffer = 0 // Bits waiting to be written out, MSB first\n  for (let i = 0; i < data.length; ++i) {\n    // Slurp data into the buffer:\n    buffer = (buffer << 8) | data[i]\n    bits += 8\n\n    // Write out as much as we can:\n    while (bits > bitsPerChar) {\n      bits -= bitsPerChar\n      out += alphabet[mask & (buffer >> bits)]\n    }\n  }\n\n  // Partial character:\n  if (bits !== 0) {\n    out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n  }\n\n  // Add padding characters until we hit a byte boundary:\n  if (pad) {\n    while (((out.length * bitsPerChar) & 7) !== 0) {\n      out += '='\n    }\n  }\n\n  return out\n}\n\nfunction createAlphabetIdx (alphabet: string, caseInsensitive: boolean): Record<string, number> {\n  // Build the character lookup table:\n  const alphabetIdx: Record<string, number> = {}\n  for (let i = 0; i < alphabet.length; ++i) {\n    alphabetIdx[alphabet[i]] = i\n    // For case-insensitive codecs, map the opposite case to the same index so\n    // differently cased input decodes without errors (multibase spec).\n    if (caseInsensitive) {\n      const lower = alphabet[i].toLowerCase()\n      const upper = alphabet[i].toUpperCase()\n      if (lower !== alphabet[i]) {\n        alphabetIdx[lower] = i\n      }\n      if (upper !== alphabet[i]) {\n        alphabetIdx[upper] = i\n      }\n    }\n  }\n  return alphabetIdx\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 <Base extends string, Prefix extends string> ({ name, prefix, bitsPerChar, alphabet, caseInsensitive = false }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string, caseInsensitive?: boolean }): Codec<Base, Prefix> {\n  const alphabetIdx = createAlphabetIdx(alphabet, caseInsensitive)\n  return from({\n    prefix,\n    name,\n    encode (input: Uint8Array): string {\n      return encode(input, alphabet, bitsPerChar)\n    },\n    decode (input: string): Uint8Array<ArrayBuffer> {\n      return decode(input, alphabetIdx, bitsPerChar, name)\n    }\n  })\n}\n", "import { rfc4648 } from './base.ts'\n\nexport const base32 = rfc4648({\n  prefix: 'b',\n  name: 'base32',\n  alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n  bitsPerChar: 5,\n  caseInsensitive: true\n})\n\nexport const base32upper = rfc4648({\n  prefix: 'B',\n  name: 'base32upper',\n  alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n  bitsPerChar: 5,\n  caseInsensitive: true\n})\n\nexport const base32pad = rfc4648({\n  prefix: 'c',\n  name: 'base32pad',\n  alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n  bitsPerChar: 5,\n  caseInsensitive: true\n})\n\nexport const base32padupper = rfc4648({\n  prefix: 'C',\n  name: 'base32padupper',\n  alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n  bitsPerChar: 5,\n  caseInsensitive: true\n})\n\nexport const base32hex = rfc4648({\n  prefix: 'v',\n  name: 'base32hex',\n  alphabet: '0123456789abcdefghijklmnopqrstuv',\n  bitsPerChar: 5,\n  caseInsensitive: true\n})\n\nexport const base32hexupper = rfc4648({\n  prefix: 'V',\n  name: 'base32hexupper',\n  alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n  bitsPerChar: 5,\n  caseInsensitive: true\n})\n\nexport const base32hexpad = rfc4648({\n  prefix: 't',\n  name: 'base32hexpad',\n  alphabet: '0123456789abcdefghijklmnopqrstuv=',\n  bitsPerChar: 5,\n  caseInsensitive: true\n})\n\nexport const base32hexpadupper = rfc4648({\n  prefix: 'T',\n  name: 'base32hexpadupper',\n  alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n  bitsPerChar: 5,\n  caseInsensitive: true\n})\n\nexport const base32z = rfc4648({\n  prefix: 'h',\n  name: 'base32z',\n  alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n  bitsPerChar: 5\n})\n", "import { baseX } from './base.ts'\n\nexport const base58btc = baseX({\n  name: 'base58btc',\n  prefix: 'z',\n  alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n  name: 'base58flickr',\n  prefix: 'Z',\n  alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n", "import { rfc4648 } from './base.ts'\n\nexport const base64 = rfc4648({\n  prefix: 'm',\n  name: 'base64',\n  alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n  bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n  prefix: 'M',\n  name: 'base64pad',\n  alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n  bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n  prefix: 'u',\n  name: 'base64url',\n  alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n  bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n  prefix: 'U',\n  name: 'base64urlpad',\n  alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n  bitsPerChar: 6\n})\n", "/**\n * Represents an array of a fixed length, preventing modifications to its size.\n *\n * The `FixedLengthArray` utility type transforms a standard array into a variant where\n * methods that could alter the length are omitted. It leverages TypeScript's advanced types,\n * such as conditional types and mapped types, to ensure that the array cannot be resized\n * through methods like `push`, `pop`, `splice`, `shift`, and `unshift`. The utility type\n * maintains all other characteristics of a standard array, including indexing, iteration,\n * and type checking for its elements.\n *\n * Note: The type does not prevent direct assignment to indices, even if it would exceed\n * the original length. However, such actions would lead to TypeScript type errors.\n *\n * @example\n * ```ts\n * // Declare a variable with a type of fixed-length array of three strings.\n * let myFixedLengthArray: FixedLengthArray< [string, string, string]>;\n *\n * // Array declaration tests\n * myFixedLengthArray = [ 'a', 'b', 'c' ];  // OK\n * myFixedLengthArray = [ 'a', 'b', 123 ];  // TYPE ERROR\n * myFixedLengthArray = [ 'a' ];            // LENGTH ERROR\n * myFixedLengthArray = [ 'a', 'b' ];       // LENGTH ERROR\n *\n * // Index assignment tests\n * myFixedLengthArray[1] = 'foo';           // OK\n * myFixedLengthArray[1000] = 'foo';        // INVALID INDEX ERROR\n *\n * // Methods that mutate array length\n * myFixedLengthArray.push('foo');          // MISSING METHOD ERROR\n * myFixedLengthArray.pop();                // MISSING METHOD ERROR\n *\n * // Direct length manipulation\n * myFixedLengthArray.length = 123;         // READ-ONLY ERROR\n *\n * // Destructuring\n * let [ a ] = myFixedLengthArray;          // OK\n * let [ a, b ] = myFixedLengthArray;       // OK\n * let [ a, b, c ] = myFixedLengthArray;    // OK\n * let [ a, b, c, d ] = myFixedLengthArray; // INVALID INDEX ERROR\n * ```\n *\n * @template T extends any[] - The array type to be transformed.\n */\nexport type FixedLengthArray<T extends any[]> =\n  Pick<T, Exclude<keyof T, ArrayLengthMutationKeys>>\n  & {\n    /**\n     * Custom iterator for the `FixedLengthArray` type.\n     *\n     * This iterator allows the `FixedLengthArray` to be used in standard iteration\n     * contexts, such as `for...of` loops and spread syntax. It ensures that even though\n     * the array is of a fixed length with disabled mutation methods, it still retains\n     * iterable behavior similar to a regular array.\n     *\n     * @returns An IterableIterator for the array items.\n     */\n    [Symbol.iterator]: () => IterableIterator<ArrayItems<T>>\n  };\n\n/** Helper types for {@link FixedLengthArray} */\ntype ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift' | number;\ntype ArrayItems<T extends Array<any>> = T extends Array<infer TItems> ? TItems : never;\n\n/**\n * isArrayBufferSlice\n *\n * Checks if the ArrayBufferView represents a slice (subarray or a subview)\n * of an ArrayBuffer.\n *\n * An ArrayBufferView (TypedArray or DataView) can represent a portion of an\n * ArrayBuffer - such a view is said to be a \"slice\" of the original buffer.\n * This can occur when the `subarray` or `slice` method is called on a\n * TypedArray or when a DataView is created with a byteOffset and/or\n * byteLength that doesn't cover the full ArrayBuffer.\n *\n * @param arrayBufferView - The ArrayBufferView to be checked\n * @returns true if the ArrayBufferView represents a slice of an ArrayBuffer; false otherwise.\n */\nexport function isArrayBufferSlice(arrayBufferView: ArrayBufferView): boolean {\n  return arrayBufferView.byteOffset !== 0 || arrayBufferView.byteLength !== arrayBufferView.buffer.byteLength;\n}\n\n/**\n * Checks if the given object is an AsyncIterable.\n *\n * An AsyncIterable is an object that implements the AsyncIterable protocol,\n * which means it has a [Symbol.asyncIterator] method. This function checks\n * if the provided object conforms to this protocol by verifying the presence\n * and type of the [Symbol.asyncIterator] method.\n *\n * @param obj - The object to be checked for AsyncIterable conformity.\n * @returns True if the object is an AsyncIterable, false otherwise.\n *\n * @example\n * ```ts\n * // Returns true for a valid AsyncIterable\n * const asyncIterable = {\n *   async *[Symbol.asyncIterator]() {\n *     yield 1;\n *     yield 2;\n *   }\n * };\n * console.log(isAsyncIterable(asyncIterable)); // true\n * ```\n *\n * @example\n * ```ts\n * // Returns false for a regular object\n * console.log(isAsyncIterable({ a: 1, b: 2 })); // false\n * ```\n */\nexport function isAsyncIterable(obj: any): obj is AsyncIterable<any> {\n  if (typeof obj !== 'object' || obj === null) {\n    return false;\n  }\n\n  return typeof obj[Symbol.asyncIterator] === 'function';\n}\n\n/**\n * isDefined\n *\n * Utility function to check if a variable is neither null nor undefined.\n * This function helps in making TypeScript infer the type of the variable\n * as being defined, excluding `null` and `undefined`.\n *\n * The function uses strict equality (`!==`) for the comparison, ensuring\n * that the variable is not just falsy (like an empty string or zero),\n * but is truly either `null` or `undefined`.\n *\n * @param arg - The variable to be checked\n * @returns true if the variable is neither `null` nor `undefined`\n */\nexport function isDefined<T>(arg: T): arg is Exclude<T, null | undefined> {\n  return arg !== null && typeof arg !== 'undefined';\n}\n\n/**\n * Utility type that transforms a type `T` to have only certain keys `K` as required, while the\n * rest remain optional, except for keys specified in `O`, which are omitted entirely.\n *\n * This type is useful when you need a variation of a type where only specific properties are\n * required, and others are either optional or not included at all. It allows for more flexible type\n * definitions based on existing types without the need to redefine them.\n *\n * @template T - The original type to be transformed.\n * @template K - The keys of `T` that should be required.\n * @template O - The keys of `T` that should be omitted from the resulting type (optional).\n *\n * @example\n * ```ts\n * // Given an interface\n * interface Example {\n *   requiredProp: string;\n *   optionalProp?: number;\n *   anotherOptionalProp?: boolean;\n * }\n *\n * // Making 'optionalProp' required and omitting 'anotherOptionalProp'\n * type ModifiedExample = RequireOnly<Example, 'optionalProp', 'anotherOptionalProp'>;\n * // Result: { requiredProp?: string; optionalProp: number; }\n * ```\n */\nexport type RequireOnly<T, K extends keyof T, O extends keyof T = never> = Required<Pick<T, K>> & Omit<Partial<T>, O>;\n\n/**\n * universalTypeOf\n *\n * Why does this function exist?\n *\n * You can typically check if a value is of a particular type, such as\n * Uint8Array or ArrayBuffer, by using the `instanceof` operator. The\n * `instanceof` operator checks the prototype property of a constructor\n * in the object's prototype chain.\n *\n * However, there is a caveat with the `instanceof` check if the value\n * was created from a different JavaScript context (like an iframe or\n * a web worker). In those cases, the `instanceof` check might fail\n * because each context has a different global object, and therefore,\n * different built-in constructor functions.\n *\n * The `typeof` operator provides information about the type of the\n * operand in a less detailed way. For basic data types like number,\n * string, boolean, and undefined, the `typeof` operator works as\n * expected.  However, for objects, including arrays and null,\n * it always returns \"object\".  For functions, it returns \"function\".\n * So, while `typeof` is good for basic type checking, it doesn't\n * give detailed information about complex data types.\n *\n * Unlike `instanceof` and `typeof`, `Object.prototype.toString.call(value)`\n * can ensure a consistent result across different JavaScript\n * contexts.\n *\n * Credit for inspiration:\n *   Angus Croll\n *   https://github.com/angus-c\n *   https://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/\n */\nexport function universalTypeOf(value: unknown): string {\n  // Returns '[Object Type]' string.\n  const typeString = Object.prototype.toString.call(value);\n  // Returns ['Object', 'Type'] array or null.\n  const match = /\\s([a-zA-Z0-9]+)/.exec(typeString);\n  // Deconstructs the array and gets just the type from index 1.\n  const [_, type] = match as RegExpExecArray;\n\n  return type;\n}\n\n/**\n * Utility type to extract the type resolved by a Promise.\n *\n * This type unwraps the type `T` from `Promise<T>` if `T` is a Promise, otherwise returns `T` as\n * is. It's useful in situations where you need to handle the type returned by a promise-based\n * function in a synchronous context, such as defining types for test vectors or handling return\n * types in non-async code blocks.\n *\n * @template T - The type to unwrap from the Promise.\n *\n * @example\n * ```ts\n * // For a Promise type, it extracts the resolved type.\n * type AsyncNumber = Promise<number>;\n * type UnwrappedNumber = UnwrapPromise<AsyncNumber>; // number\n *\n * // For a non-Promise type, it returns the type as is.\n * type StringValue = string;\n * type UnwrappedString = UnwrapPromise<StringValue>; // string\n * ```\n */\nexport type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;", "import type { Multibase } from 'multiformats';\n\nimport { base32z } from 'multiformats/bases/base32';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { base64url } from 'multiformats/bases/base64';\n\nimport { isArrayBufferSlice, isAsyncIterable, universalTypeOf } from './type-utils.js';\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\nexport class Convert {\n  data: any;\n  format: string;\n\n  constructor(data: any, format: string) {\n    this.data = data;\n    this.format = format;\n  }\n\n  static arrayBuffer(data: ArrayBuffer): Convert {\n    return new Convert(data, 'ArrayBuffer');\n  }\n\n  static asyncIterable(data: AsyncIterable<any>): Convert {\n    if (!isAsyncIterable(data)) {\n      throw new TypeError('Input must be of type AsyncIterable.');\n    }\n    return new Convert(data, 'AsyncIterable');\n  }\n\n  static base32Z(data: string): Convert {\n    return new Convert(data, 'Base32Z');\n  }\n\n  static base58Btc(data: string): Convert {\n    return new Convert(data, 'Base58Btc');\n  }\n\n  static base64Url(data: string): Convert {\n    return new Convert(data, 'Base64Url');\n  }\n\n  /**\n   * Reference:\n   * The BufferSource type is a TypeScript type that represents an ArrayBuffer\n   * or one of the ArrayBufferView types, such a TypedArray (e.g., Uint8Array)\n   * or a DataView.\n   */\n  static bufferSource(data: BufferSource): Convert {\n    return new Convert(data, 'BufferSource');\n  }\n\n  static hex(data: string): Convert {\n    if (typeof data !== 'string') {\n      throw new TypeError('Hex input must be a string.');\n    }\n    if (data.length % 2 !== 0) {\n      throw new TypeError('Hex input must have an even number of characters.');\n    }\n    return new Convert(data, 'Hex');\n  }\n\n  static multibase(data: string): Convert {\n    return new Convert(data, 'Multibase');\n  }\n\n  static object(data: Record<string, any>): Convert {\n    return new Convert(data, 'Object');\n  }\n\n  static string(data: string): Convert {\n    return new Convert(data, 'String');\n  }\n\n  static uint8Array(data: Uint8Array): Convert {\n    return new Convert(data, 'Uint8Array');\n  }\n\n  toArrayBuffer(): ArrayBuffer {\n    switch (this.format) {\n\n      case 'Base58Btc': {\n        return base58btc.baseDecode(this.data).buffer as ArrayBuffer;\n      }\n\n      case 'Base64Url': {\n        return base64url.baseDecode(this.data).buffer as ArrayBuffer;\n      }\n\n      case 'BufferSource': {\n        const dataType = universalTypeOf(this.data);\n        if (dataType === 'ArrayBuffer') {\n          // Data is already an ArrayBuffer, No conversion is necessary.\n          return this.data;\n        } else if (ArrayBuffer.isView(this.data)) {\n          // Data is a DataView or a different TypedArray (e.g., Uint16Array).\n          if (isArrayBufferSlice(this.data)) {\n            // Data is a slice of an ArrayBuffer. Return a new ArrayBuffer or ArrayBufferView of the same slice.\n            return this.data.buffer.slice(this.data.byteOffset, this.data.byteOffset + this.data.byteLength) as ArrayBuffer;\n          } else {\n            // Data is a whole ArrayBuffer viewed as a different TypedArray or DataView. Return the whole ArrayBuffer.\n            return this.data.buffer as ArrayBuffer;\n          }\n        } else {\n          throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`);\n        }\n      }\n\n      case 'Hex': {\n        return this.toUint8Array().buffer as ArrayBuffer;\n      }\n\n      case 'String': {\n        return this.toUint8Array().buffer as ArrayBuffer;\n      }\n\n      case 'Uint8Array': {\n        return this.data.buffer as ArrayBuffer;\n      }\n\n      default:\n        throw new TypeError(`Conversion from ${this.format} to ArrayBuffer is not supported.`);\n    }\n  }\n\n  async toArrayBufferAsync(): Promise<ArrayBuffer> {\n    switch (this.format) {\n      case 'AsyncIterable': {\n        const blob = await this.toBlobAsync();\n        return await blob.arrayBuffer();\n      }\n\n      default:\n        throw new TypeError(`Asynchronous conversion from ${this.format} to ArrayBuffer is not supported.`);\n    }\n  }\n\n  toBase32Z(): string {\n    switch (this.format) {\n\n      case 'Uint8Array': {\n        return base32z.baseEncode(this.data);\n      }\n\n      default:\n        throw new TypeError(`Conversion from ${this.format} to Base64Z is not supported.`);\n    }\n  }\n\n  toBase58Btc(): string {\n    switch (this.format) {\n\n      case 'ArrayBuffer': {\n        const u8a = new Uint8Array(this.data);\n        return base58btc.baseEncode(u8a);\n      }\n\n      case 'Multibase': {\n        return this.data.substring(1);\n      }\n\n      case 'Uint8Array': {\n        return base58btc.baseEncode(this.data);\n      }\n\n      default:\n        throw new TypeError(`Conversion from ${this.format} to Base58Btc is not supported.`);\n    }\n  }\n\n  toBase64Url(): string {\n    switch (this.format) {\n\n      case 'ArrayBuffer': {\n        const u8a = new Uint8Array(this.data);\n        return base64url.baseEncode(u8a);\n      }\n\n      case 'BufferSource': {\n        const u8a = this.toUint8Array();\n        return base64url.baseEncode(u8a);\n      }\n\n      case 'Object': {\n        const string = JSON.stringify(this.data);\n        const u8a = textEncoder.encode(string);\n        return base64url.baseEncode(u8a);\n      }\n\n      case 'String': {\n        const u8a = textEncoder.encode(this.data);\n        return base64url.baseEncode(u8a);\n      }\n\n      case 'Uint8Array': {\n        return base64url.baseEncode(this.data);\n      }\n\n      default:\n        throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`);\n    }\n  }\n\n  async toBlobAsync(): Promise<Blob> {\n    switch (this.format) {\n      case 'AsyncIterable': {\n        // Initialize an array to hold the chunks from the AsyncIterable.\n        const chunks = [];\n\n        // Asynchronously iterate over each chunk in the AsyncIterable.\n        for await (const chunk of (this.data as AsyncIterable<any>)) {\n          // Append each chunk to the chunks array. These chunks can be of any type, typically binary data or text.\n          chunks.push(chunk);\n        }\n\n        // Create a new Blob from the aggregated chunks.\n        // The Blob constructor combines these chunks into a single Blob object.\n        const blob = new Blob(chunks);\n\n        return blob;\n      }\n\n      default:\n        throw new TypeError(`Asynchronous conversion from ${this.format} to Blob is not supported.`);\n    }\n  }\n\n  toHex(): string {\n    // pre-calculating Hex values improves runtime by 6-10x.\n    const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));\n\n    switch (this.format) {\n\n      case 'ArrayBuffer': {\n        const u8a = this.toUint8Array();\n        return Convert.uint8Array(u8a).toHex();\n      }\n\n      case 'Base64Url': {\n        const u8a = this.toUint8Array();\n        return Convert.uint8Array(u8a).toHex();\n      }\n\n      case 'Uint8Array': {\n        let hex = '';\n        for (let i = 0; i < this.data.length; i++) {\n          hex += hexes[this.data[i]];\n        }\n        return hex;\n      }\n\n      default:\n        throw new TypeError(`Conversion from ${this.format} to Hex is not supported.`);\n    }\n  }\n\n  toMultibase(): Multibase<any> {\n    switch (this.format) {\n      case 'Base58Btc': {\n        return `z${this.data}`;\n      }\n\n      default:\n        throw new TypeError(`Conversion from ${this.format} to Multibase is not supported.`);\n    }\n  }\n\n  toObject(): object {\n    switch (this.format) {\n\n      case 'Base64Url': {\n        const u8a = base64url.baseDecode(this.data);\n        const text = textDecoder.decode(u8a);\n        return JSON.parse(text);\n      }\n\n      case 'String': {\n        return JSON.parse(this.data);\n      }\n\n      case 'Uint8Array': {\n        const text = textDecoder.decode(this.data);\n        return JSON.parse(text);\n      }\n\n      default:\n        throw new TypeError(`Conversion from ${this.format} to Object is not supported.`);\n    }\n  }\n\n  async toObjectAsync<T = unknown>(): Promise<T> {\n    switch (this.format) {\n      case 'AsyncIterable': {\n        // Convert the AsyncIterable to a String.\n        const text = await this.toStringAsync();\n\n        // Parse the string as JSON. This step assumes that the string represents a valid JSON structure.\n        // JSON.parse() will convert the string into a corresponding JavaScript object. The caller\n        // chooses the return type via the `T` type parameter (defaults to `unknown` so callers\n        // must narrow before using the result, instead of `any` silently propagating).\n        const json = JSON.parse(text) as T;\n\n        // Return the parsed JavaScript object. The type of this object will depend on the structure\n        // of the JSON in the stream. It could be an object, array, string, number, etc.\n        return json;\n      }\n\n      default:\n        throw new TypeError(`Asynchronous conversion from ${this.format} to Object is not supported.`);\n    }\n  }\n\n  toString(): string {\n    switch (this.format) {\n\n      case 'ArrayBuffer': {\n        return textDecoder.decode(this.data);\n      }\n\n      case 'Base64Url': {\n        const u8a = base64url.baseDecode(this.data);\n        return textDecoder.decode(u8a);\n      }\n\n      case 'Object': {\n        return JSON.stringify(this.data);\n      }\n\n      case 'Uint8Array': {\n        return textDecoder.decode(this.data);\n      }\n\n      default:\n        throw new TypeError(`Conversion from ${this.format} to String is not supported.`);\n    }\n  }\n\n  async toStringAsync(): Promise<string> {\n    switch (this.format) {\n      case 'AsyncIterable': {\n        // Initialize an empty string to accumulate the decoded text.\n        let str = '';\n\n        // Iterate over the chunks from the AsyncIterable.\n        for await (const chunk of (this.data as AsyncIterable<any>)) {\n          // If the chunk is already a string, concatenate it directly.\n          if (typeof chunk === 'string')\n          {str += chunk;}\n          else\n          // If the chunk is a Uint8Array or similar, use the decoder to convert it to a string.\n          // The `stream: true` option lets the decoder handle multi-byte characters spanning\n          // multiple chunks.\n          {str += textDecoder.decode(chunk, { stream: true });}\n        }\n\n        // Finalize the decoding process to handle any remaining bytes and signal the end of the stream.\n        // The `stream: false` option flushes the decoder's internal state.\n        str += textDecoder.decode(undefined, { stream: false });\n\n        // Return the accumulated string.\n        return str;\n      }\n\n      default:\n        throw new TypeError(`Asynchronous conversion from ${this.format} to String is not supported.`);\n    }\n  }\n\n  toUint8Array(): Uint8Array {\n    switch (this.format) {\n\n      case 'ArrayBuffer': {\n        // \u00C7reate Uint8Array as a view on the ArrayBuffer.\n        // Note: The Uint8Array shares the same memory as the ArrayBuffer, so this operation is very efficient.\n        return new Uint8Array(this.data);\n      }\n\n      case 'Base32Z': {\n        return base32z.baseDecode(this.data);\n      }\n\n      case 'Base58Btc': {\n        return base58btc.baseDecode(this.data);\n      }\n\n      case 'Base64Url': {\n        return base64url.baseDecode(this.data);\n      }\n\n      case 'BufferSource': {\n        const dataType = universalTypeOf(this.data);\n        if (dataType === 'Uint8Array') {\n          // Data is already a Uint8Array. No conversion is necessary.\n          // Note: Uint8Array is a type of BufferSource.\n          return this.data;\n        } else if (dataType === 'ArrayBuffer') {\n          // Data is an ArrayBuffer, create Uint8Array as a view on the ArrayBuffer.\n          // Note: The Uint8Array shares the same memory as the ArrayBuffer, so this operation is very efficient.\n          return new Uint8Array(this.data);\n        } else if (ArrayBuffer.isView(this.data)) {\n          // Data is a DataView or a different TypedArray (e.g., Uint16Array).\n          return new Uint8Array(this.data.buffer, this.data.byteOffset, this.data.byteLength);\n        } else {\n          throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`);\n        }\n      }\n\n      case 'Hex': {\n        const u8a = new Uint8Array(this.data.length / 2);\n        for (let i = 0; i < this.data.length; i += 2) {\n          const byteValue = Number.parseInt(this.data.substring(i, i + 2), 16);\n          if (Number.isNaN(byteValue)) {\n            throw new TypeError('Input is not a valid hexadecimal string.');\n          }\n          u8a[i / 2] = byteValue;\n        }\n        return u8a;\n      }\n\n      case 'Object': {\n        const string = JSON.stringify(this.data);\n        return textEncoder.encode(string);\n      }\n\n      case 'String': {\n        return textEncoder.encode(this.data);\n      }\n\n      default:\n        throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`);\n    }\n  }\n\n  async toUint8ArrayAsync(): Promise<Uint8Array> {\n    switch (this.format) {\n      case 'AsyncIterable': {\n        const arrayBuffer = await this.toArrayBufferAsync();\n        return new Uint8Array(arrayBuffer);\n      }\n\n      default:\n        throw new TypeError(`Asynchronous conversion from ${this.format} to Uint8Array is not supported.`);\n    }\n  }\n}", "/**\n * Enbox logger level.\n */\nexport enum LogLevel {\n  Debug = 'debug',\n  Silent = 'silent',\n}\n\n/**\n * Enbox logger interface.\n */\nexport interface LoggerInterface {\n\n  /**\n   * Sets the log verbose level.\n   */\n  setLogLevel(logLevel: LogLevel): void;\n\n  /**\n   * Same as `info()`.\n   * Logs an informational message.\n   */\n  log (message: string): void;\n\n  /**\n   * Logs an informational message.\n   */\n  info(message: string): void;\n\n  /**\n   * Logs an error message.\n   */\n  error(message: string): void;\n}\n\n/**\n * An Enbox logger implementation.\n */\nclass EnboxLogger implements LoggerInterface {\n  private logLevel: LogLevel = LogLevel.Silent; // Default to silent/no-op log level\n\n  setLogLevel(logLevel: LogLevel): void {\n    this.logLevel = logLevel;\n  }\n\n  public log(message: string): void {\n    this.info(message);\n  }\n\n  public info(message: string): void {\n    if (this.logLevel === LogLevel.Silent) { return; }\n\n    console.info(message);\n  }\n\n  public error(message: string): void {\n    if (this.logLevel === LogLevel.Silent) { return; }\n\n    console.error(message);\n  }\n}\n\n// Export a singleton logger instance\nexport const logger = new EnboxLogger();\n\n// Attach logger to the global window object in browser environment for easy access to the logger instance.\n// e.g. can call `enboxLogger.setLogLevel('debug');` directly in browser console.\ndeclare global {\n  interface Window { enboxLogger?: EnboxLogger }\n}\n\nif (typeof window !== 'undefined') {\n  window.enboxLogger = logger;\n}\n", "import { baseX } from './base.ts'\n\nexport const base36 = baseX({\n  prefix: 'k',\n  name: 'base36',\n  alphabet: '0123456789abcdefghijklmnopqrstuvwxyz',\n  caseInsensitive: true\n})\n\nexport const base36upper = baseX({\n  prefix: 'K',\n  name: 'base36upper',\n  alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',\n  caseInsensitive: true\n})\n", "import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n  const code = varint.decode(data, offset)\n  return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n  varint.encode(int, target, offset)\n  return target\n}\n\nexport function encodingLength (int: number): number {\n  return varint.encodingLength(int)\n}\n", "/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n  , REST = 0x7F\n  , MSBALL = ~REST\n  , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n  out = out || [];\n  offset = offset || 0;\n  var oldOffset = offset;\n\n  while(num >= INT) {\n    out[offset++] = (num & 0xFF) | MSB;\n    num /= 128;\n  }\n  while(num & MSBALL) {\n    out[offset++] = (num & 0xFF) | MSB;\n    num >>>= 7;\n  }\n  out[offset] = num | 0;\n  \n  // @ts-ignore\n  encode.bytes = offset - oldOffset + 1;\n  \n  return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n  , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n  var res    = 0\n    , offset = offset || 0\n    , shift  = 0\n    , counter = offset\n    , b\n    , l = buf.length;\n\n  do {\n    if (counter >= l) {\n      // @ts-ignore\n      read.bytes = 0;\n      throw new RangeError('Could not decode varint')\n    }\n    b = buf[counter++];\n    res += shift < 28\n      ? (b & REST$1) << shift\n      : (b & REST$1) * Math.pow(2, shift);\n    shift += 7;\n  } while (b >= MSB$1)\n\n  // @ts-ignore\n  read.bytes = counter - offset;\n\n  return res\n}\n\nvar N1 = Math.pow(2,  7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n  return (\n    value < N1 ? 1\n  : value < N2 ? 2\n  : value < N3 ? 3\n  : value < N4 ? 4\n  : value < N5 ? 5\n  : value < N6 ? 6\n  : value < N7 ? 7\n  : value < N8 ? 8\n  : value < N9 ? 9\n  :              10\n  )\n};\n\nvar varint = {\n    encode: encode_1\n  , decode: decode\n  , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n", "import { coerce, equals as equalBytes, toArrayBufferBackedArray } from '../bytes.ts'\nimport * as varint from '../varint.ts'\nimport type { MultihashDigest } from './interface.ts'\n\n/**\n * Creates a multihash digest.\n */\nexport function create <Code extends number> (code: Code, digest: Uint8Array): Digest<Code, number> {\n  const size = digest.byteLength\n  const sizeOffset = varint.encodingLength(code)\n  const digestOffset = sizeOffset + varint.encodingLength(size)\n\n  const bytes = new Uint8Array(digestOffset + size)\n  varint.encodeTo(code, bytes, 0)\n  varint.encodeTo(size, bytes, sizeOffset)\n  bytes.set(digest, digestOffset)\n\n  return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n  const bytes = coerce(multihash)\n  const [code, sizeOffset] = varint.decode(bytes)\n  const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n  const digest = bytes.subarray(sizeOffset + digestOffset)\n\n  if (digest.byteLength !== size) {\n    throw new Error('Incorrect length')\n  }\n\n  return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n  if (a === b) {\n    return true\n  } else {\n    const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n    return (\n      a.code === data.code &&\n      a.size === data.size &&\n      data.bytes instanceof Uint8Array &&\n      equalBytes(a.bytes, data.bytes)\n    )\n  }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest<Code extends number, Size extends number> implements MultihashDigest {\n  readonly code: Code\n  readonly size: Size\n  readonly digest: Uint8Array<ArrayBuffer>\n  readonly bytes: Uint8Array<ArrayBuffer>\n\n  /**\n   * Creates a multihash digest.\n   */\n  constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n    this.code = code\n    this.size = size\n    this.digest = toArrayBufferBackedArray(digest)\n    this.bytes = toArrayBufferBackedArray(bytes)\n  }\n}\n\n/**\n * Used to check that the passed multihash has the passed code\n */\nexport function hasCode <T extends number> (digest: MultihashDigest, code: T): digest is MultihashDigest<T> {\n  return digest.code === code\n}\n", "import { base32 } from './bases/base32.ts'\nimport { base36 } from './bases/base36.ts'\nimport { base58btc } from './bases/base58.ts'\nimport { coerce, toArrayBufferBackedArray } from './bytes.ts'\nimport * as Digest from './hashes/digest.ts'\nimport * as varint from './varint.ts'\nimport type * as API from './link/interface.ts'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.ts'\n\nexport function format <T extends API.Link<unknown, number, number, API.Version>, Prefix extends string> (link: T, base?: API.MultibaseEncoder<Prefix>): API.ToString<T, Prefix> {\n  const { bytes, version } = link\n  switch (version) {\n    case 0:\n      return toStringV0(\n        bytes,\n        baseCache(link),\n        base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n      )\n    default:\n      return toStringV1(\n        bytes,\n        baseCache(link),\n        (base ?? base32.encoder) as API.MultibaseEncoder<Prefix>\n      )\n  }\n}\n\nexport function toJSON <Link extends API.UnknownLink> (link: Link): API.LinkJSON<Link> {\n  return {\n    '/': format(link)\n  }\n}\n\nexport function fromJSON <Link extends API.UnknownLink> (json: API.LinkJSON<Link>): CID<unknown, number, number, API.Version> {\n  return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap<API.UnknownLink, Map<string, string>>()\n\nfunction baseCache (cid: API.UnknownLink): Map<string, string> {\n  const baseCache = cache.get(cid)\n  if (baseCache == null) {\n    const baseCache = new Map()\n    cache.set(cid, baseCache)\n    return baseCache\n  }\n  return baseCache\n}\n\nexport class CID<Data = unknown, Format extends number = number, Alg extends number = number, Version extends API.Version = API.Version> implements API.Link<Data, Format, Alg, Version> {\n  readonly code: Format\n  readonly version: Version\n  readonly multihash: API.MultihashDigest<Alg>\n  readonly bytes: Uint8Array<ArrayBuffer>\n  readonly '/': Uint8Array<ArrayBuffer>\n\n  /**\n   * @param version - Version of the CID\n   * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n   * @param multihash - (Multi)hash of the of the content.\n   */\n  constructor (version: Version, code: Format, multihash: API.MultihashDigest<Alg>, bytes: Uint8Array) {\n    this.code = code\n    this.version = version\n    this.multihash = multihash\n    this.bytes = toArrayBufferBackedArray(bytes)\n\n    // flag to serializers that this is a CID and\n    // should be treated specially\n    this['/'] = this.bytes\n  }\n\n  /**\n   * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n   * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n   *\n   * @deprecated\n   */\n  get asCID (): this {\n    return this\n  }\n\n  // ArrayBufferView\n  get byteOffset (): number {\n    return this.bytes.byteOffset\n  }\n\n  // ArrayBufferView\n  get byteLength (): number {\n    return this.bytes.byteLength\n  }\n\n  toV0 (): CID<Data, API.DAG_PB, API.SHA_256, 0> {\n    switch (this.version) {\n      case 0: {\n        return this as CID<Data, API.DAG_PB, API.SHA_256, 0>\n      }\n      case 1: {\n        const { code, multihash } = this\n\n        if (code !== DAG_PB_CODE) {\n          throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n        }\n\n        // sha2-256\n        if (multihash.code !== SHA_256_CODE) {\n          throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n        }\n\n        return (\n          CID.createV0(\n            multihash as API.MultihashDigest<API.SHA_256>\n          )\n        )\n      }\n      default: {\n        throw Error(\n          `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n        )\n      }\n    }\n  }\n\n  toV1 (): CID<Data, Format, Alg, 1> {\n    switch (this.version) {\n      case 0: {\n        const { code, digest } = this.multihash\n        const multihash = Digest.create(code, digest)\n        return (\n          CID.createV1(this.code, multihash)\n        )\n      }\n      case 1: {\n        return this as CID<Data, Format, Alg, 1>\n      }\n      default: {\n        throw Error(\n          `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n        )\n      }\n    }\n  }\n\n  equals (other: unknown): other is CID<Data, Format, Alg, Version> {\n    return CID.equals(this, other)\n  }\n\n  static equals <Data, Format extends number, Alg extends number, Version extends API.Version>(self: API.Link<Data, Format, Alg, Version>, other: unknown): other is CID {\n    const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n    return (\n      unknown != null &&\n      self.code === unknown.code &&\n      self.version === unknown.version &&\n      Digest.equals(self.multihash, unknown.multihash)\n    )\n  }\n\n  toString (base?: API.MultibaseEncoder<string>): string {\n    return format(this, base)\n  }\n\n  toJSON (): API.LinkJSON<this> {\n    return { '/': format(this) }\n  }\n\n  link (): this {\n    return this\n  }\n\n  readonly [Symbol.toStringTag] = 'CID';\n\n  // Legacy\n\n  [Symbol.for('nodejs.util.inspect.custom')] (): string {\n    return `CID(${this.toString()})`\n  }\n\n  /**\n   * Takes any input `value` and returns a `CID` instance if it was\n   * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n   * it will return value back. If `value` is not instance of this CID\n   * class, but is compatible CID it will return new instance of this\n   * `CID` class. Otherwise returns null.\n   *\n   * This allows two different incompatible versions of CID library to\n   * co-exist and interop as long as binary interface is compatible.\n   */\n  static asCID <Data, Format extends number, Alg extends number, Version extends API.Version, U>(input: API.Link<Data, Format, Alg, Version> | U): CID<Data, Format, Alg, Version> | null {\n    if (input == null) {\n      return null\n    }\n\n    const value = input as any\n    if (value instanceof CID) {\n      // If value is instance of CID then we're all set.\n      return value\n    } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n      // If value isn't instance of this CID class but `this.asCID === this` or\n      // `value['/'] === value.bytes` is true it is CID instance coming from a\n      // different implementation (diff version or duplicate). In that case we\n      // rebase it to this `CID` implementation so caller is guaranteed to get\n      // instance with expected API.\n      const { version, code, multihash, bytes } = value\n      return new CID(\n        version,\n        code,\n        multihash as API.MultihashDigest<Alg>,\n        bytes ?? encodeCID(version, code, multihash.bytes)\n      )\n    } else if (value[cidSymbol] === true) {\n      // If value is a CID from older implementation that used to be tagged via\n      // symbol we still rebase it to the this `CID` implementation by\n      // delegating that to a constructor.\n      const { version, multihash, code } = value\n      const digest = Digest.decode(multihash) as API.MultihashDigest<Alg>\n      return CID.create(version, code, digest)\n    } else {\n      // Otherwise value is not a CID (or an incompatible version of it) in\n      // which case we return `null`.\n      return null\n    }\n  }\n\n  /**\n   * @param version - Version of the CID\n   * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n   * @param digest - (Multi)hash of the of the content.\n   */\n  static create <Data, Format extends number, Alg extends number, Version extends API.Version>(version: Version, code: Format, digest: API.MultihashDigest<Alg>): CID<Data, Format, Alg, Version> {\n    if (typeof code !== 'number') {\n      throw new Error('String codecs are no longer supported')\n    }\n\n    if (!(digest.bytes instanceof Uint8Array)) {\n      throw new Error('Invalid digest')\n    }\n\n    switch (version) {\n      case 0: {\n        if (code !== DAG_PB_CODE) {\n          throw new Error(\n            `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n          )\n        } else {\n          return new CID(version, code, digest, digest.bytes)\n        }\n      }\n      case 1: {\n        const bytes = encodeCID(version, code, digest.bytes)\n        return new CID(version, code, digest, bytes)\n      }\n      default: {\n        throw new Error('Invalid version')\n      }\n    }\n  }\n\n  /**\n   * Simplified version of `create` for CIDv0.\n   */\n  static createV0 <T = unknown>(digest: API.MultihashDigest<typeof SHA_256_CODE>): CID<T, typeof DAG_PB_CODE, typeof SHA_256_CODE, 0> {\n    return CID.create(0, DAG_PB_CODE, digest)\n  }\n\n  /**\n   * Simplified version of `create` for CIDv1.\n   *\n   * @param code - Content encoding format code.\n   * @param digest - Multihash of the content.\n   */\n  static createV1 <Data, Code extends number, Alg extends number>(code: Code, digest: API.MultihashDigest<Alg>): CID<Data, Code, Alg, 1> {\n    return CID.create(1, code, digest)\n  }\n\n  /**\n   * Decoded a CID from its binary representation. The byte array must contain\n   * only the CID with no additional bytes.\n   *\n   * An error will be thrown if the bytes provided do not contain a valid\n   * binary representation of a CID.\n   */\n  static decode <Data, Code extends number, Alg extends number, Version extends API.Version>(bytes: API.ByteView<API.Link<Data, Code, Alg, Version>>): CID<Data, Code, Alg, Version> {\n    const [cid, remainder] = CID.decodeFirst(bytes)\n    if (remainder.length !== 0) {\n      throw new Error('Incorrect length')\n    }\n    return cid\n  }\n\n  /**\n   * Decoded a CID from its binary representation at the beginning of a byte\n   * array.\n   *\n   * Returns an array with the first element containing the CID and the second\n   * element containing the remainder of the original byte array. The remainder\n   * will be a zero-length byte array if the provided bytes only contained a\n   * binary CID representation.\n   */\n  static decodeFirst <T, C extends number, A extends number, V extends API.Version>(bytes: API.ByteView<API.Link<T, C, A, V>>): [CID<T, C, A, V>, Uint8Array] {\n    const specs = CID.inspectBytes(bytes)\n    const prefixSize = specs.size - specs.multihashSize\n    const multihashBytes = coerce(\n      bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n    )\n    if (multihashBytes.byteLength !== specs.multihashSize) {\n      throw new Error('Incorrect length')\n    }\n    const digestBytes = multihashBytes.subarray(\n      specs.multihashSize - specs.digestSize\n    )\n    const digest = new Digest.Digest(\n      specs.multihashCode,\n      specs.digestSize,\n      digestBytes,\n      multihashBytes\n    )\n    const cid =\n      specs.version === 0\n        ? CID.createV0(digest as API.MultihashDigest<API.SHA_256>)\n        : CID.createV1(specs.codec, digest)\n    return [cid as CID<T, C, A, V>, bytes.subarray(specs.size)]\n  }\n\n  /**\n   * Inspect the initial bytes of a CID to determine its properties.\n   *\n   * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n   * bytes but for larger multicodec code values and larger multihash digest\n   * lengths these varints can be quite large. It is recommended that at least\n   * 10 bytes be made available in the `initialBytes` argument for a complete\n   * inspection.\n   */\n  static inspectBytes <T, C extends number, A extends number, V extends API.Version>(initialBytes: API.ByteView<API.Link<T, C, A, V>>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n    let offset = 0\n    const next = (): number => {\n      const [i, length] = varint.decode(initialBytes.subarray(offset))\n      offset += length\n      return i\n    }\n\n    let version = next() as V\n    let codec = DAG_PB_CODE as C\n    if (version as number === 18) {\n      // CIDv0\n      version = 0 as V\n      offset = 0\n    } else {\n      codec = next() as C\n    }\n\n    if (version !== 0 && version !== 1) {\n      throw new RangeError(`Invalid CID version ${version}`)\n    }\n\n    const prefixSize = offset\n    const multihashCode = next() as A // multihash code\n    const digestSize = next() // multihash length\n    const size = offset + digestSize\n    const multihashSize = size - prefixSize\n\n    return { version, codec, multihashCode, digestSize, multihashSize, size }\n  }\n\n  /**\n   * Takes cid in a string representation and creates an instance. If `base`\n   * decoder is not provided will use a default from the configuration. It will\n   * throw an error if encoding of the CID is not compatible with supplied (or\n   * a default decoder).\n   */\n  static parse <Prefix extends string, Data, Code extends number, Alg extends number, Version extends API.Version>(source: API.ToString<API.Link<Data, Code, Alg, Version>, Prefix>, base?: API.MultibaseDecoder<Prefix>): CID<Data, Code, Alg, Version> {\n    const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n    const cid = CID.decode(bytes)\n\n    if (cid.version === 0 && source[0] !== 'Q') {\n      throw Error('Version 0 CID string must not include multibase prefix')\n    }\n\n    // Cache string representation to avoid computing it on `this.toString()`\n    baseCache(cid).set(prefix, source)\n\n    return cid\n  }\n}\n\nfunction parseCIDtoBytes <Prefix extends string, Data, Code extends number, Alg extends number, Version extends API.Version> (source: API.ToString<API.Link<Data, Code, Alg, Version>, Prefix>, base?: API.MultibaseDecoder<Prefix>): [Prefix, API.ByteView<API.Link<Data, Code, Alg, Version>>] {\n  switch (source[0]) {\n    // CIDv0 is parsed differently\n    case 'Q': {\n      const decoder = base ?? base58btc\n      return [\n        base58btc.prefix as Prefix,\n        decoder.decode(`${base58btc.prefix}${source}`)\n      ]\n    }\n    case base58btc.prefix: {\n      const decoder = base ?? base58btc\n      return [base58btc.prefix as Prefix, decoder.decode(source)]\n    }\n    case base32.prefix: {\n      const decoder = base ?? base32\n      return [base32.prefix as Prefix, decoder.decode(source)]\n    }\n    case base36.prefix: {\n      const decoder = base ?? base36\n      return [base36.prefix as Prefix, decoder.decode(source)]\n    }\n    default: {\n      if (base == null) {\n        throw Error(\n          'To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided'\n        )\n      }\n      return [source[0] as Prefix, base.decode(source)]\n    }\n  }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map<string, string>, base: API.MultibaseEncoder<'z'>): string {\n  const { prefix } = base\n  if (prefix !== base58btc.prefix) {\n    throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n  }\n\n  const cid = cache.get(prefix)\n  if (cid == null) {\n    const cid = base.encode(bytes).slice(1)\n    cache.set(prefix, cid)\n    return cid\n  } else {\n    return cid\n  }\n}\n\nfunction toStringV1 <Prefix extends string> (bytes: Uint8Array, cache: Map<string, string>, base: API.MultibaseEncoder<Prefix>): string {\n  const { prefix } = base\n  const cid = cache.get(prefix)\n  if (cid == null) {\n    const cid = base.encode(bytes)\n    cache.set(prefix, cid)\n    return cid\n  } else {\n    return cid\n  }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n  const codeOffset = varint.encodingLength(version)\n  const hashOffset = codeOffset + varint.encodingLength(code)\n  const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n  varint.encodeTo(version, bytes, 0)\n  varint.encodeTo(code, bytes, codeOffset)\n  bytes.set(multihash, hashOffset)\n  return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n", "import { varint } from 'multiformats';\n\nexport type MulticodecCode = number;\n\nexport type MulticodecDefinition<MulticodecCode> = {\n  code: MulticodecCode;\n  // codeBytes: Uint8Array;\n  name: string;\n};\n\n/**\n * The `Multicodec` class provides an interface to prepend binary data\n * with a prefix that identifies the data that follows.\n * https://github.com/multiformats/multicodec/blob/master/table.csv\n *\n * Multicodec is a self-describing multiformat, it wraps other formats with\n * a tiny bit of self-description. A multicodec identifier is a\n * varint (variable integer) that indicates the format of the data.\n *\n * The canonical table of multicodecs can be access at the following URL:\n * https://github.com/multiformats/multicodec/blob/master/table.csv\n *\n * Example usage:\n *\n * ```ts\n * Multicodec.registerCodec({ code: 0xed, name: 'ed25519-pub' });\n * const prefixedData = Multicodec.addPrefix({ code: 0xed, data: new Uint8Array(32) });\n * ```\n */\nexport class Multicodec {\n  /**\n   * A static field containing a map of codec codes to their corresponding names.\n   */\n  static codeToName = new Map<MulticodecCode, string>();\n\n  /**\n   * A static field containing a map of codec names to their corresponding codes.\n   */\n  static nameToCode = new Map<string, MulticodecCode>();\n\n  /**\n   * Adds a multicodec prefix to input data.\n   *\n   * @param options - The options for adding a prefix.\n   * @param options.code - The codec code. Either the code or name must be provided.\n   * @param options.name - The codec name. Either the code or name must be provided.\n   * @param options.data - The data to be prefixed.\n   * @returns The data with the added prefix as a Uint8Array.\n   */\n  public static addPrefix(options: {\n    code?: MulticodecCode,\n    data: Uint8Array,\n    name?: string,\n  }): Uint8Array {\n    let { code, data, name } = options;\n\n    if (!(name ? !code : code)) {\n      throw new Error(`Either 'name' or 'code' must be defined, but not both.`);\n    }\n\n    // If code was given, confirm it exists, or lookup code by name.\n    code = Multicodec.codeToName.has(code!) ? code : Multicodec.nameToCode.get(name!);\n\n    // Throw error if a registered Codec wasn't found.\n    if (code === undefined) {\n      throw new Error(`Unsupported multicodec: ${options.name ?? options.code}`);\n    }\n\n    // Create a new array to store the prefix and input data.\n    const prefixLength = varint.encodingLength(code);\n    const dataWithPrefix = new Uint8Array(prefixLength + data.byteLength);\n    dataWithPrefix.set(data, prefixLength);\n\n    // Prepend the prefix.\n    varint.encodeTo(code, dataWithPrefix);\n\n    return dataWithPrefix;\n  }\n\n  /**\n   * Get the Multicodec code from given prefixed data.\n   *\n   * @param options - The options for getting the codec code.\n   * @param options.prefixedData - The data to extract the codec code from.\n   * @returns - The Multicodec code as a number.\n   */\n  public static getCodeFromData(options: {\n    prefixedData: Uint8Array\n  }): MulticodecCode {\n    const { prefixedData } = options;\n    const [code, _] = varint.decode(prefixedData);\n\n    return code;\n  }\n\n  /**\n   * Get the Multicodec code from given Multicodec name.\n   *\n   * @param options - The options for getting the codec code.\n   * @param options.name - The name to lookup.\n   * @returns - The Multicodec code as a number.\n   */\n  public static getCodeFromName(options: {\n    name: string\n  }): MulticodecCode {\n    const { name } = options;\n\n    // Throw error if a registered Codec wasn't found.\n    const code = Multicodec.nameToCode.get(name);\n    if (code === undefined) {\n      throw new Error(`Unsupported multicodec: ${name}`);\n    }\n\n    return code;\n  }\n\n  /**\n   * Get the Multicodec name from given Multicodec code.\n   *\n   * @param options - The options for getting the codec name.\n   * @param options.name - The code to lookup.\n   * @returns - The Multicodec name as a string.\n   */\n  public static getNameFromCode(options: {\n    code: MulticodecCode\n  }): string {\n    const { code } = options;\n\n    // Throw error if a registered Codec wasn't found.\n    const name = Multicodec.codeToName.get(code);\n    if (name === undefined) {\n      throw new Error(`Unsupported multicodec: ${code}`);\n    }\n\n    return name;\n  }\n\n  /**\n   * Registers a new codec in the Multicodec class.\n   *\n   * @param codec - The codec to be registered.\n   */\n  public static registerCodec(codec: MulticodecDefinition<MulticodecCode>): void {\n    Multicodec.codeToName.set(codec.code, codec.name);\n    Multicodec.nameToCode.set(codec.name, codec.code);\n  }\n\n  /**\n   * Returns the data with the Multicodec prefix removed.\n   *\n   * @param refixedData - The data to extract the codec code from.\n   * @returns {Uint8Array}\n   */\n  public static removePrefix(options: {\n    prefixedData: Uint8Array\n  }): { code: MulticodecCode, name: string, data: Uint8Array } {\n    const { prefixedData } = options;\n    const [code, codeByteLength] = varint.decode(prefixedData);\n\n    // Throw error if a registered Codec wasn't found.\n    const name = Multicodec.codeToName.get(code);\n    if (name === undefined) {\n      throw new Error(`Unsupported multicodec: ${code}`);\n    }\n\n    return { code, data: prefixedData.slice(codeByteLength), name };\n  }\n}\n\n// Pre-defined registered codecs:\nMulticodec.registerCodec({ code: 0xed, name: 'ed25519-pub' });\nMulticodec.registerCodec({ code: 0x1300, name: 'ed25519-priv' });\nMulticodec.registerCodec({ code: 0xec, name: 'x25519-pub' });\nMulticodec.registerCodec({ code: 0x1302, name: 'x25519-priv' });\nMulticodec.registerCodec({ code: 0xe7, name: 'secp256k1-pub' });\nMulticodec.registerCodec({ code: 0x1301, name: 'secp256k1-priv' });", "/**\n * Checks whether the given object has any properties.\n */\nexport function isEmptyObject(obj: unknown): boolean {\n  if (typeof obj !== 'object' || obj === null) {\n    return false;\n  }\n\n  if (Object.getOwnPropertySymbols(obj).length > 0) {\n    return false;\n  }\n\n  return Object.keys(obj).length === 0;\n}\n\n/**\n * Recursively removes all properties with an empty object or array as its value from the given object.\n *\n * Null-tolerant: skips `null` values without recursing into them.\n * `typeof null === 'object'` in JavaScript, so without an explicit guard\n * the recursion would call `Object.keys(null)` and throw.\n */\nexport function removeEmptyObjects(obj: Record<string, unknown>): void {\n  Object.keys(obj).forEach(key => {\n    const value = obj[key];\n    if (value !== null && typeof value === 'object') {\n      // recursive remove empty object or array properties in nested objects\n      removeEmptyObjects(value as Record<string, unknown>);\n    }\n\n    if (isEmptyObject(value)) {\n      delete obj[key];\n    }\n  });\n}\n\n/**\n * Recursively removes all properties with `undefined` as its value from the given object.\n *\n * Mutates `obj` in place and descends into nested objects. Null-tolerant:\n * `null` values are left in place but not recursed into (`typeof null ===\n * 'object'` in JavaScript, so without the guard the recursion would call\n * `Object.keys(null)` and throw). Use {@link omitUndefined} when you\n * want an immutable, shallow, type-preserving alternative.\n *\n * @see {@link omitUndefined} for the non-mutating, typed, shallow variant used\n *   by higher-level packages like `@enbox/api` to normalize call-site options.\n */\nexport function removeUndefinedProperties(obj: Record<string, unknown>): void {\n  Object.keys(obj).forEach(key => {\n    const value = obj[key];\n    if (value === undefined) {\n      delete obj[key];\n    } else if (value !== null && typeof value === 'object') {\n      removeUndefinedProperties(value as Record<string, unknown>); // recursive remove `undefined` properties in nested objects\n    }\n  });\n}\n\n/**\n * Returns a new object containing only the entries of `input` whose values are\n * not `undefined`. Pure \u2014 never mutates the input. Shallow \u2014 does not descend\n * into nested objects.\n *\n * Companion to {@link removeUndefinedProperties}, which mutates and recurses.\n * Pick the variant that matches the call site:\n *\n * | Helper                       | Mutates? | Recursive? | Typed?           |\n * |------------------------------|----------|------------|------------------|\n * | `removeUndefinedProperties`  | yes      | yes        | no (`Record`)    |\n * | `omitUndefined`              | no       | no         | yes (preserves T)|\n *\n * Both helpers are the single source of truth for the monorepo \u2014\n * `@enbox/dwn-sdk-js/utils/object.ts` re-exports them rather than holding\n * its own copy. New shape-transform helpers belong here.\n *\n * @example\n * ```ts\n * omitUndefined({ a: 1, b: undefined, c: 'x' });\n * // \u2192 { a: 1, c: 'x' }\n *\n * // Useful when building option payloads where `undefined` keys would break\n * // assertion equality in tests:\n * const opts = omitUndefined({ password: input.password, sync: input.sync });\n * ```\n */\nexport function omitUndefined<T extends object>(input: T): Partial<T> {\n  const result: Partial<T> = {};\n  for (const key of Object.keys(input) as (keyof T)[]) {\n    const value = input[key];\n    if (value !== undefined) {\n      result[key] = value;\n    }\n  }\n  return result;\n}", "import type { KeyValueStore } from './types.js';\n\n/**\n * The `MemoryStore` class is an implementation of\n * `KeyValueStore` that holds data in memory.\n *\n * It provides a basic key-value store that works synchronously and keeps all\n * data in memory. This can be used for testing, or for handling small amounts\n * of data with simple key-value semantics.\n *\n * Example usage:\n *\n * ```ts\n * const memoryStore = new MemoryStore<string, number>();\n * await memoryStore.set(\"key1\", 1);\n * const value = await memoryStore.get(\"key1\");\n * console.log(value); // 1\n * ```\n *\n * @public\n */\nexport class MemoryStore<K, V> implements KeyValueStore<K, V> {\n  /**\n   * A private field that contains the Map used as the key-value store.\n   */\n  private readonly store: Map<K, V> = new Map();\n\n  /**\n   * Clears all entries in the key-value store.\n   *\n   * @returns A Promise that resolves when the operation is complete.\n   */\n  public async clear(): Promise<void> {\n    this.store.clear();\n  }\n\n  /**\n   * This operation is no-op for `MemoryStore`.\n   */\n  public async open(): Promise<void> {\n    /** no-op */\n  }\n\n  /**\n   * This operation is no-op for `MemoryStore`.\n   */\n  public async close(): Promise<void> {\n    /** no-op */\n  }\n\n  /**\n   * Deletes an entry from the key-value store by its key.\n   *\n   * @param id - The key of the entry to delete.\n   * @returns A Promise that resolves to a boolean indicating whether the entry was successfully deleted.\n   */\n  public async delete(id: K): Promise<boolean> {\n    return this.store.delete(id);\n  }\n\n  /**\n   * Retrieves the value of an entry by its key.\n   *\n   * @param id - The key of the entry to retrieve.\n   * @returns A Promise that resolves to the value of the entry, or `undefined` if the entry does not exist.\n   */\n  public async get(id: K): Promise<V | undefined> {\n    return this.store.get(id);\n  }\n\n  /**\n   * Checks for the presence of an entry by key.\n   *\n   * @param id - The key to check for the existence of.\n   * @returns A Promise that resolves to a boolean indicating whether an element with the specified key exists or not.\n   */\n  public async has(id: K): Promise<boolean> {\n    return this.store.has(id);\n  }\n\n  /**\n   * Retrieves all values in the key-value store.\n   *\n   * @returns A Promise that resolves to an array of all values in the store.\n   */\n  public async list(): Promise<V[]> {\n    return Array.from(this.store.values());\n  }\n\n  /**\n   * Sets the value of an entry in the key-value store.\n   *\n   * @param id - The key of the entry to set.\n   * @param key - The new value for the entry.\n   * @returns A Promise that resolves when the operation is complete.\n   */\n  public async set(id: K, key: V): Promise<void> {\n    this.store.set(id, key);\n  }\n}\n", "/**\n * Time-related helpers shared across packages.\n *\n * @module\n */\n\nimport { logger } from './logger.js';\n\nexport type TimedOptions = {\n  /** Receives the success/failure timing line. Defaults to the shared Enbox logger. */\n  log?: (message: string) => void;\n};\n\nconst durationUnitMultipliers = new Map<string, number>([\n  ['ms', 1],\n  ['msec', 1],\n  ['msecs', 1],\n  ['millisecond', 1],\n  ['milliseconds', 1],\n  ['s', 1000],\n  ['sec', 1000],\n  ['secs', 1000],\n  ['second', 1000],\n  ['seconds', 1000],\n  ['m', 60 * 1000],\n  ['min', 60 * 1000],\n  ['mins', 60 * 1000],\n  ['minute', 60 * 1000],\n  ['minutes', 60 * 1000],\n  ['h', 60 * 60 * 1000],\n  ['hr', 60 * 60 * 1000],\n  ['hrs', 60 * 60 * 1000],\n  ['hour', 60 * 60 * 1000],\n  ['hours', 60 * 60 * 1000],\n  ['d', 24 * 60 * 60 * 1000],\n  ['day', 24 * 60 * 60 * 1000],\n  ['days', 24 * 60 * 60 * 1000],\n  ['w', 7 * 24 * 60 * 60 * 1000],\n  ['week', 7 * 24 * 60 * 60 * 1000],\n  ['weeks', 7 * 24 * 60 * 60 * 1000],\n  ['y', 365.25 * 24 * 60 * 60 * 1000],\n  ['yr', 365.25 * 24 * 60 * 60 * 1000],\n  ['yrs', 365.25 * 24 * 60 * 60 * 1000],\n  ['year', 365.25 * 24 * 60 * 60 * 1000],\n  ['years', 365.25 * 24 * 60 * 60 * 1000],\n]);\n\n/**\n * Returns a high-resolution monotonic timestamp in milliseconds.\n *\n * Uses `performance.now()` when available so elapsed durations are not\n * affected by wall-clock changes. Falls back to `Date.now()` in runtimes\n * that do not expose `performance`.\n */\nexport function nowMs(): number {\n  if (typeof performance !== 'undefined' && typeof performance.now === 'function') {\n    return performance.now();\n  }\n\n  return Date.now();\n}\n\n/**\n * Parses a human-readable duration string into milliseconds.\n *\n * Accepted units: milliseconds (`ms`), seconds (`s`), minutes (`m`), hours (`h`),\n * days (`d`), weeks (`w`), and years (`y`), including their common long-form\n * aliases such as `minutes` and `hours`. A bare numeric string is treated as\n * milliseconds.\n *\n * @throws Error if the input is empty, negative, non-finite, or uses an unknown unit.\n */\nexport function parseDurationInMilliseconds(duration: string): number {\n  const match = /^((?:\\d+|\\d*\\.\\d+))\\s*([a-zA-Z]+)?$/.exec(duration.trim());\n  if (match === null) {\n    throw new Error(`Invalid duration: '${duration}'`);\n  }\n\n  const durationUnit = match[2]?.toLowerCase() ?? 'ms';\n  const multiplier = durationUnitMultipliers.get(durationUnit);\n  if (multiplier === undefined) {\n    throw new Error(`Invalid duration unit: '${durationUnit}'`);\n  }\n\n  const durationInMilliseconds = Number(match[1]) * multiplier;\n  if (!Number.isFinite(durationInMilliseconds)) {\n    throw new Error(`Invalid duration: '${duration}'`);\n  }\n\n  return durationInMilliseconds;\n}\n\n/**\n * Times an async operation and logs a single success/failure duration line.\n *\n * The label is intentionally caller-defined so packages can include their own\n * log namespace, e.g. `[connect.perf] response.sign`.\n */\nexport async function timed<T>(\n  label: string,\n  fn: () => Promise<T>,\n  { log = logger.log.bind(logger) }: TimedOptions = {}\n): Promise<T> {\n  const start = nowMs();\n  try {\n    const result = await fn();\n    const elapsed = nowMs() - start;\n    log(`${label} ok in ${elapsed.toFixed(1)}ms`);\n    return result;\n  } catch (err) {\n    const elapsed = nowMs() - start;\n    log(`${label} fail in ${elapsed.toFixed(1)}ms`);\n    throw err;\n  }\n}\n\n/**\n * Returns a promise that resolves after the given duration.\n *\n * Use this anywhere you would otherwise inline\n * `new Promise(resolve => setTimeout(resolve, ms))` \u2014 retry backoff,\n * polling intervals, throttled tests, etc. Centralizing the idiom keeps\n * call sites readable and ensures every retry/poll path has one obvious\n * primitive to reach for.\n *\n * Negative or zero durations resolve on the next macrotask via\n * `setTimeout(_, 0)`; they do not throw.\n *\n * @param durationInMilliseconds - How long to wait, in milliseconds.\n * @returns A promise that resolves after the duration elapses.\n *\n * @example\n * ```ts\n * import { sleep } from '@enbox/common';\n *\n * await sleep(250); // pause for 250ms\n * ```\n */\nexport function sleep(durationInMilliseconds: number): Promise<void> {\n  return new Promise(resolve => setTimeout(resolve, Math.max(0, durationInMilliseconds)));\n}\n", "/**\n * Base class for all cryptographic algorithm implementations.\n */\nexport abstract class CryptoAlgorithm {}", "/**\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 * 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 * 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 * 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 * 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 * hash-to-curve from RFC 9380.\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.\n * https://www.rfc-editor.org/rfc/rfc9380\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport type { CHash, TArg, TRet } from '../utils.ts';\nimport {\n  abytes,\n  asafenumber,\n  asciiToBytes,\n  bytesToNumberBE,\n  copyBytes,\n  concatBytes,\n  isBytes,\n  validateObject,\n} from '../utils.ts';\nimport type { AffinePoint, PC_ANY, PC_F, PC_P } from './curve.ts';\nimport { FpInvertBatch, mod, type IField } from './modular.ts';\n\n/** ASCII domain-separation tag or raw bytes. */\nexport type AsciiOrBytes = string | Uint8Array;\ntype H2CDefaults = {\n  DST: AsciiOrBytes;\n  expand: 'xmd' | 'xof';\n  hash: CHash;\n  p: bigint;\n  m: number;\n  k: number;\n  encodeDST?: AsciiOrBytes;\n};\n\n/**\n * * `DST` is a domain separation tag, defined in section 2.2.5\n * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m\n * * `m` is extension degree (1 for prime fields)\n * * `k` is the target security target in bits (e.g. 128), from section 5.1\n * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF)\n * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props\n */\nexport type H2COpts = {\n  /** Domain separation tag. */\n  DST: AsciiOrBytes;\n  /** Expander family used by RFC 9380. */\n  expand: 'xmd' | 'xof';\n  /** Hash or XOF implementation used by the expander. */\n  hash: CHash;\n  /** Base-field characteristic. */\n  p: bigint;\n  /** Extension degree (`1` for prime fields). */\n  m: number;\n  /** Target security level in bits. */\n  k: number;\n};\n/** Hash-only subset of RFC 9380 options used by per-call overrides. */\nexport type H2CHashOpts = {\n  /** Expander family used by RFC 9380. */\n  expand: 'xmd' | 'xof';\n  /** Hash or XOF implementation used by the expander. */\n  hash: CHash;\n};\n/**\n * Map one hash-to-field output tuple onto affine curve coordinates.\n * Implementations receive the validated scalar tuple by reference for performance and MUST treat it\n * as read-only. Callers that need scratch space should copy before mutating.\n * @param scalar - Field-element tuple produced by `hash_to_field`.\n * @returns Affine point before subgroup clearing.\n */\nexport type MapToCurve<T> = (scalar: bigint[]) => AffinePoint<T>;\n\n// Separated from initialization opts, so users won't accidentally change per-curve parameters\n// (changing DST is ok!)\n/** Per-call override for the domain-separation tag. */\nexport type H2CDSTOpts = {\n  /** Domain-separation tag override. */\n  DST: AsciiOrBytes;\n};\n/** Base hash-to-curve helpers shared by `hashToCurve` and `encodeToCurve`. */\nexport type H2CHasherBase<PC extends PC_ANY> = {\n  /**\n   * Hash arbitrary bytes to one curve point.\n   * @param msg - Input message bytes.\n   * @param options - Optional domain-separation override. See {@link H2CDSTOpts}.\n   * @returns Curve point after hash-to-curve.\n   */\n  hashToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC>;\n  /**\n   * Hash arbitrary bytes to one scalar.\n   * @param msg - Input message bytes.\n   * @param options - Optional domain-separation override. See {@link H2CDSTOpts}.\n   * @returns Scalar reduced into the target field.\n   */\n  hashToScalar(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): bigint;\n  /**\n   * Derive one curve point from non-uniform bytes without the random-oracle\n   * guarantees of `hashToCurve`.\n   * Accepts the same arguments as `hashToCurve`, but runs the encode-to-curve\n   * path instead of the random-oracle construction.\n   */\n  deriveToCurve?(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC>;\n  /** Point constructor for the target curve. */\n  Point: PC;\n};\n/**\n * RFC 9380 methods, with cofactor clearing. See {@link https://www.rfc-editor.org/rfc/rfc9380#section-3 | RFC 9380 section 3}.\n *\n * * hashToCurve: `map(hash(input))`, encodes RANDOM bytes to curve (WITH hashing)\n * * encodeToCurve: `map(hash(input))`, encodes NON-UNIFORM bytes to curve (WITH hashing)\n * * mapToCurve: `map(scalars)`, encodes NON-UNIFORM scalars to curve (NO hashing)\n */\nexport type H2CHasher<PC extends PC_ANY> = H2CHasherBase<PC> & {\n  /**\n   * Encode non-uniform bytes to one curve point.\n   * @param msg - Input message bytes.\n   * @param options - Optional domain-separation override. See {@link H2CDSTOpts}.\n   * @returns Curve point after encode-to-curve.\n   */\n  encodeToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC>;\n  /** Deterministic map from `hash_to_field` tuples into affine coordinates. */\n  mapToCurve: MapToCurve<PC_F<PC>>;\n  /** Default RFC 9380 options captured by this hasher bundle. */\n  defaults: H2CDefaults;\n};\n\n// Octet Stream to Integer. \"spec\" implementation of os2ip is 2.5x slower vs bytesToNumberBE.\nconst os2ip = bytesToNumberBE;\n\n// Integer to Octet Stream (numberToBytesBE).\nfunction i2osp(value: number, length: number): TRet<Uint8Array> {\n  asafenumber(value);\n  asafenumber(length);\n  // This helper stays on the JS bitwise/u32 fast-path. Callers that need wider encodings should\n  // use bigint + numberToBytesBE instead of routing large widths through this small helper.\n  if (length < 0 || length > 4) throw new Error('invalid I2OSP length: ' + length);\n  if (value < 0 || value > 2 ** (8 * length) - 1) throw new Error('invalid I2OSP input: ' + value);\n  const res = Array.from({ length }).fill(0) as number[];\n  for (let i = length - 1; i >= 0; i--) {\n    res[i] = value & 0xff;\n    value >>>= 8;\n  }\n  return new Uint8Array(res) as TRet<Uint8Array>;\n}\n\n// RFC 9380 only applies strxor() to equal-length strings; callers must preserve that invariant.\nfunction strxor(a: TArg<Uint8Array>, b: TArg<Uint8Array>): TRet<Uint8Array> {\n  const arr = new Uint8Array(a.length);\n  for (let i = 0; i < a.length; i++) {\n    arr[i] = a[i] ^ b[i];\n  }\n  return arr as TRet<Uint8Array>;\n}\n\n// User can always use utf8 if they want, by passing Uint8Array.\n// If string is passed, we treat it as ASCII: other formats are likely a mistake.\nfunction normDST(DST: TArg<AsciiOrBytes>): TRet<Uint8Array> {\n  if (!isBytes(DST) && typeof DST !== 'string')\n    throw new Error('DST must be Uint8Array or ascii string');\n  const dst = typeof DST === 'string' ? asciiToBytes(DST) : DST;\n  // RFC 9380 \u00A73.1 requirement 2: tags \"MUST have nonzero length\".\n  if (dst.length === 0) throw new Error('DST must be non-empty');\n  return dst as TRet<Uint8Array>;\n}\n\n/**\n * Produces a uniformly random byte string using a cryptographic hash\n * function H that outputs b bits.\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 | RFC 9380 section 5.3.1}.\n * @param msg - Input message.\n * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and\n *   oversize-hashes DST when needed.\n * @param lenInBytes - Output length.\n * @param H - Hash function.\n * @returns Uniform byte string.\n * @throws If the message, DST, hash, or output length is invalid. {@link Error}\n * @example\n * Expand one message into uniform bytes with the XMD construction.\n *\n * ```ts\n * import { expand_message_xmd } from '@noble/curves/abstract/hash-to-curve.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const uniform = expand_message_xmd(new TextEncoder().encode('hello noble'), 'DST', 32, sha256);\n * ```\n */\nexport function expand_message_xmd(\n  msg: TArg<Uint8Array>,\n  DST: TArg<AsciiOrBytes>,\n  lenInBytes: number,\n  H: TArg<CHash>\n): TRet<Uint8Array> {\n  abytes(msg);\n  asafenumber(lenInBytes);\n  DST = normDST(DST);\n  // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n  if (DST.length > 255) DST = H(concatBytes(asciiToBytes('H2C-OVERSIZE-DST-'), DST));\n  const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;\n  const ell = Math.ceil(lenInBytes / b_in_bytes);\n  if (lenInBytes > 65535 || ell > 255) throw new Error('expand_message_xmd: invalid lenInBytes');\n  const DST_prime = concatBytes(DST, i2osp(DST.length, 1));\n  const Z_pad = new Uint8Array(r_in_bytes); // RFC 9380: Z_pad = I2OSP(0, s_in_bytes)\n  const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str\n  const b = new Array<Uint8Array>(ell);\n  const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));\n  b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));\n  // `b[0]` already stores RFC `b_1`, so only derive `b_2..b_ell` here. The old `<= ell`\n  // loop computed one extra tail block, which was usually sliced away but broke at max `ell=255`\n  // by reaching `I2OSP(256, 1)`.\n  for (let i = 1; i < ell; i++) {\n    const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];\n    b[i] = H(concatBytes(...args));\n  }\n  const pseudo_random_bytes = concatBytes(...b);\n  return pseudo_random_bytes.slice(0, lenInBytes);\n}\n\n/**\n * Produces a uniformly random byte string using an extendable-output function (XOF) H.\n * 1. The collision resistance of H MUST be at least k bits.\n * 2. H MUST be an XOF that has been proved indifferentiable from\n *    a random oracle under a reasonable cryptographic assumption.\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 | RFC 9380 section 5.3.2}.\n * @param msg - Input message.\n * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and\n *   oversize-hashes DST when needed.\n * @param lenInBytes - Output length.\n * @param k - Target security level.\n * @param H - XOF hash function.\n * @returns Uniform byte string.\n * @throws If the message, DST, XOF, or output length is invalid. {@link Error}\n * @example\n * Expand one message into uniform bytes with the XOF construction.\n *\n * ```ts\n * import { expand_message_xof } from '@noble/curves/abstract/hash-to-curve.js';\n * import { shake256 } from '@noble/hashes/sha3.js';\n * const uniform = expand_message_xof(\n *   new TextEncoder().encode('hello noble'),\n *   'DST',\n *   32,\n *   128,\n *   shake256\n * );\n * ```\n */\nexport function expand_message_xof(\n  msg: TArg<Uint8Array>,\n  DST: TArg<AsciiOrBytes>,\n  lenInBytes: number,\n  k: number,\n  H: TArg<CHash>\n): TRet<Uint8Array> {\n  abytes(msg);\n  asafenumber(lenInBytes);\n  DST = normDST(DST);\n  // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n  // RFC 9380 \u00A75.3.3: DST = H(\"H2C-OVERSIZE-DST-\" || a_very_long_DST, ceil(2 * k / 8)).\n  if (DST.length > 255) {\n    const dkLen = Math.ceil((2 * k) / 8);\n    DST = H.create({ dkLen }).update(asciiToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();\n  }\n  if (lenInBytes > 65535 || DST.length > 255)\n    throw new Error('expand_message_xof: invalid lenInBytes');\n  return (\n    H.create({ dkLen: lenInBytes })\n      .update(msg)\n      .update(i2osp(lenInBytes, 2))\n      // 2. DST_prime = DST || I2OSP(len(DST), 1)\n      .update(DST)\n      .update(i2osp(DST.length, 1))\n      .digest()\n  );\n}\n\n/**\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.2 | RFC 9380 section 5.2}.\n * @param msg - Input message bytes.\n * @param count - Number of field elements to derive. Must be `>= 1`.\n * @param options - RFC 9380 options. See {@link H2COpts}. `m` must be `>= 1`.\n * @returns `[u_0, ..., u_(count - 1)]`, a list of field elements.\n * @throws If the expander choice or RFC 9380 options are invalid. {@link Error}\n * @example\n * Hash one message into field elements before mapping it onto a curve.\n *\n * ```ts\n * import { hash_to_field } from '@noble/curves/abstract/hash-to-curve.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const scalars = hash_to_field(new TextEncoder().encode('hello noble'), 2, {\n *   DST: 'DST',\n *   p: 17n,\n *   m: 1,\n *   k: 128,\n *   expand: 'xmd',\n *   hash: sha256,\n * });\n * ```\n */\nexport function hash_to_field(\n  msg: TArg<Uint8Array>,\n  count: number,\n  options: TArg<H2COpts>\n): bigint[][] {\n  validateObject(options, {\n    p: 'bigint',\n    m: 'number',\n    k: 'number',\n    hash: 'function',\n  });\n  const { p, k, m, hash, expand, DST } = options;\n  asafenumber(hash.outputLen, 'valid hash');\n  abytes(msg);\n  asafenumber(count);\n  // RFC 9380 \u00A75.2 defines hash_to_field over a list of one or more field elements and requires\n  // extension degree `m >= 1`; rejecting here avoids degenerate `[]` / `[[]]` helper outputs.\n  if (count < 1) throw new Error('hash_to_field: expected count >= 1');\n  if (m < 1) throw new Error('hash_to_field: expected m >= 1');\n  const log2p = p.toString(2).length;\n  const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above\n  const len_in_bytes = count * m * L;\n  let prb; // pseudo_random_bytes\n  if (expand === 'xmd') {\n    prb = expand_message_xmd(msg, DST, len_in_bytes, hash);\n  } else if (expand === 'xof') {\n    prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);\n  } else if (expand === '_internal_pass') {\n    // for internal tests only\n    prb = msg;\n  } else {\n    throw new Error('expand must be \"xmd\" or \"xof\"');\n  }\n  const u = new Array(count);\n  for (let i = 0; i < count; i++) {\n    const e = new Array(m);\n    for (let j = 0; j < m; j++) {\n      const elm_offset = L * (j + i * m);\n      const tv = prb.subarray(elm_offset, elm_offset + L);\n      e[j] = mod(os2ip(tv), p);\n    }\n    u[i] = e;\n  }\n  return u;\n}\n\ntype XY<T> = (x: T, y: T) => { x: T; y: T };\ntype XYRatio<T> = [T[], T[], T[], T[]]; // xn/xd, yn/yd\n/**\n * @param field - Field implementation.\n * @param map - Isogeny coefficients.\n * @returns Isogeny mapping helper.\n * @example\n * Build one rational isogeny map, then apply it to affine x/y coordinates.\n *\n * ```ts\n * import { isogenyMap } from '@noble/curves/abstract/hash-to-curve.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const iso = isogenyMap(Fp, [[0n, 1n], [1n], [1n], [1n]]);\n * const point = iso(3n, 5n);\n * ```\n */\nexport function isogenyMap<T, F extends IField<T>>(field: F, map: XYRatio<T>): XY<T> {\n  // Make same order as in spec\n  const coeff = map.map((i) => Array.from(i).reverse());\n  return (x: T, y: T) => {\n    const [xn, xd, yn, yd] = coeff.map((val) =>\n      val.reduce((acc, i) => field.add(field.mul(acc, x), i))\n    );\n    // RFC 9380 \u00A76.6.3 / Appendix E: denominator-zero exceptional cases must\n    // return the identity on E.\n    // Shipped Weierstrass consumers encode that affine identity as all-zero\n    // coordinates, so `passZero=true` intentionally collapses zero\n    // denominators to `{ x: 0, y: 0 }`.\n    const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);\n    x = field.mul(xn, xd_inv); // xNum / xDen\n    y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)\n    return { x, y };\n  };\n}\n\n// Keep the shared DST removable when the selected bundle never hashes to scalar.\n// Callers that need protocol-specific scalar domain separation must override this generic default.\n// RFC 9497 \u00A7\u00A74.1-4.5 use this ASCII prefix before appending the ciphersuite context string.\n// Export a string instead of mutable bytes so callers cannot poison default hash-to-scalar behavior\n// by mutating a shared Uint8Array in place.\nexport const _DST_scalar = 'HashToScalar-' as const;\n\n/**\n * Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}.\n * @param Point - Point constructor.\n * @param mapToCurve - Map-to-curve function.\n * @param defaults - Default hash-to-curve options. This object is frozen in place and reused as\n *   the shared defaults bundle for the returned helpers.\n * @returns Hash-to-curve helper namespace.\n * @throws If the map-to-curve callback or default hash-to-curve options are invalid. {@link Error}\n * @example\n * Bundle hash-to-curve, hash-to-scalar, and encode-to-curve helpers for one curve.\n *\n * ```ts\n * import { createHasher } from '@noble/curves/abstract/hash-to-curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hasher = createHasher(p256.Point, () => p256.Point.BASE.toAffine(), {\n *   DST: 'P256_XMD:SHA-256_SSWU_RO_',\n *   encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',\n *   p: p256.Point.Fp.ORDER,\n *   m: 1,\n *   k: 128,\n *   expand: 'xmd',\n *   hash: sha256,\n * });\n * const point = hasher.encodeToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport function createHasher<PC extends PC_ANY>(\n  Point: PC,\n  mapToCurve: MapToCurve<PC_F<PC>>,\n  defaults: TArg<H2COpts & { encodeDST?: AsciiOrBytes }>\n): H2CHasher<PC> {\n  if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined');\n  // `Point` is intentionally not shape-validated eagerly here: point constructors vary across\n  // curve families, so this helper only checks the hooks it can validate cheaply. Misconfigured\n  // suites fail later when hashing first touches Point.fromAffine / Point.ZERO / clearCofactor().\n  const snapshot = (src: TArg<H2COpts & { encodeDST?: AsciiOrBytes }>): TRet<H2CDefaults> =>\n    Object.freeze({\n      ...src,\n      DST: isBytes(src.DST) ? copyBytes(src.DST) : src.DST,\n      ...(src.encodeDST === undefined\n        ? {}\n        : { encodeDST: isBytes(src.encodeDST) ? copyBytes(src.encodeDST) : src.encodeDST }),\n    }) as TRet<H2CDefaults>;\n  // Keep one private defaults snapshot for actual hashing and expose fresh\n  // detached snapshots via the public getter.\n  // Otherwise a caller could mutate `hasher.defaults.DST` in place and poison\n  // the singleton hasher for every other consumer in the same process.\n  const safeDefaults = snapshot(defaults);\n  function map(num: bigint[]): PC_P<PC> {\n    return Point.fromAffine(mapToCurve(num)) as PC_P<PC>;\n  }\n  function clear(initial: PC_P<PC>): PC_P<PC> {\n    const P = initial.clearCofactor();\n    // Keep ZERO as the algebraic cofactor-clearing result here; strict public point-validity\n    // surfaces may still reject it later, but createHasher.clear() itself is not that boundary.\n    if (P.equals(Point.ZERO)) return Point.ZERO as PC_P<PC>;\n    P.assertValidity();\n    return P as PC_P<PC>;\n  }\n\n  return Object.freeze({\n    get defaults() {\n      return snapshot(safeDefaults);\n    },\n    Point,\n\n    hashToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC> {\n      const opts = Object.assign({}, safeDefaults, options);\n      const u = hash_to_field(msg, 2, opts);\n      const u0 = map(u[0]);\n      const u1 = map(u[1]);\n      return clear(u0.add(u1) as PC_P<PC>);\n    },\n    encodeToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC> {\n      const optsDst = safeDefaults.encodeDST ? { DST: safeDefaults.encodeDST } : {};\n      const opts = Object.assign({}, safeDefaults, optsDst, options);\n      const u = hash_to_field(msg, 1, opts);\n      const u0 = map(u[0]);\n      return clear(u0);\n    },\n    /** See {@link H2CHasher} */\n    mapToCurve(scalars: bigint | bigint[]): PC_P<PC> {\n      // Curves with m=1 accept only single scalar\n      if (safeDefaults.m === 1) {\n        if (typeof scalars !== 'bigint') throw new Error('expected bigint (m=1)');\n        return clear(map([scalars]));\n      }\n      if (!Array.isArray(scalars)) throw new Error('expected array of bigints');\n      for (const i of scalars)\n        if (typeof i !== 'bigint') throw new Error('expected array of bigints');\n      return clear(map(scalars));\n    },\n\n    // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393\n    // RFC 9380, draft-irtf-cfrg-bbs-signatures-08. Default scalar DST is the shared generic\n    // `HashToScalar-` prefix above unless the caller overrides it per invocation.\n    hashToScalar(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): bigint {\n      // @ts-ignore\n      const N = Point.Fn.ORDER;\n      const opts = Object.assign({}, safeDefaults, { p: N, m: 1, DST: _DST_scalar }, options);\n      return hash_to_field(msg, 1, opts)[0][0];\n    },\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 * Canonicalizes a given object according to RFC 8785 (https://tools.ietf.org/html/rfc8785),\n * which describes JSON Canonicalization Scheme (JCS). This function sorts the keys of the\n * object and its nested objects alphabetically and then returns a stringified version of it.\n * This method handles nested objects, array values, and null values appropriately.\n *\n * @param obj - The object to canonicalize.\n * @returns The stringified version of the input object with its keys sorted alphabetically\n * per RFC 8785.\n */\nexport function canonicalize(obj: { [key: string]: any }): string {\n  /**\n   * Recursively sorts the keys of an object.\n   *\n   * @param obj - The object whose keys are to be sorted.\n   * @returns A new object with sorted keys.\n   */\n  const sortObjKeys = (obj: { [key: string]: any }): { [key: string]: any } => {\n    if (obj !== null && typeof obj === 'object' && !Array.isArray(obj)) {\n      const sortedKeys = Object.keys(obj).sort((a, b) => a.localeCompare(b));\n      const sortedObj: { [key: string]: any } = {};\n      for (const key of sortedKeys) {\n        // Recursively sort keys of nested objects.\n        sortedObj[key] = sortObjKeys(obj[key]);\n      }\n      return sortedObj;\n    }\n    return obj;\n  };\n\n  // Stringify and return the final sorted object.\n  const sortedObj = sortObjKeys(obj);\n  return JSON.stringify(sortedObj);\n}", "import { sha256 } from '@noble/hashes/sha2.js';\n\n/**\n * The `Sha256` class provides an interface for generating SHA-256 hash digests.\n *\n * This class utilizes the '@noble/hashes/sha2.js' function to generate hash digests\n * of the provided data. The SHA-256 algorithm is widely used in cryptographic\n * applications to produce a fixed-size 256-bit (32-byte) hash.\n *\n * The methods of this class are asynchronous and return Promises. They use the Uint8Array\n * type for input data and the resulting digest, ensuring a consistent interface\n * for binary data processing.\n *\n * @example\n * ```ts\n * const data = new Uint8Array([...]);\n * const hash = await Sha256.digest({ data });\n * ```\n */\nexport class Sha256 {\n  /**\n   * Generates a SHA-256 hash digest for the given data.\n   *\n   * @remarks\n   * This method produces a hash digest using the SHA-256 algorithm. The resultant digest\n   * is deterministic, meaning the same data will always produce the same hash, but\n   * is computationally infeasible to regenerate the original data from the hash.\n   *\n   * @example\n   * ```ts\n   * const data = new Uint8Array([...]);\n   * const hash = await Sha256.digest({ data });\n   * ```\n   *\n   * @param params - The parameters for the hashing operation.\n   * @param params.data - The data to hash, represented as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the SHA-256 hash digest of the provided data as a Uint8Array.\n   */\n  public static async digest({ data }: {\n    data: Uint8Array;\n  }): Promise<Uint8Array> {\n    const hash = sha256(data);\n\n    return hash;\n  }\n}", "import { Convert, removeUndefinedProperties } from '@enbox/common';\n\nimport { canonicalize } from './utils.js';\nimport { Sha256 } from '../primitives/sha256.js';\n\n/**\n * Constant defining the prefix for JSON Web Keys (JWK) key URIs in this library.\n *\n * The prefix 'urn:jwk:' makes it explicit that a string represents a JWK, referenced by a\n * {@link https://datatracker.ietf.org/doc/html/rfc3986 | URI} (Uniform Resource Identifier),\n * which ensures consistent key referencing across all Web5 Key Management System (KMS)\n * implementations.\n *\n * These key URIs take the form `urn:jwk:<JWK thumbprint>`, where the\n * {@link https://datatracker.ietf.org/doc/html/rfc7638 | JWK thumbprint}, derived from the JWK, is\n * unique to the key's material, unaffected by the order or optional properties in the JWK.\n */\nexport const KEY_URI_PREFIX_JWK = 'urn:jwk:';\n\n/**\n * JSON Web Key Operations\n *\n * The \"key_ops\" (key operations) parameter identifies the operation(s)\n * for which the key is intended to be used.  The \"key_ops\" parameter is\n * intended for use cases in which public, private, or symmetric keys\n * may be present.\n *\n * Its value is an array of key operation values.  Values defined by\n * {@link https://www.rfc-editor.org/rfc/rfc7517.html#section-4.3 | RFC 7517 Section 4.3} are:\n *\n * - \"decrypt\"    : Decrypt content and validate decryption, if applicable\n * - \"deriveBits\" : Derive bits not to be used as a key\n * - \"deriveKey\"  : Derive key\n * - \"encrypt\"    : Encrypt content\n * - \"sign\"       : Compute digital signature or MAC\n * - \"unwrapKey\"  : Decrypt key and validate decryption, if applicable\n * - \"verify\"     : Verify digital signature or MAC\n * - \"wrapKey\"    : Encrypt key\n *\n * Other values MAY be used.  The key operation values are case-\n * sensitive strings.  Duplicate key operation values MUST NOT be\n * present in the array.  Use of the \"key_ops\" member is OPTIONAL,\n * unless the application requires its presence.\n *\n * The \"use\" and \"key_ops\" JWK members SHOULD NOT be used together;\n * however, if both are used, the information they convey MUST be\n * consistent.  Applications should specify which of these members they\n * use, if either is to be used by the application.\n */\nexport type JwkOperation = 'encrypt' | 'decrypt' | 'sign' | 'verify' | 'deriveKey' | 'deriveBits' | 'wrapKey' | 'unwrapKey';\n\n/**\n * JSON Web Key Use\n *\n * The \"use\" (public key use) parameter identifies the intended use of\n * the public key.  The \"use\" parameter is employed to indicate whether\n * a public key is used for encrypting data or verifying the signature\n * on data.\n *\n * Values defined by {@link https://datatracker.ietf.org/doc/html/rfc7517#section-4.2 | RFC 7517 Section 4.2} are:\n *\n * - \"sig\" (signature)\n * - \"enc\" (encryption)\n *\n * Other values MAY be used.  The \"use\" value is a case-sensitive\n * string.  Use of the \"use\" member is OPTIONAL, unless the application\n * requires its presence.\n *\n * The \"use\" and \"key_ops\" JWK members SHOULD NOT be used together;\n * however, if both are used, the information they convey MUST be\n * consistent.  Applications should specify which of these members they\n * use, if either is to be used by the application.\n *\n * When a key is used to wrap another key and a public key use\n * designation for the first key is desired, the \"enc\" (encryption) key\n * use value is used, since key wrapping is a kind of encryption.  The\n * \"enc\" value is also to be used for public keys used for key agreement\n * operations.\n */\nexport type JwkUse = 'sig' | 'enc' | (string & {});\n\n/**\n * JSON Web Key Types\n */\nexport type JwkType =\n  /**\n   * Elliptic Curve\n   * Used with Elliptic Curve Digital Signature Algorithm (ECDSA) and Elliptic\n   * Curve Diffie-Hellman (ECDH), including secp256k1, P-256, P-384, and P-521.\n   */\n  | 'EC'\n  /**\n   * RSA\n   * Widely used for encryption and digital signatures. RSA keys are used in\n   * various algorithms like RS256, RS384, RS512, etc.\n   */\n  | 'RSA'\n  /**\n   * Octet sequence\n   * Used with symmetric signing (e.g., HMAC HS256, HS512, etc.) and\n   * symmetric encryption (e.g., A256CBC-HS512, A256GCM, etc.) algorithms.\n   */\n  | 'oct'\n  /**\n   * Octet string key pairs (OKP)\n   * A type of public key that is used with algorithms such as EdDSA (Ed25519 and\n   * Ed448 curves) and ECDH (X25519 and X448 curves).\n   */\n  | 'OKP';\n\n/**\n * JSON Web Key Elliptic Curve\n */\nexport type JwkNamedCurves =\n  // P-256 Curve\n  | 'P-256'\n  // P-384 Curve\n  | 'P-384'\n  // P-521 Curve\n  | 'P-521'\n  // Ed25519 signature algorithm key pairs\n  | 'Ed25519'\n  // Ed448 signature algorithm key pairs\n  | 'Ed448'\n  // X25519 function key pairs\n  | 'X25519'\n  // X448 function key pairs\n  | 'X448'\n  // SECG secp256k1 curve\n  | 'secp256k1';\n\n/**\n * JSON Web Key Parameters\n */\n\n/** Parameters used with any \"kty\" (key type) value. */\nexport type JwkParamsAnyKeyType = {\n  /** JWK Algorithm Parameter. The algorithm intended for use with the key. */\n  alg?: string;\n  /** JWK Extractable Parameter */\n  ext?: 'true' | 'false';\n  /** JWK Key Operations Parameter */\n  key_ops?: JwkOperation[];\n  /** JWK Key ID Parameter */\n  kid?: string;\n  /** JWK Key Type Parameter */\n  kty: JwkType;\n  /** JWK Public Key Use Parameter */\n  use?: JwkUse;\n  /** JWK X.509 Certificate Chain Parameter */\n  x5c?: string;\n  /** JWK X.509 Certificate SHA-1 Thumbprint Parameter */\n  x5t?: string;\n  /** JWK X.509 Certificate SHA-256 Thumbprint Parameter */\n  'x5t#S256'?: string;\n  /** JWK X.509 URL Parameter */\n  x5u?: string;\n};\n\n/** Parameters used with \"EC\" (elliptic curve) public keys. */\nexport type JwkParamsEcPublic = Omit<JwkParamsAnyKeyType, 'alg' | 'kty'> & {\n  /**\n   * The algorithm intended for use with the key.\n   * ES256  : ECDSA using P-256 and SHA-256\n   * ES256K : ECDSA using secp256k1 curve and SHA-256\n   * ES384  : ECDSA using P-384 and SHA-384\n   * ES512  : ECDSA using P-521 and SHA-512\n   */\n  alg?: 'ES256' | 'ES256K' | 'ES384' | 'ES512';\n\n  /**\n   * Elliptic Curve key pair.\n   */\n  kty: 'EC';\n\n  /**\n   * The cryptographic curve used with the key.\n   * MUST be present for all EC public keys.\n   */\n  crv: 'secp256k1' | 'P-256' | 'P-384' | 'P-521';\n\n  /**\n   * The x-coordinate for the Elliptic Curve point.\n   * Represented as the base64url encoding of the octet string\n   * representation of the coordinate.\n   * MUST be present for all EC public keys\n   */\n  x: string;\n\n  /**\n   * The y-coordinate for the Elliptic Curve point.\n   * Represented as the base64url encoding of the octet string\n   * representation of the coordinate.\n   * MUST be present only for secp256k1 public keys.\n   */\n  y?: string;\n};\n\n/** Parameters used with \"EC\" (elliptic curve) private keys. */\nexport type JwkParamsEcPrivate = JwkParamsEcPublic & {\n  /**\n   * The d-coordinate for the Elliptic Curve point.\n   * Represented as the base64url encoding of the octet string\n   * representation of the coordinate.\n   * MUST be present for all EC private keys.\n   */\n  d: string;\n};\n\n/** Parameters used with \"OKP\" (octet key pair) public keys. */\nexport type JwkParamsOkpPublic =\n  Omit<JwkParamsAnyKeyType, 'kty' | 'alg' | 'crv'> &\n  Pick<JwkParamsEcPublic, 'x'> & {\n  /**\n   * The algorithm intended for use with the key.\n   * EdDSA: Edwards Curve Digital Signature Algorithm\n   */\n  alg?: 'EdDSA';\n\n  /**\n   * The cryptographic curve used with the key.\n   * MUST be present for all OKP public keys.\n   */\n  crv: 'Ed25519' | 'Ed448' | 'X25519' | 'X448';\n\n  /**\n   * Key type\n   * OKP (Octet Key Pair) is defined for public key algorithms that use octet\n   * strings as private and public keys.\n   */\n  kty: 'OKP';\n};\n\n/** Parameters used with \"OKP\" (octet key pair) private keys. */\nexport type JwkParamsOkpPrivate = JwkParamsOkpPublic & {\n  /**\n   * The d-coordinate for the Edwards Curve point.\n   * Represented as the base64url encoding of the octet string\n   * representation of the coordinate.\n   * MUST be present for all EC private keys.\n   */\n  d: string;\n};\n\n/** Parameters used with \"oct\" (octet sequence) private keys. */\nexport type JwkParamsOctPrivate = Omit<JwkParamsAnyKeyType, 'alg' | 'kty'> & {\n  /**\n   * The algorithm intended for use with the key.\n   * Used with symmetric signing (e.g., HMAC HS256, etc.) and\n   * symmetric encryption (e.g., A256GCM, etc.) algorithms.\n   */\n  alg?:\n    // AES CBC using 128-bit key\n    | 'A128CBC'\n    // AES CBC using 192-bit key\n    | 'A192CBC'\n    // AES CBC using 256-bit key\n    | 'A256CBC'\n    // AES CTR using 128-bit key\n    | 'A128CTR'\n    // AES CTR using 192-bit key\n    | 'A192CTR'\n    // AES CTR using 256-bit key\n    | 'A256CTR'\n    // AES GCM using a 128-bit key\n    | 'A128GCM'\n    // AES GCM using a 192-bit key\n    | 'A192GCM'\n    // AES GCM using a 256-bit key\n    | 'A256GCM'\n    // HMAC using SHA-256\n    | 'HS256'\n    // HMAC using SHA-384\n    | 'HS384'\n    // HMAC using SHA-512\n    | 'HS512'\n\n  /**\n   * The \"k\" (key value) parameter contains the value of the symmetric\n   * (or other single-valued) key.  It is represented as the base64url\n   * encoding of the octet sequence containing the key value.\n   */\n  k: string;\n\n  /**\n   * Key type\n   * oct (Octet Sequence) is defined for symmetric encryption and\n   * symmetric signature algorithms.\n   */\n  kty: 'oct';\n};\n\n/** Parameters Used with \"RSA\" public keys. */\nexport type JwkParamsRsaPublic = Omit<JwkParamsAnyKeyType, 'kty'> & {\n  /** Public exponent for RSA */\n  e: string;\n\n  /**\n   * Key type\n   * RSA is widely used for encryption and digital signatures.\n   */\n  kty: 'RSA';\n\n  /** Modulus for RSA */\n  n: string;\n};\n\n/** Parameters used with \"RSA\" private keys. */\nexport type JwkParamsRsaPrivate = JwkParamsRsaPublic & {\n  /** Private exponent for RSA */\n  d: string;\n  /** First prime factor for RSA */\n  p?: string;\n  /** Second prime factor for RSA */\n  q?: string;\n  /** First factor's CRT exponent for RSA */\n  dp?: string;\n  /** Second factor's CRT exponent for RSA */\n  dq?: string;\n  /** First CRT coefficient for RSA */\n  qi?: string;\n  /** Other primes information (optional in RFC 7518) */\n  oth?: {\n    /** Other primes' factor */\n    r: string;\n    /** Other primes' CRT exponent */\n    d: string;\n    /** Other primes' CRT coefficient */\n    t: string;\n  }[];\n};\n\n/** Parameters used with public keys in JWK format. */\nexport type PublicKeyJwk = JwkParamsEcPublic | JwkParamsOkpPublic | JwkParamsRsaPublic;\n\n/** Parameters used with private keys in JWK format. */\nexport type PrivateKeyJwk = JwkParamsEcPrivate | JwkParamsOkpPrivate | JwkParamsOctPrivate | JwkParamsRsaPrivate;\n\n/**\n * JSON Web Key ({@link https://datatracker.ietf.org/doc/html/rfc7517 | JWK}).\n * \"RSA\", \"EC\", \"OKP\", and \"oct\" key types are supported.\n */\nexport interface Jwk {\n  // Common properties that apply to all key types.\n\n  /** JWK Algorithm Parameter. The algorithm intended for use with the key. */\n  alg?: string;\n  /** JWK Extractable Parameter */\n  ext?: 'true' | 'false';\n  /** JWK Key Operations Parameter */\n  key_ops?: JwkOperation[];\n  /** JWK Key ID Parameter */\n  kid?: string;\n  /** JWK Key Type Parameter */\n  kty: JwkType;\n  /** JWK Public Key Use Parameter */\n  use?: JwkUse;\n  /** JWK X.509 Certificate Chain Parameter */\n  x5c?: string;\n  /** JWK X.509 Certificate SHA-1 Thumbprint Parameter */\n  x5t?: string;\n  /** JWK X.509 Certificate SHA-256 Thumbprint Parameter */\n  'x5t#S256'?: string;\n  /** JWK X.509 URL Parameter */\n  x5u?: string;\n\n  // Elliptic Curve (EC or OKP) public key properties.\n\n  /** The cryptographic curve used with the key. */\n  crv?: string;\n  /** The x-coordinate for the Elliptic Curve point. */\n  x?: string;\n  /** The y-coordinate for the Elliptic Curve point. */\n  y?: string;\n\n  // Symmetric key properties.\n\n  /** The \"k\" (key value) parameter contains the value of the symmetric (or other single-valued) key. */\n  k?: string;\n\n  // RSA public key properties.\n\n  /** Public exponent for RSA */\n  e?: string;\n  /** Modulus for RSA */\n  n?: string;\n  /** First prime factor for RSA */\n  p?: string;\n  /** Second prime factor for RSA */\n  q?: string;\n  /** First factor's CRT exponent for RSA */\n  dp?: string;\n  /** Second factor's CRT exponent for RSA */\n  dq?: string;\n  /** First CRT coefficient for RSA */\n  qi?: string;\n  /** Other primes information (optional in RFC 7518) */\n  oth?: {\n    /** Other primes' factor */\n    r: string;\n    /** Other primes' CRT exponent */\n    d: string;\n    /** Other primes' CRT coefficient */\n    t: string;\n  }[];\n\n  // Elliptic Curve and RSA private key properties.\n\n  /** Private key component for EC, OKP, or RSA keys. */\n  d?: string;\n\n  // Additional public or private properties.\n  [key: string]: unknown;\n}\n\n/**\n * JSON Web Key Set ({@link https://datatracker.ietf.org/doc/html/rfc7517 | JWK Set})\n *\n * @remarks\n * A JWK Set is a JSON object that represents a set of JWKs. The JSON object MUST have a \"keys\"\n * member, with its value being an array of JWKs.\n *\n * Additional members can be present in the JWK Set but member names MUST be unique. If not\n * understood by implementations encountering them, they MUST be ignored. Parameters for\n * representing additional properties of JWK Sets should either be registered in the IANA\n * \"JSON Web Key Set Parameters\" registry or be a value that contains a Collision-Resistant Name.\n */\nexport interface JwkSet {\n  /** Array of JWKs */\n  keys: Jwk[]\n}\n\n/**\n * Computes the thumbprint of a JSON Web Key (JWK) using the method\n * specified in RFC 7638. This function accepts RSA, EC, OKP, and oct keys\n * and returns the thumbprint as a base64url encoded SHA-256 hash of the\n * JWK's required members, serialized and sorted lexicographically.\n *\n * Purpose:\n * - Uniquely Identifying Keys: The thumbprint allows the unique\n *   identification of a specific JWK within a set of JWKs. It provides a\n *   deterministic way to generate a value that can be used as a key\n *   identifier (kid) or to match a specific key.\n *\n * - Simplifying Key Management: In systems where multiple keys are used,\n *   managing and identifying individual keys can become complex. The\n *   thumbprint method simplifies this by creating a standardized, unique\n *   identifier for each key.\n *\n * - Enabling Interoperability: By standardizing the method to compute a\n *   thumbprint, different systems can compute the same thumbprint value for\n *   a given JWK. This enables interoperability among systems that use JWKs.\n *\n * - Secure Comparison: The thumbprint provides a way to securely compare\n *   JWKs to determine if they are equivalent.\n *\n * @example\n * ```ts\n * const jwk: PublicKeyJwk = {\n *   'kty': 'EC',\n *   'crv': 'secp256k1',\n *   'x': '61iPYuGefxotzBdQZtDvv6cWHZmXrTTscY-u7Y2pFZc',\n *   'y': '88nPCVLfrAY9i-wg5ORcwVbHWC_tbeAd1JE2e0co0lU'\n * };\n *\n * const thumbprint = jwkThumbprint(jwk);\n * console.log(`JWK thumbprint: ${thumbprint}`);\n * ```\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc7638 | RFC7638} for\n * the specification of JWK thumbprint computation.\n *\n * @param jwk - The JSON Web Key for which the thumbprint will be computed.\n *              This must be an RSA, EC, OKP, or oct key.\n * @returns The thumbprint as a base64url encoded string.\n * @throws Throws an `Error` if the provided key type is unsupported.\n */\nexport async function computeJwkThumbprint({ jwk }: {\n  jwk: Jwk\n}): Promise<string> {\n  /** Step 1 - Normalization: The JWK is normalized to include only specific\n   * members and in lexicographic order.\n   */\n  const keyType = jwk.kty;\n  let normalizedJwk: Jwk;\n  if (keyType === 'EC') {\n    normalizedJwk = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };\n  } else if (keyType === 'oct') {\n    normalizedJwk = { k: jwk.k, kty: jwk.kty };\n  } else if (keyType === 'OKP') {\n    normalizedJwk = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };\n  } else if (keyType === 'RSA') {\n    normalizedJwk = { e: jwk.e, kty: jwk.kty, n: jwk.n };\n  } else {\n    throw new Error(`Unsupported key type: ${keyType}`);\n  }\n  removeUndefinedProperties(normalizedJwk);\n\n  /** Step 2 - Serialization: The normalized JWK is serialized to a UTF-8\n   * representation of its JSON encoding. */\n  const serializedJwk = canonicalize(normalizedJwk);\n\n  /** Step 3 - Digest Calculation: A cryptographic hash function\n   * (SHA-256 is recommended) is applied to the serialized JWK,\n   * resulting in the thumbprint. */\n  const utf8Bytes = Convert.string(serializedJwk).toUint8Array();\n  const digest = await Sha256.digest({ data: utf8Bytes });\n\n  // Encode as Base64Url.\n  const thumbprint = Convert.uint8Array(digest).toBase64Url();\n\n  return thumbprint;\n}\n\n/**\n * Checks if the provided object is a valid elliptic curve private key in JWK format.\n *\n * @param obj - The object to check.\n * @returns True if the object is a valid EC private JWK; otherwise, false.\n */\nexport function isEcPrivateJwk(obj: unknown): obj is JwkParamsEcPrivate {\n  if (!obj || typeof obj !== 'object') {return false;}\n  if (!('kty' in obj && 'crv' in obj && 'x' in obj && 'd' in obj)) {return false;}\n  if (obj.kty !== 'EC') {return false;}\n  if (typeof obj.d !== 'string') {return false;}\n  if (typeof obj.x !== 'string') {return false;}\n  return true;\n}\n\n/**\n * Checks if the provided object is a valid elliptic curve public key in JWK format.\n *\n * @param obj - The object to check.\n * @returns True if the object is a valid EC public JWK; otherwise, false.\n */\nexport function isEcPublicJwk(obj: unknown): obj is JwkParamsEcPublic {\n  if (!obj || typeof obj !== 'object') {return false;}\n  if (!('kty' in obj && 'crv' in obj && 'x' in obj)) {return false;}\n  if ('d' in obj) {return false;}\n  if (obj.kty !== 'EC') {return false;}\n  if (typeof obj.x !== 'string') {return false;}\n  return true;\n}\n\n/**\n * Checks if the provided object is a valid octet sequence (symmetric key) in JWK format.\n *\n * @param obj - The object to check.\n * @returns True if the object is a valid oct private JWK; otherwise, false.\n */\nexport function isOctPrivateJwk(obj: unknown): obj is JwkParamsOctPrivate {\n  if (!obj || typeof obj !== 'object') {return false;}\n  if (!('kty' in obj && 'k' in obj)) {return false;}\n  if (obj.kty !== 'oct') {return false;}\n  if (typeof obj.k !== 'string') {return false;}\n  return true;\n}\n\n/**\n * Checks if the provided object is a valid octet key pair private key in JWK format.\n *\n * @param obj - The object to check.\n * @returns True if the object is a valid OKP private JWK; otherwise, false.\n */\nexport function isOkpPrivateJwk(obj: unknown): obj is JwkParamsOkpPrivate {\n  if (!obj || typeof obj !== 'object') {return false;}\n  if (!('kty' in obj && 'crv' in obj && 'x' in obj && 'd' in obj)) {return false;}\n  if (obj.kty !== 'OKP') {return false;}\n  if (typeof obj.d !== 'string') {return false;}\n  if (typeof obj.x !== 'string') {return false;}\n  return true;\n}\n\n/**\n * Checks if the provided object is a valid octet key pair public key in JWK format.\n *\n * @param obj - The object to check.\n * @returns True if the object is a valid OKP public JWK; otherwise, false.\n */\nexport function isOkpPublicJwk(obj: unknown): obj is JwkParamsOkpPublic {\n  if (!obj || typeof obj !== 'object') {return false;}\n  if ('d' in obj) {return false;}\n  if (!('kty' in obj && 'crv' in obj && 'x' in obj)) {return false;}\n  if (obj.kty !== 'OKP') {return false;}\n  if (typeof obj.x !== 'string') {return false;}\n  return true;\n}\n\n/**\n * Checks if the provided object is a valid private key in JWK format of any supported type.\n *\n * @param obj - The object to check.\n * @returns True if the object is a valid private JWK; otherwise, false.\n */\nexport function isPrivateJwk(obj: unknown): obj is PrivateKeyJwk {\n  if (!obj || typeof obj !== 'object') {return false;}\n\n  const kty = (obj as { kty: string }).kty;\n\n  switch (kty) {\n    case 'EC':\n    case 'OKP':\n    case 'RSA':\n      return 'd' in obj;\n    case 'oct':\n      return 'k' in obj;\n    default:\n      return false;\n  }\n}\n\n/**\n * Checks if the provided object is a valid public key in JWK format of any supported type.\n *\n * @param obj - The object to check.\n * @returns True if the object is a valid public JWK; otherwise, false.\n */\nexport function isPublicJwk(obj: unknown): obj is PublicKeyJwk {\n  if (!obj || typeof obj !== 'object') {return false;}\n\n  const kty = (obj as { kty: string }).kty;\n\n  switch (kty) {\n    case 'EC':\n    case 'OKP':\n      return 'x' in obj && !('d' in obj);\n    case 'RSA':\n      return 'n' in obj && 'e' in obj && !('d' in obj);\n    default:\n      return false;\n  }\n}", "import type { AffinePoint } from '@noble/curves/abstract/weierstrass.js';\n\nimport { Convert } from '@enbox/common';\nimport { numberToBytesBE } from '@noble/curves/utils.js';\nimport { secp256k1 } from '@noble/curves/secp256k1.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nimport type { Jwk } from '../jose/jwk.js';\nimport type { ComputePublicKeyParams, GetPublicKeyParams, SignParams, VerifyParams } from '../types/params-direct.js';\n\nimport { computeJwkThumbprint, isEcPrivateJwk, isEcPublicJwk } from '../jose/jwk.js';\n\n/**\n * The `Secp256k1` class provides a comprehensive suite of utilities for working with\n * the secp256k1 elliptic curve, commonly used in blockchain and cryptographic applications.\n * This class includes methods for key generation, conversion, signing, verification, and\n * Elliptic Curve Diffie-Hellman (ECDH) key agreement.\n *\n * The class supports conversions between raw byte formats and JSON Web Key (JWK) formats. It\n * adheres to RFC6979 for ECDSA signing and verification and RFC6090 for ECDH.\n *\n * Key Features:\n * - Key Generation: Generate secp256k1 private keys in JWK format.\n * - Key Conversion: Transform keys between raw byte arrays and JWK formats.\n * - Public Key Derivation: Derive public keys from private keys.\n * - ECDH Shared Secret Computation: Securely derive shared secrets using private and public keys.\n * - ECDSA Signing and Verification: Sign data and verify signatures with secp256k1 keys.\n * - Key Validation: Validate the mathematical correctness of secp256k1 keys.\n *\n * The methods in this class are asynchronous, returning Promises to accommodate various\n * JavaScript environments, and use `Uint8Array` for binary data handling.\n *\n * @example\n * ```ts\n * // Key Generation\n * const privateKey = await Secp256k1.generateKey();\n *\n * // Public Key Derivation\n * const publicKey = await Secp256k1.computePublicKey({ key: privateKey });\n * console.log(publicKey === await Secp256k1.getPublicKey({ key: privateKey })); // Output: true\n *\n * // ECDH Shared Secret Computation\n * const sharedSecret = await Secp256k1.sharedSecret({\n *   privateKeyA: privateKey,\n *   publicKeyB: anotherPublicKey\n * });\n *\n * // ECDSA Signing\n * const signature = await Secp256k1.sign({\n *   key: privateKey,\n *   data: new TextEncoder().encode('Message')\n * });\n *\n * // ECDSA Signature Verification\n * const isValid = await Secp256k1.verify({\n *   key: publicKey,\n *   signature: signature,\n *   data: new TextEncoder().encode('Message')\n * });\n *\n * // Key Conversion\n * const publicKeyBytes = await Secp256k1.publicKeyToBytes({ publicKey });\n * const privateKeyBytes = await Secp256k1.privateKeyToBytes({ privateKey });\n * const compressedPublicKey = await Secp256k1.compressPublicKey({ publicKeyBytes });\n * const uncompressedPublicKey = await Secp256k1.decompressPublicKey({ publicKeyBytes });\n *\n * // Key Validation\n * const isPrivateKeyValid = await Secp256k1.validatePrivateKey({ privateKeyBytes });\n * const isPublicKeyValid = await Secp256k1.validatePublicKey({ publicKeyBytes });\n * ```\n */\nexport class Secp256k1 {\n  /**\n   * Adjusts an ECDSA signature to a normalized, low-S form.\n   *\n   * @remarks\n   * All ECDSA signatures, regardless of the curve, consist of two components, `r` and `s`, both of\n   * which are integers. The curve's order (the total number of points on the curve) is denoted by\n   * `n`. In a valid ECDSA signature, both `r` and `s` must be in the range [1, n-1]. However, due\n   * to the mathematical properties of ECDSA, if `(r, s)` is a valid signature, then `(r, n - s)` is\n   * also a valid signature for the same message and public key. In other words, for every\n   * signature, there's a \"mirror\" signature that's equally valid. For these elliptic curves:\n   *\n   * - Low S Signature: A signature where the `s` component is in the lower half of the range,\n   *                    specifically less than or equal to `n/2`.\n   *\n   * - High S Signature: This is where the `s` component is in the upper half of the range, greater\n   *                     than `n/2`.\n   *\n   * The practical implication is that a third-party can forge a second valid signature for the same\n   * message by negating the `s` component of the original signature, without any knowledge of the\n   * private key. This is known as a \"signature malleability\" attack.\n   *\n   * This type of forgery is not a problem in all systems, but it can be an issue in systems that\n   * rely on digital signature uniqueness to ensure transaction integrity. For example, in Bitcoin,\n   * transaction malleability is an issue because it allows for the modification of transaction\n   * identifiers (and potentially, transactions themselves) after they're signed but before they're\n   * confirmed in a block. By enforcing low `s` values, the Bitcoin network reduces the likelihood of\n   * this occurring, making the system more secure and predictable.\n   *\n   * For this reason, it's common practice to normalize ECDSA signatures to a low-S form. This\n   * form is considered standard and preferable in some systems and is known as the \"normalized\"\n   * form of the signature.\n   *\n   * This method takes a signature, and if it's high-S, returns the normalized low-S form. If the\n   * signature is already low-S, it's returned unmodified. It's important to note that this\n   * method does not change the validity of the signature but makes it compliant with systems that\n   * enforce low-S signatures.\n   *\n   * @example\n   * ```ts\n   * const signature = new Uint8Array([...]); // Your ECDSA signature\n   * const adjustedSignature = await Secp256k1.adjustSignatureToLowS({ signature });\n   * // Now 'adjustedSignature' is in the low-S form.\n   * ```\n   *\n   * @param params - The parameters for the signature adjustment.\n   * @param params.signature - The ECDSA signature as a `Uint8Array`.\n   *\n   * @returns A Promise that resolves to the adjusted signature in low-S form as a `Uint8Array`.\n   */\n  public static async adjustSignatureToLowS({ signature }: {\n    signature: Uint8Array;\n  }): Promise<Uint8Array> {\n    // Convert the signature to a `secp256k1.Signature` object.\n    const signatureObject = secp256k1.Signature.fromBytes(signature, 'compact');\n\n    if (signatureObject.hasHighS()) {\n      // Adjust the signature to low-S format if it's high-S.\n      const adjustedSignatureObject = new secp256k1.Signature(\n        signatureObject.r,\n        secp256k1.Point.CURVE().n - signatureObject.s\n      );\n\n      // Convert the adjusted signature object back to a byte array.\n      const adjustedSignature = adjustedSignatureObject.toBytes('compact');\n\n      return adjustedSignature;\n\n    } else {\n      // Return the unmodified signature if it is already in low-S format.\n      return signature;\n    }\n  }\n\n  /**\n   * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method takes a private key represented as a byte array (Uint8Array) and\n   * converts it into a JWK object. The conversion involves extracting the\n   * elliptic curve point (x and y coordinates) from the private key and encoding\n   * them into base64url format, alongside other JWK parameters.\n   *\n   * The resulting JWK object includes the following properties:\n   * - `kty`: Key Type, set to 'EC' for Elliptic Curve.\n   * - `crv`: Curve Name, set to 'secp256k1'.\n   * - `d`: The private key component, base64url-encoded.\n   * - `x`: The x-coordinate of the public key point, base64url-encoded.\n   * - `y`: The y-coordinate of the public key point, base64url-encoded.\n   *\n   * This method is useful for converting raw public keys into a standardized\n   * JSON format, facilitating their use in cryptographic operations and making\n   * them easy to share and store.\n   *\n   * @example\n   * ```ts\n   * const privateKeyBytes = new Uint8Array([...]); // Replace with actual private key bytes\n   * const privateKey = await Secp256k1.bytesToPrivateKey({ privateKeyBytes });\n   * ```\n   *\n   * @param params - The parameters for the private key conversion.\n   * @param params.privateKeyBytes - The raw private key as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the private key in JWK format.\n   */\n  public static async bytesToPrivateKey({ privateKeyBytes }: {\n    privateKeyBytes: Uint8Array;\n  }): Promise<Jwk> {\n    // Get the elliptic curve point (x and y coordinates) for the provided private key.\n    const point = await Secp256k1.getCurvePoint({ keyBytes: privateKeyBytes });\n\n    // Construct the private key in JWK format.\n    const privateKey: Jwk = {\n      kty : 'EC',\n      crv : 'secp256k1',\n      d   : Convert.uint8Array(privateKeyBytes).toBase64Url(),\n      x   : Convert.uint8Array(point.x).toBase64Url(),\n      y   : Convert.uint8Array(point.y).toBase64Url()\n    };\n\n    // Compute the JWK thumbprint and set as the key ID.\n    privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n    return privateKey;\n  }\n\n  /**\n   * Converts a raw public key in bytes to its corresponding JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method accepts a public key in a byte array (Uint8Array) format and\n   * transforms it to a JWK object. It involves decoding the elliptic curve point\n   * (x and y coordinates) from the raw public key bytes and encoding them into\n   * base64url format, along with setting appropriate JWK parameters.\n   *\n   * The resulting JWK object includes the following properties:\n   * - `kty`: Key Type, set to 'EC' for Elliptic Curve.\n   * - `crv`: Curve Name, set to 'secp256k1'.\n   * - `x`: The x-coordinate of the public key point, base64url-encoded.\n   * - `y`: The y-coordinate of the public key point, base64url-encoded.\n   *\n   * This method is useful for converting raw public keys into a standardized\n   * JSON format, facilitating their use in cryptographic operations and making\n   * them easy to share and store.\n   *\n   * @example\n   * ```ts\n   * const publicKeyBytes = new Uint8Array([...]); // Replace with actual public key bytes\n   * const publicKey = await Secp256k1.bytesToPublicKey({ publicKeyBytes });\n   * ```\n   *\n   * @param params - The parameters for the public key conversion.\n   * @param params.publicKeyBytes - The raw public key as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the public key in JWK format.\n   */\n  public static async bytesToPublicKey({ publicKeyBytes }: {\n    publicKeyBytes: Uint8Array;\n  }): Promise<Jwk> {\n    // Get the elliptic curve point (x and y coordinates) for the provided public key.\n    const point = await Secp256k1.getCurvePoint({ keyBytes: publicKeyBytes });\n\n    // Construct the public key in JWK format.\n    const publicKey: Jwk = {\n      kty : 'EC',\n      crv : 'secp256k1',\n      x   : Convert.uint8Array(point.x).toBase64Url(),\n      y   : Convert.uint8Array(point.y).toBase64Url()\n    };\n\n    // Compute the JWK thumbprint and set as the key ID.\n    publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n    return publicKey;\n  }\n\n  /**\n   * Converts a public key to its compressed form.\n   *\n   * @remarks\n   * This method takes a public key represented as a byte array and compresses it. Public key\n   * compression is a process that reduces the size of the public key by removing the y-coordinate,\n   * making it more efficient for storage and transmission. The compressed key retains the same\n   * level of security as the uncompressed key.\n   *\n   * @example\n   * ```ts\n   * const uncompressedPublicKeyBytes = new Uint8Array([...]); // Replace with actual uncompressed public key bytes\n   * const compressedPublicKey = await Secp256k1.compressPublicKey({\n   *   publicKeyBytes: uncompressedPublicKeyBytes\n   * });\n   * ```\n   *\n   * @param params - The parameters for the public key compression.\n   * @param params.publicKeyBytes - The public key as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the compressed public key as a Uint8Array.\n   */\n  public static async compressPublicKey({ publicKeyBytes }: {\n    publicKeyBytes: Uint8Array;\n  }): Promise<Uint8Array> {\n    // Decode Weierstrass points from the public key byte array.\n    const point = secp256k1.Point.fromBytes(publicKeyBytes);\n\n    // Return the compressed form of the public key.\n    return point.toBytes(true);\n  }\n\n  /**\n   * Derives the public key in JWK format from a given private key.\n   *\n   * @remarks\n   * This method takes a private key in JWK format and derives its corresponding public key,\n   * also in JWK format. The derivation process involves converting the private key to a raw\n   * byte array, then computing the elliptic curve point (x and y coordinates) from this private\n   * key. These coordinates are then encoded into base64url format to construct the public key in\n   * JWK format.\n   *\n   * The process ensures that the derived public key correctly corresponds to the given private key,\n   * adhering to the secp256k1 elliptic curve standards. This method is useful in cryptographic\n   * operations where a public key is needed for operations like signature verification, but only\n   * the private key is available.\n   *\n   * @example\n   * ```ts\n   * const privateKey = { ... }; // A Jwk object representing a secp256k1 private key\n   * const publicKey = await Secp256k1.computePublicKey({ key: privateKey });\n   * ```\n   *\n   * @param params - The parameters for the public key derivation.\n   * @param params.key - The private key in JWK format from which to derive the public key.\n   *\n   * @returns A Promise that resolves to the derived public key in JWK format.\n   */\n  public static async computePublicKey({ key }:\n    ComputePublicKeyParams\n  ): Promise<Jwk> {\n    // Convert the provided private key to a byte array.\n    const privateKeyBytes = await Secp256k1.privateKeyToBytes({ privateKey: key });\n\n    // Get the elliptic curve point (x and y coordinates) for the provided private key.\n    const point = await Secp256k1.getCurvePoint({ keyBytes: privateKeyBytes });\n\n    // Construct the public key in JWK format.\n    const publicKey: Jwk = {\n      kty : 'EC',\n      crv : 'secp256k1',\n      x   : Convert.uint8Array(point.x).toBase64Url(),\n      y   : Convert.uint8Array(point.y).toBase64Url()\n    };\n\n    // Compute the JWK thumbprint and set as the key ID.\n    publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n    return publicKey;\n  }\n\n  /**\n   * Converts an ASN.1 DER encoded ECDSA signature to a compact R+S format.\n   *\n   * @remarks\n   * This method is used for converting an ECDSA signature from the ASN.1 DER encoding to the more\n   * compact R+S format. This conversion is often required when dealing with ECDSA signatures in\n   * certain cryptographic standards such as JWS (JSON Web Signature).\n   *\n   * The method decodes the DER-encoded signature, extracts the R and S values, and concatenates\n   * them into a single byte array. This process involves handling the ASN.1 structure to correctly\n   * parse the R and S values, considering padding and integer encoding specifics of DER.\n   *\n   * @example\n   * ```ts\n   * const derSignature = new Uint8Array([...]); // Replace with your DER-encoded signature\n   * const signature = await Secp256k1.convertDerToCompactSignature({ derSignature });\n   * ```\n   *\n   * @param params - The parameters for the signature conversion.\n   * @param params.derSignature - The signature in ASN.1 DER format as a `Uint8Array`.\n   *\n   * @returns A Promise that resolves to the signature in compact R+S format as a `Uint8Array`.\n   */\n  public static async convertDerToCompactSignature({ derSignature }: {\n    derSignature: Uint8Array;\n  }): Promise<Uint8Array> {\n    // Convert the DER-encoded signature into a `secp256k1.Signature` object.\n    // This involves parsing the ASN.1 DER structure to extract the R and S components.\n    const signatureObject = secp256k1.Signature.fromBytes(derSignature, 'der');\n\n    // Convert the signature object into compact R+S format, which concatenates the R and S values\n    // into a single byte array.\n    const compactSignature = signatureObject.toBytes('compact');\n\n    return compactSignature;\n  }\n\n  /**\n   * Converts a public key to its uncompressed form.\n   *\n   * @remarks\n   * This method takes a compressed public key represented as a byte array and decompresses it.\n   * Public key decompression involves reconstructing the y-coordinate from the x-coordinate,\n   * resulting in the full public key. This method is used when the uncompressed key format is\n   * required for certain cryptographic operations or interoperability.\n   *\n   * @example\n   * ```ts\n   * const compressedPublicKeyBytes = new Uint8Array([...]); // Replace with actual compressed public key bytes\n   * const decompressedPublicKey = await Secp256k1.decompressPublicKey({\n   *   publicKeyBytes: compressedPublicKeyBytes\n   * });\n   * ```\n   *\n   * @param params - The parameters for the public key decompression.\n   * @param params.publicKeyBytes - The public key as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the uncompressed public key as a Uint8Array.\n   */\n  public static async decompressPublicKey({ publicKeyBytes }: {\n    publicKeyBytes: Uint8Array;\n  }): Promise<Uint8Array> {\n    // Decode Weierstrass points from the public key byte array.\n    const point = secp256k1.Point.fromBytes(publicKeyBytes);\n\n    // Return the uncompressed form of the public key.\n    return point.toBytes(false);\n  }\n\n  /**\n   * Generates a secp256k1 private key in JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method creates a new private key suitable for use with the secp256k1\n   * elliptic curve. The key is generated using cryptographically secure random\n   * number generation to ensure its uniqueness and security. The resulting\n   * private key adheres to the JWK format, specifically tailored for secp256k1,\n   * making it compatible with common cryptographic standards and easy to use in\n   * various cryptographic processes.\n   *\n   * The private key generated by this method includes the following components:\n   * - `kty`: Key Type, set to 'EC' for Elliptic Curve.\n   * - `crv`: Curve Name, set to 'secp256k1'.\n   * - `d`: The private key component, base64url-encoded.\n   * - `x`: The x-coordinate of the public key point, derived from the private key, base64url-encoded.\n   * - `y`: The y-coordinate of the public key point, derived from the private key, base64url-encoded.\n   *\n   * The key is returned in a format suitable for direct use in signin and key agreement operations.\n   *\n   * @example\n   * ```ts\n   * const privateKey = await Secp256k1.generateKey();\n   * ```\n   *\n   * @returns A Promise that resolves to the generated private key in JWK format.\n   */\n  public static async generateKey(): Promise<Jwk> {\n    // Generate a random private key.\n    const privateKeyBytes = secp256k1.utils.randomSecretKey();\n\n    // Convert private key from bytes to JWK format.\n    const privateKey = await Secp256k1.bytesToPrivateKey({ privateKeyBytes });\n\n    // Compute the JWK thumbprint and set as the key ID.\n    privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n    return privateKey;\n  }\n\n  /**\n   * Retrieves the public key properties from a given private key in JWK format.\n   *\n   * @remarks\n   * This method extracts the public key portion from a secp256k1 private key in JWK format. It does\n   * so by removing the private key property 'd' and making a shallow copy, effectively yielding the\n   * public key. The method sets the 'kid' (key ID) property using the JWK thumbprint if it is not\n   * already defined. This approach is used under the assumption that a private key in JWK format\n   * always contains the corresponding public key properties.\n   *\n   * Note: This method offers a significant performance advantage, being about 200 times faster\n   * than `computePublicKey()`. However, it does not mathematically validate the private key, nor\n   * does it derive the public key from the private key. It simply extracts existing public key\n   * properties from the private key object. This makes it suitable for scenarios where speed is\n   * critical and the private key's integrity is already assured.\n   *\n   * @example\n   * ```ts\n   * const privateKey = { ... }; // A Jwk object representing a secp256k1 private key\n   * const publicKey = await Secp256k1.getPublicKey({ key: privateKey });\n   * ```\n   *\n   * @param params - The parameters for retrieving the public key properties.\n   * @param params.key - The private key in JWK format.\n   *\n   * @returns A Promise that resolves to the public key in JWK format.\n   */\n  public static async getPublicKey({ key }:\n    GetPublicKeyParams\n  ): Promise<Jwk> {\n    // Verify the provided JWK represents an elliptic curve (EC) secp256k1 private key.\n    if (!(isEcPrivateJwk(key) && key.crv === 'secp256k1')) {\n      throw new Error(`Secp256k1: The provided key is not a secp256k1 private JWK.`);\n    }\n\n    // Remove the private key property ('d') and make a shallow copy of the provided key.\n    const { d, ...publicKey } = key;\n\n    // If the key ID is undefined, set it to the JWK thumbprint.\n    publicKey.kid ??= await computeJwkThumbprint({ jwk: publicKey });\n\n    return publicKey;\n  }\n\n  /**\n   * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n   *\n   * @remarks\n   * This method takes a private key in JWK format and extracts its raw byte representation.\n   * It specifically focuses on the 'd' parameter of the JWK, which represents the private\n   * key component in base64url encoding. The method decodes this value into a byte array.\n   *\n   * This conversion is essential for operations that require the private key in its raw\n   * binary form, such as certain low-level cryptographic operations or when interfacing\n   * with systems and libraries that expect keys in a byte array format.\n   *\n   * @example\n   * ```ts\n   * const privateKey = { ... }; // An X25519 private key in JWK format\n   * const privateKeyBytes = await Secp256k1.privateKeyToBytes({ privateKey });\n   * ```\n   *\n   * @param params - The parameters for the private key conversion.\n   * @param params.privateKey - The private key in JWK format.\n   *\n   * @returns A Promise that resolves to the private key as a Uint8Array.\n   */\n  public static async privateKeyToBytes({ privateKey }: {\n    privateKey: Jwk;\n  }): Promise<Uint8Array> {\n    // Verify the provided JWK represents a valid EC secp256k1 private key.\n    if (!isEcPrivateJwk(privateKey)) {\n      throw new Error(`Secp256k1: The provided key is not a valid EC private key.`);\n    }\n\n    // Decode the provided private key to bytes.\n    const privateKeyBytes = Convert.base64Url(privateKey.d).toUint8Array();\n\n    return privateKeyBytes;\n  }\n\n  /**\n   * Converts a public key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n   *\n   * @remarks\n   * This method accepts a public key in JWK format and converts it into its raw binary\n   * form. The conversion process involves decoding the 'x' and 'y' parameters of the JWK\n   * (which represent the x and y coordinates of the elliptic curve point, respectively)\n   * from base64url format into a byte array. The method then concatenates these values,\n   * along with a prefix indicating the key format, to form the full public key.\n   *\n   * This function is particularly useful for use cases where the public key is needed\n   * in its raw byte format, such as for certain cryptographic operations or when\n   * interfacing with systems that require raw key formats.\n   *\n   * @example\n   * ```ts\n   * const publicKey = { ... }; // A Jwk public key object\n   * const publicKeyBytes = await Secp256k1.publicKeyToBytes({ publicKey });\n   * ```\n   *\n   * @param params - The parameters for the public key conversion.\n   * @param params.publicKey - The public key in JWK format.\n   *\n   * @returns A Promise that resolves to the public key as a Uint8Array.\n   */\n  public static async publicKeyToBytes({ publicKey }: {\n    publicKey: Jwk;\n  }): Promise<Uint8Array> {\n    // Verify the provided JWK represents a valid EC secp256k1 public key, which must have a 'y' value.\n    if (!(isEcPublicJwk(publicKey) && publicKey.y)) {\n      throw new Error(`Secp256k1: The provided key is not a valid EC public key.`);\n    }\n\n    // Decode the provided public key to bytes.\n    const prefix = new Uint8Array([0x04]); // Designates an uncompressed key.\n    const x = Convert.base64Url(publicKey.x).toUint8Array();\n    const y = Convert.base64Url(publicKey.y).toUint8Array();\n\n    // Concatenate the prefix, x-coordinate, and y-coordinate as a single byte array.\n    const publicKeyBytes = new Uint8Array([...prefix, ...x, ...y]);\n\n    return publicKeyBytes;\n  }\n\n  /**\n   * Computes an RFC6090-compliant Elliptic Curve Diffie-Hellman (ECDH) shared secret\n   * using secp256k1 private and public keys in JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method facilitates the ECDH key agreement protocol, which is a method of securely\n   * deriving a shared secret between two parties based on their private and public keys.\n   * It takes the private key of one party (privateKeyA) and the public key of another\n   * party (publicKeyB) to compute a shared secret. The shared secret is derived from the\n   * x-coordinate of the elliptic curve point resulting from the multiplication of the\n   * public key with the private key.\n   *\n   * Note: When performing Elliptic Curve Diffie-Hellman (ECDH) key agreement,\n   * the resulting shared secret is a point on the elliptic curve, which\n   * consists of an x-coordinate and a y-coordinate. With a 256-bit curve like\n   * secp256k1, each of these coordinates is 32 bytes (256 bits) long. However,\n   * in the ECDH process, it's standard practice to use only the x-coordinate\n   * of the shared secret point as the resulting shared key. This is because\n   * the y-coordinate does not add to the entropy of the key, and both parties\n   * can independently compute the x-coordinate.  Consquently, this implementation\n   * omits the y-coordinate for simplicity and standard compliance.\n   *\n   * @example\n   * ```ts\n   * const privateKeyA = { ... }; // A Jwk private key object for party A\n   * const publicKeyB = { ... }; // A Jwk public key object for party B\n   * const sharedSecret = await Secp256k1.sharedSecret({\n   *   privateKeyA,\n   *   publicKeyB\n   * });\n   * ```\n   *\n   * @param params - The parameters for the shared secret computation.\n   * @param params.privateKeyA - The private key in JWK format of one party.\n   * @param params.publicKeyB - The public key in JWK format of the other party.\n   *\n   * @returns A Promise that resolves to the computed shared secret as a Uint8Array.\n   */\n  public static async sharedSecret({ privateKeyA, publicKeyB }: {\n    privateKeyA: Jwk;\n    publicKeyB: Jwk;\n  }): Promise<Uint8Array> {\n    // Ensure that keys from the same key pair are not specified.\n    if ('x' in privateKeyA && 'x' in publicKeyB && privateKeyA.x === publicKeyB.x) {\n      throw new Error(`Secp256k1: ECDH shared secret cannot be computed from a single key pair's public and private keys.`);\n    }\n\n    // Convert the provided private and public keys to bytes.\n    const privateKeyABytes = await Secp256k1.privateKeyToBytes({ privateKey: privateKeyA });\n    const publicKeyBBytes = await Secp256k1.publicKeyToBytes({ publicKey: publicKeyB });\n\n    // Compute the compact representation shared secret between the public and private keys.\n    const sharedSecret = secp256k1.getSharedSecret(privateKeyABytes, publicKeyBBytes, true);\n\n    // Remove the leading byte that indicates the sign of the y-coordinate\n    // of the point on the elliptic curve.  See note above.\n    return sharedSecret.slice(1);\n  }\n\n  /**\n   * Generates an RFC6979-compliant ECDSA signature of given data using a secp256k1 private key.\n   *\n   * @remarks\n   * This method signs the provided data with a specified private key using the ECDSA\n   * (Elliptic Curve Digital Signature Algorithm) signature algorithm, as defined in RFC6979.\n   * The data to be signed is first hashed using the SHA-256 algorithm, and this hash is then\n   * signed using the private key. The output is a digital signature in the form of a\n   * Uint8Array, which uniquely corresponds to both the data and the private key used for signing.\n   *\n   * This method is commonly used in cryptographic applications to ensure data integrity and\n   * authenticity. The signature can later be verified by parties with access to the corresponding\n   * public key, ensuring that the data has not been tampered with and was indeed signed by the\n   * holder of the private key.\n   *\n   * @example\n   * ```ts\n   * const data = new TextEncoder().encode('Messsage'); // Data to be signed\n   * const privateKey = { ... }; // A Jwk object representing a secp256k1 private key\n   * const signature = await Secp256k1.sign({\n   *   key: privateKey,\n   *   data\n   * });\n   * ```\n   *\n   * @param params - The parameters for the signing operation.\n   * @param params.key - The private key to use for signing, represented in JWK format.\n   * @param params.data - The data to sign, represented as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the signature as a Uint8Array.\n   */\n  public static async sign({ data, key }:\n    SignParams\n  ): Promise<Uint8Array> {\n    // Convert the private key from JWK format to bytes.\n    const privateKeyBytes = await Secp256k1.privateKeyToBytes({ privateKey: key });\n\n    // Generate a digest of the data using the SHA-256 hash function.\n    const digest = sha256(data);\n\n    // Sign the provided data using the ECDSA algorithm.\n    // The `secp256k1.sign` operation returns a signature object with { r, s, recovery } properties.\n    const signature = secp256k1.sign(digest, privateKeyBytes, { prehash: false });\n\n    return signature;\n  }\n\n  /**\n   * Validates a given private key to ensure its compliance with the secp256k1 curve standards.\n   *\n   * @remarks\n   * This method checks whether a provided private key is a valid 32-byte number and falls within\n   * the range defined by the secp256k1 curve's order. It is essential for ensuring the private\n   * key's mathematical correctness in the context of secp256k1-based cryptographic operations.\n   *\n   * Note that this validation strictly pertains to the key's format and numerical validity; it does\n   * not assess whether the key corresponds to a known entity or its security status (e.g., whether\n   * it has been compromised).\n   *\n   * @example\n   * ```ts\n   * const privateKeyBytes = new Uint8Array([...]); // A 32-byte private key\n   * const isValid = await Secp256k1.validatePrivateKey({ privateKeyBytes });\n   * console.log(isValid); // true or false based on the key's validity\n   * ```\n   *\n   * @param params - The parameters for the key validation.\n   * @param params.privateKeyBytes - The private key to validate, represented as a Uint8Array.\n   *\n   * @returns A Promise that resolves to a boolean indicating whether the private key is valid.\n   */\n  public static async validatePrivateKey({ privateKeyBytes }: {\n    privateKeyBytes: Uint8Array;\n  }): Promise<boolean> {\n    return secp256k1.utils.isValidSecretKey(privateKeyBytes);\n  }\n\n  /**\n   * Validates a given public key to confirm its mathematical correctness on the secp256k1 curve.\n   *\n   * @remarks\n   * This method checks if the provided public key represents a valid point on the secp256k1 curve.\n   * It decodes the key's Weierstrass points (x and y coordinates) and verifies their validity\n   * against the curve's parameters. A valid point must lie on the curve and meet specific\n   * mathematical criteria defined by the curve's equation.\n   *\n   * It's important to note that this method does not verify the key's ownership or whether it has\n   * been compromised; it solely focuses on the key's adherence to the curve's mathematical\n   * principles.\n   *\n   * @example\n   * ```ts\n   * const publicKeyBytes = new Uint8Array([...]); // A public key in byte format\n   * const isValid = await Secp256k1.validatePublicKey({ publicKeyBytes });\n   * console.log(isValid); // true if the key is valid on the secp256k1 curve, false otherwise\n   * ```\n   *\n   * @param params - The parameters for the key validation.\n   * @param params.publicKeyBytes - The public key to validate, represented as a Uint8Array.\n   *\n   * @returns A Promise that resolves to a boolean indicating the public key's validity on\n   *          the secp256k1 curve.\n   */\n  public static async validatePublicKey({ publicKeyBytes }: {\n    publicKeyBytes: Uint8Array;\n  }): Promise<boolean> {\n    try {\n      // Decode Weierstrass points from key bytes.\n      const point = secp256k1.Point.fromBytes(publicKeyBytes);\n\n      // Check if points are on the Short Weierstrass curve.\n      point.assertValidity();\n\n    } catch {\n      return false;\n    }\n\n    return true;\n  }\n\n  /**\n   * Verifies an RFC6979-compliant ECDSA signature against given data and a secp256k1 public key.\n   *\n   * @remarks\n   * This method validates a digital signature to ensure that it was generated by the holder of the\n   * corresponding private key and that the signed data has not been altered. The signature\n   * verification is performed using the ECDSA (Elliptic Curve Digital Signature Algorithm) as\n   * specified in RFC6979. The data to be verified is first hashed using the SHA-256 algorithm, and\n   * this hash is then used along with the public key to verify the signature.\n   *\n   * The method returns a boolean value indicating whether the signature is valid. A valid signature\n   * proves that the signed data was indeed signed by the owner of the private key corresponding to\n   * the provided public key and that the data has not been tampered with since it was signed.\n   *\n   * Note: The verification process does not consider the malleability of low-s signatures, which\n   * may be relevant in certain contexts, such as Bitcoin transactions.\n   *\n   * @example\n   * ```ts\n   * const data = new TextEncoder().encode('Messsage'); // Data that was signed\n   * const publicKey = { ... }; // Public key in JWK format corresponding to the private key that signed the data\n   * const signature = new Uint8Array([...]); // Signature to verify\n   * const isSignatureValid = await Secp256k1.verify({\n   *   key: publicKey,\n   *   signature,\n   *   data\n   * });\n   * console.log(isSignatureValid); // true if the signature is valid, false otherwise\n   * ```\n   *\n   * @param params - The parameters for the signature verification.\n   * @param params.key - The public key used for verification, represented in JWK format.\n   * @param params.signature - The signature to verify, represented as a Uint8Array.\n   * @param params.data - The data that was signed, represented as a Uint8Array.\n   *\n   * @returns A Promise that resolves to a boolean indicating whether the signature is valid.\n   */\n  public static async verify({ key, signature, data }:\n    VerifyParams\n  ): Promise<boolean> {\n    // Convert the public key from JWK format to bytes.\n    const publicKeyBytes = await Secp256k1.publicKeyToBytes({ publicKey: key });\n\n    // Generate a digest of the data using the SHA-256 hash function.\n    const digest = sha256(data);\n\n    /** Perform the verification of the signature.\n     * This verify operation has the malleability check disabled. Guaranteed support\n     * for low-s signatures across languages is unlikely especially in the context\n     * of SSI. Notable Cloud KMS providers do not natively support it either. It is\n     * also worth noting that low-s signatures are a requirement for Bitcoin. */\n    const isValid = secp256k1.verify(signature, digest, publicKeyBytes, { lowS: false, prehash: false });\n\n    return isValid;\n  }\n\n  /**\n   * Returns the elliptic curve point (x and y coordinates) for a given secp256k1 key.\n   *\n   * @remarks\n   * This method extracts the elliptic curve point from a given secp256k1 key, whether\n   * it's a private or a public key. For a private key, the method first computes the\n   * corresponding public key and then extracts the x and y coordinates. For a public key,\n   * it directly returns these coordinates. The coordinates are represented as Uint8Array.\n   *\n   * The x and y coordinates represent the key's position on the elliptic curve and can be\n   * used in various cryptographic operations, such as digital signatures or key agreement\n   * protocols.\n   *\n   * @example\n   * ```ts\n   * // For a private key\n   * const privateKey = new Uint8Array([...]); // A 32-byte private key\n   * const { x: xFromPrivateKey, y: yFromPrivateKey } = await Secp256k1.getCurvePoint({ keyBytes: privateKey });\n   *\n   * // For a public key\n   * const publicKey = new Uint8Array([...]); // A 33-byte or 65-byte public key\n   * const { x: xFromPublicKey, y: yFromPublicKey } = await Secp256k1.getCurvePoint({ keyBytes: publicKey });\n   * ```\n   *\n   * @param params - The parameters for the curve point decoding operation.\n   * @param params.keyBytes - The key for which to get the elliptic curve point.\n   *                          Can be either a private key or a public key.\n   *                          The key should be passed as a `Uint8Array`.\n   *\n   * @returns A Promise that resolves to an object with properties 'x' and 'y',\n   *          each being a Uint8Array representing the x and y coordinates of the key point on the\n   *          elliptic curve.\n   */\n  private static async getCurvePoint({ keyBytes }: {\n    keyBytes: Uint8Array;\n  }): Promise<AffinePoint<Uint8Array>> {\n    // If key is a private key, first compute the public key.\n    if (keyBytes.byteLength === 32) {\n      keyBytes = secp256k1.getPublicKey(keyBytes);\n    }\n\n    // Decode Weierstrass affine point from key bytes.\n    const point = secp256k1.Point.fromBytes(keyBytes);\n\n    // Get x- and y-coordinate values and convert to Uint8Array.\n    const x = numberToBytesBE(point.x, 32);\n    const y = numberToBytesBE(point.y, 32);\n\n    return { x, y };\n  }\n}\n", "/**\n * Internal module for NIST P256, P384, P521 curves.\n * Do not use for now.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256, sha384, sha512 } from '@noble/hashes/sha2.js';\nimport { createFROST, type FROST } from './abstract/frost.ts';\nimport { createHasher, type H2CHasher } from './abstract/hash-to-curve.ts';\nimport { createOPRF, type OPRF } from './abstract/oprf.ts';\nimport {\n  ecdsa,\n  mapToCurveSimpleSWU,\n  weierstrass,\n  type ECDSA,\n  type WeierstrassOpts,\n  type WeierstrassPointCons,\n} from './abstract/weierstrass.ts';\nimport { type TRet } from './utils.ts';\n\n// p = 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n - 1n\n// a = Fp256.create(BigInt('-3'));\nconst p256_CURVE: WeierstrassOpts<bigint> = /* @__PURE__ */ (() => ({\n  p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),\n  n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),\n  h: BigInt(1),\n  a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),\n  b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),\n  Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),\n  Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),\n}))();\n\n// p = 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n\nconst p384_CURVE: WeierstrassOpts<bigint> = /* @__PURE__ */ (() => ({\n  p: BigInt(\n    '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'\n  ),\n  n: BigInt(\n    '0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'\n  ),\n  h: BigInt(1),\n  a: BigInt(\n    '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc'\n  ),\n  b: BigInt(\n    '0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'\n  ),\n  Gx: BigInt(\n    '0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'\n  ),\n  Gy: BigInt(\n    '0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'\n  ),\n}))();\n\n// p = 2n**521n - 1n\nconst p521_CURVE: WeierstrassOpts<bigint> = /* @__PURE__ */ (() => ({\n  p: BigInt(\n    '0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'\n  ),\n  n: BigInt(\n    '0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'\n  ),\n  h: BigInt(1),\n  a: BigInt(\n    '0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc'\n  ),\n  b: BigInt(\n    '0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'\n  ),\n  Gx: BigInt(\n    '0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'\n  ),\n  Gy: BigInt(\n    '0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'\n  ),\n}))();\n\ntype SwuOpts = {\n  A: bigint;\n  B: bigint;\n  Z: bigint;\n};\n\nfunction createSWU(Point: WeierstrassPointCons<bigint>, opts: SwuOpts) {\n  let map: ((u: bigint) => { x: bigint; y: bigint }) | undefined;\n  // RFC 9380's NIST suites here all use m = 1, so createHasher passes one field element per map.\n  // Building the SWU sqrt-ratio helper eagerly adds noticeable `nist.js` import cost, so defer it\n  // to first use; after that the cached mapper is reused directly.\n  return (scalars: bigint[]) => (map || (map = mapToCurveSimpleSWU(Point.Fp, opts)))(scalars[0]);\n}\n\n// NIST P256\nconst p256_Point = /* @__PURE__ */ weierstrass(p256_CURVE);\n/**\n * NIST P256 (aka secp256r1, prime256v1) curve, ECDSA and ECDH methods.\n * Hashes inputs with sha256 by default.\n *\n * @example\n * Generate one P-256 keypair, sign a message, and verify it.\n *\n * ```js\n * import { p256 } from '@noble/curves/nist.js';\n * const { secretKey, publicKey } = p256.keygen();\n * // const publicKey = p256.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = p256.sign(msg, secretKey);\n * const isValid = p256.verify(sig, msg, publicKey);\n * // const sigKeccak = p256.sign(keccak256(msg), secretKey, { prehash: false });\n * ```\n */\nexport const p256: ECDSA = /* @__PURE__ */ ecdsa(p256_Point, sha256);\n/**\n * Hashing / encoding to p256 points / field. RFC 9380 methods.\n * @example\n * Hash one message onto the P-256 curve.\n *\n * ```ts\n * const point = p256_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const p256_hasher: H2CHasher<WeierstrassPointCons<bigint>> = /* @__PURE__ */ (() => {\n  return createHasher(\n    p256_Point,\n    createSWU(p256_Point, {\n      A: p256_CURVE.a,\n      B: p256_CURVE.b,\n      Z: p256_Point.Fp.create(BigInt('-10')),\n    }),\n    {\n      DST: 'P256_XMD:SHA-256_SSWU_RO_',\n      encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',\n      p: p256_CURVE.p,\n      m: 1,\n      k: 128,\n      expand: 'xmd',\n      hash: sha256,\n    }\n  );\n})();\n/**\n * p256 OPRF, defined in RFC 9497.\n * @example\n * Run one blind/evaluate/finalize OPRF round over P-256.\n *\n * ```ts\n * const input = new TextEncoder().encode('hello noble');\n * const keys = p256_oprf.oprf.generateKeyPair();\n * const blind = p256_oprf.oprf.blind(input);\n * const evaluated = p256_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded);\n * const output = p256_oprf.oprf.finalize(input, blind.blind, evaluated);\n * ```\n */\nexport const p256_oprf: TRet<OPRF> = /* @__PURE__ */ (() =>\n  createOPRF({\n    name: 'P256-SHA256',\n    Point: p256_Point,\n    hash: sha256,\n    hashToGroup: p256_hasher.hashToCurve,\n    hashToScalar: p256_hasher.hashToScalar,\n  }))();\n/**\n * FROST threshold signatures over p256. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 p256 signing.\n *\n * ```ts\n * const alice = p256_FROST.Identifier.derive('alice@example.com');\n * const bob = p256_FROST.Identifier.derive('bob@example.com');\n * const carol = p256_FROST.Identifier.derive('carol@example.com');\n * const deal = p256_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const p256_FROST: TRet<FROST> = /* @__PURE__ */ (() =>\n  createFROST({\n    name: 'FROST-P256-SHA256-v1',\n    Point: p256_Point,\n    hashToScalar: p256_hasher.hashToScalar,\n    hash: sha256,\n  }))();\n\n// NIST P384\nconst p384_Point = /* @__PURE__ */ weierstrass(p384_CURVE);\n/**\n * NIST P384 (aka secp384r1) curve, ECDSA and ECDH methods. Hashes inputs with sha384 by default.\n * @example\n * Generate one P-384 keypair, sign a message, and verify it.\n *\n * ```ts\n * const { secretKey, publicKey } = p384.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = p384.sign(msg, secretKey);\n * const isValid = p384.verify(sig, msg, publicKey);\n * ```\n */\nexport const p384: ECDSA = /* @__PURE__ */ ecdsa(p384_Point, sha384);\n/**\n * Hashing / encoding to p384 points / field. RFC 9380 methods.\n * @example\n * Hash one message onto the P-384 curve.\n *\n * ```ts\n * const point = p384_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const p384_hasher: H2CHasher<WeierstrassPointCons<bigint>> = /* @__PURE__ */ (() => {\n  return createHasher(\n    p384_Point,\n    createSWU(p384_Point, {\n      A: p384_CURVE.a,\n      B: p384_CURVE.b,\n      Z: p384_Point.Fp.create(BigInt('-12')),\n    }),\n    {\n      DST: 'P384_XMD:SHA-384_SSWU_RO_',\n      encodeDST: 'P384_XMD:SHA-384_SSWU_NU_',\n      p: p384_CURVE.p,\n      m: 1,\n      k: 192,\n      expand: 'xmd',\n      hash: sha384,\n    }\n  );\n})();\n/**\n * p384 OPRF, defined in RFC 9497.\n * @example\n * Run one blind/evaluate/finalize OPRF round over P-384.\n *\n * ```ts\n * const input = new TextEncoder().encode('hello noble');\n * const keys = p384_oprf.oprf.generateKeyPair();\n * const blind = p384_oprf.oprf.blind(input);\n * const evaluated = p384_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded);\n * const output = p384_oprf.oprf.finalize(input, blind.blind, evaluated);\n * ```\n */\nexport const p384_oprf: TRet<OPRF> = /* @__PURE__ */ (() =>\n  createOPRF({\n    name: 'P384-SHA384',\n    Point: p384_Point,\n    hash: sha384,\n    hashToGroup: p384_hasher.hashToCurve,\n    hashToScalar: p384_hasher.hashToScalar,\n  }))();\n\n// NIST P521\n// RFC 7518 fixes the canonical JWK/JOSE width at 66 bytes:\n// - Section 3.4 says ECDSA octet strings must not omit leading zero octets\n// - Sections 6.2.1.2/6.2.1.3 say P-521 coordinates \"x\"/\"y\" must be 66 octets\n// - Section 6.2.2.1 says private scalar \"d\" must be ceil(log2(n)/8) octets, i.e. 66 for P-521\n// NIST FIPS 186-5 Appendix A.3.3 also routes deterministic ECDSA private keys through Appendix\n// B.2.3, whose Integer-to-Octet-String output has explicit fixed length L; for P-521 that is the\n// same 66-byte order width.\n// RFC 6979 matches that width too: private key x is an integer, while `int2octets(x)` uses\n// rlen = 8 * ceil(qlen/8); for P-521, qlen = 521 so the canonical octet width is 66 bytes.\n// Wycheproof ECDH stores private values as integers, not fixed-width scalar bytes, so it does not\n// require a dedicated 65-byte parser path; the repo tests now normalize those integer fixtures to\n// the canonical 66-byte width before use. There is no good standards or oracle reason to accept\n// exactly 65 bytes here: the coherent choices are canonical 66 only, or a broader integer-style\n// parser across many widths. Since this field parser is fixed-width, keep it canonical and use the\n// default exact-66-byte scalar field path.\nconst p521_Point = /* @__PURE__ */ weierstrass(p521_CURVE);\n/**\n * NIST P521 (aka secp521r1) curve, ECDSA and ECDH methods. Hashes inputs with sha512 by default.\n * Deterministic `keygen(seed)` expects 99 seed bytes here because the generic scalar-derivation\n * helper uses `getMinHashLength(n)`, not the 66-byte canonical secret-key width.\n * @example\n * Generate one P-521 keypair, sign a message, and verify it.\n *\n * ```ts\n * const { secretKey, publicKey } = p521.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = p521.sign(msg, secretKey);\n * const isValid = p521.verify(sig, msg, publicKey);\n * ```\n */\nexport const p521: ECDSA = /* @__PURE__ */ ecdsa(p521_Point, sha512);\n/**\n * Hashing / encoding to p521 points / field. RFC 9380 methods.\n * @example\n * Hash one message onto the P-521 curve.\n *\n * ```ts\n * const point = p521_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const p521_hasher: H2CHasher<WeierstrassPointCons<bigint>> = /* @__PURE__ */ (() => {\n  return createHasher(\n    p521_Point,\n    createSWU(p521_Point, {\n      A: p521_CURVE.a,\n      B: p521_CURVE.b,\n      Z: p521_Point.Fp.create(BigInt('-4')),\n    }),\n    {\n      DST: 'P521_XMD:SHA-512_SSWU_RO_',\n      encodeDST: 'P521_XMD:SHA-512_SSWU_NU_',\n      p: p521_CURVE.p,\n      m: 1,\n      k: 256,\n      expand: 'xmd',\n      hash: sha512,\n    }\n  );\n})();\n/**\n * p521 OPRF, defined in RFC 9497.\n * @example\n * Run one blind/evaluate/finalize OPRF round over P-521.\n *\n * ```ts\n * const input = new TextEncoder().encode('hello noble');\n * const keys = p521_oprf.oprf.generateKeyPair();\n * const blind = p521_oprf.oprf.blind(input);\n * const evaluated = p521_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded);\n * const output = p521_oprf.oprf.finalize(input, blind.blind, evaluated);\n * ```\n */\nexport const p521_oprf: TRet<OPRF> = /* @__PURE__ */ (() =>\n  createOPRF({\n    name: 'P521-SHA512',\n    Point: p521_Point,\n    hash: sha512,\n    hashToGroup: p521_hasher.hashToCurve,\n    hashToScalar: p521_hasher.hashToScalar, // produces L=98 just like in RFC\n  }))();\n", "import type { AffinePoint } from '@noble/curves/abstract/weierstrass.js';\n\nimport { Convert } from '@enbox/common';\nimport { numberToBytesBE } from '@noble/curves/utils.js';\nimport { p256 as secp256r1 } from '@noble/curves/nist.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nimport type { Jwk } from '../jose/jwk.js';\nimport type { ComputePublicKeyParams, GetPublicKeyParams, SignParams, VerifyParams } from '../types/params-direct.js';\n\nimport { computeJwkThumbprint, isEcPrivateJwk, isEcPublicJwk } from '../jose/jwk.js';\n\n/**\n * The `Secp256r1` class provides a comprehensive suite of utilities for working with\n * the secp256r1 (aka P-256) elliptic curve, commonly used in blockchain and cryptographic\n * applications. This class includes methods for key generation, conversion, signing, verification,\n * and Elliptic Curve Diffie-Hellman (ECDH) key agreement.\n *\n * The class supports conversions between raw byte formats and JSON Web Key (JWK) formats. It\n * adheres to RFC6979 for ECDSA signing and verification and RFC6090 for ECDH.\n *\n * Key Features:\n * - Key Generation: Generate secp256r1 private keys in JWK format.\n * - Key Conversion: Transform keys between raw byte arrays and JWK formats.\n * - Public Key Derivation: Derive public keys from private keys.\n * - ECDH Shared Secret Computation: Securely derive shared secrets using private and public keys.\n * - ECDSA Signing and Verification: Sign data and verify signatures with secp256r1 keys.\n * - Key Validation: Validate the mathematical correctness of secp256r1 keys.\n *\n * The methods in this class are asynchronous, returning Promises to accommodate various\n * JavaScript environments, and use `Uint8Array` for binary data handling.\n *\n * @example\n * ```ts\n * // Key Generation\n * const privateKey = await Secp256r1.generateKey();\n *\n * // Public Key Derivation\n * const publicKey = await Secp256r1.computePublicKey({ key: privateKey });\n * console.log(publicKey === await Secp256r1.getPublicKey({ key: privateKey })); // Output: true\n *\n * // ECDH Shared Secret Computation\n * const sharedSecret = await Secp256r1.sharedSecret({\n *   privateKeyA: privateKey,\n *   publicKeyB: anotherPublicKey\n * });\n *\n * // ECDSA Signing\n * const signature = await Secp256r1.sign({\n *   key: privateKey,\n *   data: new TextEncoder().encode('Message')\n * });\n *\n * // ECDSA Signature Verification\n * const isValid = await Secp256r1.verify({\n *   key: publicKey,\n *   signature: signature,\n *   data: new TextEncoder().encode('Message')\n * });\n *\n * // Key Conversion\n * const publicKeyBytes = await Secp256r1.publicKeyToBytes({ publicKey });\n * const privateKeyBytes = await Secp256r1.privateKeyToBytes({ privateKey });\n * const compressedPublicKey = await Secp256r1.compressPublicKey({ publicKeyBytes });\n * const uncompressedPublicKey = await Secp256r1.decompressPublicKey({ publicKeyBytes });\n *\n * // Key Validation\n * const isPrivateKeyValid = await Secp256r1.validatePrivateKey({ privateKeyBytes });\n * const isPublicKeyValid = await Secp256r1.validatePublicKey({ publicKeyBytes });\n * ```\n */\nexport class Secp256r1 {\n/**\n   * Adjusts an ECDSA signature to a normalized, low-S form.\n   *\n   * @remarks\n   * All ECDSA signatures, regardless of the curve, consist of two components, `r` and `s`, both of\n   * which are integers. The curve's order (the total number of points on the curve) is denoted by\n   * `n`. In a valid ECDSA signature, both `r` and `s` must be in the range [1, n-1]. However, due\n   * to the mathematical properties of ECDSA, if `(r, s)` is a valid signature, then `(r, n - s)` is\n   * also a valid signature for the same message and public key. In other words, for every\n   * signature, there's a \"mirror\" signature that's equally valid. For these elliptic curves:\n   *\n   * - Low S Signature: A signature where the `s` component is in the lower half of the range,\n   *                    specifically less than or equal to `n/2`.\n   *\n   * - High S Signature: This is where the `s` component is in the upper half of the range, greater\n   *                     than `n/2`.\n   *\n   * The practical implication is that a third-party can forge a second valid signature for the same\n   * message by negating the `s` component of the original signature, without any knowledge of the\n   * private key. This is known as a \"signature malleability\" attack.\n   *\n   * This type of forgery is not a problem in all systems, but it can be an issue in systems that\n   * rely on digital signature uniqueness to ensure transaction integrity. For example, in Bitcoin,\n   * transaction malleability is an issue because it allows for the modification of transaction\n   * identifiers (and potentially, transactions themselves) after they're signed but before they're\n   * confirmed in a block. By enforcing low `s` values, the Bitcoin network reduces the likelihood of\n   * this occurring, making the system more secure and predictable.\n   *\n   * For this reason, it's common practice to normalize ECDSA signatures to a low-S form. This\n   * form is considered standard and preferable in some systems and is known as the \"normalized\"\n   * form of the signature.\n   *\n   * This method takes a signature, and if it's high-S, returns the normalized low-S form. If the\n   * signature is already low-S, it's returned unmodified. It's important to note that this\n   * method does not change the validity of the signature but makes it compliant with systems that\n   * enforce low-S signatures.\n   *\n   * @example\n   * ```ts\n   * const signature = new Uint8Array([...]); // Your ECDSA signature\n   * const adjustedSignature = await Secp256r1.adjustSignatureToLowS({ signature });\n   * // Now 'adjustedSignature' is in the low-S form.\n   * ```\n   *\n   * @param params - The parameters for the signature adjustment.\n   * @param params.signature - The ECDSA signature as a `Uint8Array`.\n   *\n   * @returns A Promise that resolves to the adjusted signature in low-S form as a `Uint8Array`.\n   */\n  public static async adjustSignatureToLowS({ signature }: {\n    signature: Uint8Array;\n  }): Promise<Uint8Array> {\n    // Convert the signature to a `Secp256r1.Signature` object.\n    const signatureObject = secp256r1.Signature.fromBytes(signature, 'compact');\n\n    if (signatureObject.hasHighS()) {\n      // Adjust the signature to low-S format if it's high-S.\n      const adjustedSignatureObject = new secp256r1.Signature(\n        signatureObject.r,\n        secp256r1.Point.CURVE().n - signatureObject.s\n      );\n\n      // Convert the adjusted signature object back to a byte array.\n      const adjustedSignature = adjustedSignatureObject.toBytes('compact');\n\n      return adjustedSignature;\n\n    } else {\n      // Return the unmodified signature if it is already in low-S format.\n      return signature;\n    }\n  }\n\n  /**\n   * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method takes a private key represented as a byte array (Uint8Array) and\n   * converts it into a JWK object. The conversion involves extracting the\n   * elliptic curve point (x and y coordinates) from the private key and encoding\n   * them into base64url format, alongside other JWK parameters.\n   *\n   * The resulting JWK object includes the following properties:\n   * - `kty`: Key Type, set to 'EC' for Elliptic Curve.\n   * - `crv`: Curve Name, set to 'P-256'.\n   * - `d`: The private key component, base64url-encoded.\n   * - `x`: The x-coordinate of the public key point, base64url-encoded.\n   * - `y`: The y-coordinate of the public key point, base64url-encoded.\n   *\n   * This method is useful for converting raw public keys into a standardized\n   * JSON format, facilitating their use in cryptographic operations and making\n   * them easy to share and store.\n   *\n   * @example\n   * ```ts\n   * const privateKeyBytes = new Uint8Array([...]); // Replace with actual private key bytes\n   * const privateKey = await Secp256r1.bytesToPrivateKey({ privateKeyBytes });\n   * ```\n   *\n   * @param params - The parameters for the private key conversion.\n   * @param params.privateKeyBytes - The raw private key as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the private key in JWK format.\n   */\n  public static async bytesToPrivateKey({ privateKeyBytes }: {\n    privateKeyBytes: Uint8Array;\n  }): Promise<Jwk> {\n    // Get the elliptic curve points (x and y coordinates) for the provided private key.\n    const point = await Secp256r1.getCurvePoint({ keyBytes: privateKeyBytes });\n\n    // Construct the private key in JWK format.\n    const privateKey: Jwk = {\n      kty : 'EC',\n      crv : 'P-256',\n      d   : Convert.uint8Array(privateKeyBytes).toBase64Url(),\n      x   : Convert.uint8Array(point.x).toBase64Url(),\n      y   : Convert.uint8Array(point.y).toBase64Url()\n    };\n\n    // Compute the JWK thumbprint and set as the key ID.\n    privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n    return privateKey;\n  }\n\n  /**\n   * Converts a raw public key in bytes to its corresponding JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method accepts a public key in a byte array (Uint8Array) format and\n   * transforms it to a JWK object. It involves decoding the elliptic curve point\n   * (x and y coordinates) from the raw public key bytes and encoding them into\n   * base64url format, along with setting appropriate JWK parameters.\n   *\n   * The resulting JWK object includes the following properties:\n   * - `kty`: Key Type, set to 'EC' for Elliptic Curve.\n   * - `crv`: Curve Name, set to 'P-256'.\n   * - `x`: The x-coordinate of the public key point, base64url-encoded.\n   * - `y`: The y-coordinate of the public key point, base64url-encoded.\n   *\n   * This method is useful for converting raw public keys into a standardized\n   * JSON format, facilitating their use in cryptographic operations and making\n   * them easy to share and store.\n   *\n   * @example\n   * ```ts\n   * const publicKeyBytes = new Uint8Array([...]); // Replace with actual public key bytes\n   * const publicKey = await Secp256r1.bytesToPublicKey({ publicKeyBytes });\n   * ```\n   *\n   * @param params - The parameters for the public key conversion.\n   * @param params.publicKeyBytes - The raw public key as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the public key in JWK format.\n   */\n  public static async bytesToPublicKey({ publicKeyBytes }: {\n    publicKeyBytes: Uint8Array;\n  }): Promise<Jwk> {\n    // Get the elliptic curve point (x and y coordinates) for the provided public key.\n    const point = await Secp256r1.getCurvePoint({ keyBytes: publicKeyBytes });\n\n    // Construct the public key in JWK format.\n    const publicKey: Jwk = {\n      kty : 'EC',\n      crv : 'P-256',\n      x   : Convert.uint8Array(point.x).toBase64Url(),\n      y   : Convert.uint8Array(point.y).toBase64Url()\n    };\n\n    // Compute the JWK thumbprint and set as the key ID.\n    publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n    return publicKey;\n  }\n\n  /**\n   * Converts a public key to its compressed form.\n   *\n   * @remarks\n   * This method takes a public key represented as a byte array and compresses it. Public key\n   * compression is a process that reduces the size of the public key by removing the y-coordinate,\n   * making it more efficient for storage and transmission. The compressed key retains the same\n   * level of security as the uncompressed key.\n   *\n   * @example\n   * ```ts\n   * const uncompressedPublicKeyBytes = new Uint8Array([...]); // Replace with actual uncompressed public key bytes\n   * const compressedPublicKey = await Secp256r1.compressPublicKey({\n   *   publicKeyBytes: uncompressedPublicKeyBytes\n   * });\n   * ```\n   *\n   * @param params - The parameters for the public key compression.\n   * @param params.publicKeyBytes - The public key as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the compressed public key as a Uint8Array.\n   */\n  public static async compressPublicKey({ publicKeyBytes }: {\n    publicKeyBytes: Uint8Array;\n  }): Promise<Uint8Array> {\n    // Decode Weierstrass points from the public key byte array.\n    const point = secp256r1.Point.fromBytes(publicKeyBytes);\n\n    // Return the compressed form of the public key.\n    return point.toBytes(true);\n  }\n\n  /**\n   * Derives the public key in JWK format from a given private key.\n   *\n   * @remarks\n   * This method takes a private key in JWK format and derives its corresponding public key,\n   * also in JWK format. The derivation process involves converting the private key to a raw\n   * byte array, then computing the elliptic curve point (x and y coordinates) from this private\n   * key. These coordinates are then encoded into base64url format to construct the public key in\n   * JWK format.\n   *\n   * The process ensures that the derived public key correctly corresponds to the given private key,\n   * adhering to the secp256r1 elliptic curve standards. This method is useful in cryptographic\n   * operations where a public key is needed for operations like signature verification, but only\n   * the private key is available.\n   *\n   * @example\n   * ```ts\n   * const privateKey = { ... }; // A Jwk object representing a secp256r1 private key\n   * const publicKey = await Secp256r1.computePublicKey({ key: privateKey });\n   * ```\n   *\n   * @param params - The parameters for the public key derivation.\n   * @param params.key - The private key in JWK format from which to derive the public key.\n   *\n   * @returns A Promise that resolves to the derived public key in JWK format.\n   */\n  public static async computePublicKey({ key }:\n    ComputePublicKeyParams\n  ): Promise<Jwk> {\n    // Convert the provided private key to a byte array.\n    const privateKeyBytes = await Secp256r1.privateKeyToBytes({ privateKey: key });\n\n    // Get the elliptic curve point (x and y coordinates) for the provided private key.\n    const point = await Secp256r1.getCurvePoint({ keyBytes: privateKeyBytes });\n\n    // Construct the public key in JWK format.\n    const publicKey: Jwk = {\n      kty : 'EC',\n      crv : 'P-256',\n      x   : Convert.uint8Array(point.x).toBase64Url(),\n      y   : Convert.uint8Array(point.y).toBase64Url()\n    };\n\n    // Compute the JWK thumbprint and set as the key ID.\n    publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n    return publicKey;\n  }\n\n  /**\n   * Converts an ASN.1 DER encoded ECDSA signature to a compact R+S format.\n   *\n   * @remarks\n   * This method is used for converting an ECDSA signature from the ASN.1 DER encoding to the more\n   * compact R+S format. This conversion is often required when dealing with ECDSA signatures in\n   * certain cryptographic standards such as JWS (JSON Web Signature).\n   *\n   * The method decodes the DER-encoded signature, extracts the R and S values, and concatenates\n   * them into a single byte array. This process involves handling the ASN.1 structure to correctly\n   * parse the R and S values, considering padding and integer encoding specifics of DER.\n   *\n   * @example\n   * ```ts\n   * const derSignature = new Uint8Array([...]); // Replace with your DER-encoded signature\n   * const signature = await Secp256r1.convertDerToCompactSignature({ derSignature });\n   * ```\n   *\n   * @param params - The parameters for the signature conversion.\n   * @param params.derSignature - The signature in ASN.1 DER format as a `Uint8Array`.\n   *\n   * @returns A Promise that resolves to the signature in compact R+S format as a `Uint8Array`.\n   */\n  public static async convertDerToCompactSignature({ derSignature }: {\n    derSignature: Uint8Array;\n  }): Promise<Uint8Array> {\n    // Convert the DER-encoded signature into a `Secp256r1.Signature` object.\n    // This involves parsing the ASN.1 DER structure to extract the R and S components.\n    const signatureObject = secp256r1.Signature.fromBytes(derSignature, 'der');\n\n    // Convert the signature object into compact R+S format, which concatenates the R and S values\n    // into a single byte array.\n    const compactSignature = signatureObject.toBytes('compact');\n\n    return compactSignature;\n  }\n\n  /**\n   * Converts a public key to its uncompressed form.\n   *\n   * @remarks\n   * This method takes a compressed public key represented as a byte array and decompresses it.\n   * Public key decompression involves reconstructing the y-coordinate from the x-coordinate,\n   * resulting in the full public key. This method is used when the uncompressed key format is\n   * required for certain cryptographic operations or interoperability.\n   *\n   * @example\n   * ```ts\n   * const compressedPublicKeyBytes = new Uint8Array([...]); // Replace with actual compressed public key bytes\n   * const decompressedPublicKey = await Secp256r1.decompressPublicKey({\n   *   publicKeyBytes: compressedPublicKeyBytes\n   * });\n   * ```\n   *\n   * @param params - The parameters for the public key decompression.\n   * @param params.publicKeyBytes - The public key as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the uncompressed public key as a Uint8Array.\n   */\n  public static async decompressPublicKey({ publicKeyBytes }: {\n    publicKeyBytes: Uint8Array;\n  }): Promise<Uint8Array> {\n    // Decode Weierstrass points from the public key byte array.\n    const point = secp256r1.Point.fromBytes(publicKeyBytes);\n\n    // Return the uncompressed form of the public key.\n    return point.toBytes(false);\n  }\n\n  /**\n   * Generates a secp256r1 private key in JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method creates a new private key suitable for use with the secp256r1\n   * elliptic curve. The key is generated using cryptographically secure random\n   * number generation to ensure its uniqueness and security. The resulting\n   * private key adheres to the JWK format, specifically tailored for secp256r1,\n   * making it compatible with common cryptographic standards and easy to use in\n   * various cryptographic processes.\n   *\n   * The private key generated by this method includes the following components:\n   * - `kty`: Key Type, set to 'EC' for Elliptic Curve.\n   * - `crv`: Curve Name, set to 'P-256'.\n   * - `d`: The private key component, base64url-encoded.\n   * - `x`: The x-coordinate of the public key point, derived from the private key, base64url-encoded.\n   * - `y`: The y-coordinate of the public key point, derived from the private key, base64url-encoded.\n   *\n   * The key is returned in a format suitable for direct use in signin and key agreement operations.\n   *\n   * @example\n   * ```ts\n   * const privateKey = await Secp256r1.generateKey();\n   * ```\n   *\n   * @returns A Promise that resolves to the generated private key in JWK format.\n   */\n  public static async generateKey(): Promise<Jwk> {\n    // Generate a random private key.\n    const privateKeyBytes = secp256r1.utils.randomSecretKey();\n\n    // Convert private key from bytes to JWK format.\n    const privateKey = await Secp256r1.bytesToPrivateKey({ privateKeyBytes });\n\n    // Compute the JWK thumbprint and set as the key ID.\n    privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n    return privateKey;\n  }\n\n  /**\n   * Retrieves the public key properties from a given private key in JWK format.\n   *\n   * @remarks\n   * This method extracts the public key portion from a secp256r1 private key in JWK format. It does\n   * so by removing the private key property 'd' and making a shallow copy, effectively yielding the\n   * public key. The method sets the 'kid' (key ID) property using the JWK thumbprint if it is not\n   * already defined. This approach is used under the assumption that a private key in JWK format\n   * always contains the corresponding public key properties.\n   *\n   * Note: This method offers a significant performance advantage, being about 200 times faster\n   * than `computePublicKey()`. However, it does not mathematically validate the private key, nor\n   * does it derive the public key from the private key. It simply extracts existing public key\n   * properties from the private key object. This makes it suitable for scenarios where speed is\n   * critical and the private key's integrity is already assured.\n   *\n   * @example\n   * ```ts\n   * const privateKey = { ... }; // A Jwk object representing a secp256r1 private key\n   * const publicKey = await Secp256r1.getPublicKey({ key: privateKey });\n   * ```\n   *\n   * @param params - The parameters for retrieving the public key properties.\n   * @param params.key - The private key in JWK format.\n   *\n   * @returns A Promise that resolves to the public key in JWK format.\n   */\n  public static async getPublicKey({ key }:\n    GetPublicKeyParams\n  ): Promise<Jwk> {\n    // Verify the provided JWK represents an elliptic curve (EC) secp256r1 private key.\n    if (!(isEcPrivateJwk(key) && key.crv === 'P-256')) {\n      throw new Error(`Secp256r1: The provided key is not a 'P-256' private JWK.`);\n    }\n\n    // Remove the private key property ('d') and make a shallow copy of the provided key.\n    const { d, ...publicKey } = key;\n\n    // If the key ID is undefined, set it to the JWK thumbprint.\n    publicKey.kid ??= await computeJwkThumbprint({ jwk: publicKey });\n\n    return publicKey;\n  }\n\n  /**\n   * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n   *\n   * @remarks\n   * This method takes a private key in JWK format and extracts its raw byte representation.\n   * It specifically focuses on the 'd' parameter of the JWK, which represents the private\n   * key component in base64url encoding. The method decodes this value into a byte array.\n   *\n   * This conversion is essential for operations that require the private key in its raw\n   * binary form, such as certain low-level cryptographic operations or when interfacing\n   * with systems and libraries that expect keys in a byte array format.\n   *\n   * @example\n   * ```ts\n   * const privateKey = { ... }; // An X25519 private key in JWK format\n   * const privateKeyBytes = await Secp256r1.privateKeyToBytes({ privateKey });\n   * ```\n   *\n   * @param params - The parameters for the private key conversion.\n   * @param params.privateKey - The private key in JWK format.\n   *\n   * @returns A Promise that resolves to the private key as a Uint8Array.\n   */\n  public static async privateKeyToBytes({ privateKey }: {\n    privateKey: Jwk;\n  }): Promise<Uint8Array> {\n    // Verify the provided JWK represents a valid EC P-256 private key.\n    if (!isEcPrivateJwk(privateKey)) {\n      throw new Error(`Secp256r1: The provided key is not a valid EC private key.`);\n    }\n\n    // Decode the provided private key to bytes.\n    const privateKeyBytes = Convert.base64Url(privateKey.d).toUint8Array();\n\n    return privateKeyBytes;\n  }\n\n  /**\n   * Converts a public key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n   *\n   * @remarks\n   * This method accepts a public key in JWK format and converts it into its raw binary\n   * form. The conversion process involves decoding the 'x' and 'y' parameters of the JWK\n   * (which represent the x and y coordinates of the elliptic curve point, respectively)\n   * from base64url format into a byte array. The method then concatenates these values,\n   * along with a prefix indicating the key format, to form the full public key.\n   *\n   * This function is particularly useful for use cases where the public key is needed\n   * in its raw byte format, such as for certain cryptographic operations or when\n   * interfacing with systems that require raw key formats.\n   *\n   * @example\n   * ```ts\n   * const publicKey = { ... }; // A Jwk public key object\n   * const publicKeyBytes = await Secp256r1.publicKeyToBytes({ publicKey });\n   * ```\n   *\n   * @param params - The parameters for the public key conversion.\n   * @param params.publicKey - The public key in JWK format.\n   *\n   * @returns A Promise that resolves to the public key as a Uint8Array.\n   */\n  public static async publicKeyToBytes({ publicKey }: {\n    publicKey: Jwk;\n  }): Promise<Uint8Array> {\n    // Verify the provided JWK represents a valid EC P-256 public key, which must have a 'y' value.\n    if (!(isEcPublicJwk(publicKey) && publicKey.y)) {\n      throw new Error(`Secp256r1: The provided key is not a valid EC public key.`);\n    }\n\n    // Decode the provided public key to bytes.\n    const prefix = new Uint8Array([0x04]); // Designates an uncompressed key.\n    const x = Convert.base64Url(publicKey.x).toUint8Array();\n    const y = Convert.base64Url(publicKey.y).toUint8Array();\n\n    // Concatenate the prefix, x-coordinate, and y-coordinate as a single byte array.\n    const publicKeyBytes = new Uint8Array([...prefix, ...x, ...y]);\n\n    return publicKeyBytes;\n  }\n\n  /**\n   * Computes an RFC6090-compliant Elliptic Curve Diffie-Hellman (ECDH) shared secret\n   * using secp256r1 private and public keys in JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method facilitates the ECDH key agreement protocol, which is a method of securely\n   * deriving a shared secret between two parties based on their private and public keys.\n   * It takes the private key of one party (privateKeyA) and the public key of another\n   * party (publicKeyB) to compute a shared secret. The shared secret is derived from the\n   * x-coordinate of the elliptic curve point resulting from the multiplication of the\n   * public key with the private key.\n   *\n   * Note: When performing Elliptic Curve Diffie-Hellman (ECDH) key agreement,\n   * the resulting shared secret is a point on the elliptic curve, which\n   * consists of an x-coordinate and a y-coordinate. With a 256-bit curve like\n   * secp256r1, each of these coordinates is 32 bytes (256 bits) long. However,\n   * in the ECDH process, it's standard practice to use only the x-coordinate\n   * of the shared secret point as the resulting shared key. This is because\n   * the y-coordinate does not add to the entropy of the key, and both parties\n   * can independently compute the x-coordinate.  Consquently, this implementation\n   * omits the y-coordinate for simplicity and standard compliance.\n   *\n   * @example\n   * ```ts\n   * const privateKeyA = { ... }; // A Jwk private key object for party A\n   * const publicKeyB = { ... }; // A Jwk public key object for party B\n   * const sharedSecret = await Secp256r1.sharedSecret({\n   *   privateKeyA,\n   *   publicKeyB\n   * });\n   * ```\n   *\n   * @param params - The parameters for the shared secret computation.\n   * @param params.privateKeyA - The private key in JWK format of one party.\n   * @param params.publicKeyB - The public key in JWK format of the other party.\n   *\n   * @returns A Promise that resolves to the computed shared secret as a Uint8Array.\n   */\n  public static async sharedSecret({ privateKeyA, publicKeyB }: {\n    privateKeyA: Jwk;\n    publicKeyB: Jwk;\n  }): Promise<Uint8Array> {\n    // Ensure that keys from the same key pair are not specified.\n    if ('x' in privateKeyA && 'x' in publicKeyB && privateKeyA.x === publicKeyB.x) {\n      throw new Error(`Secp256r1: ECDH shared secret cannot be computed from a single key pair's public and private keys.`);\n    }\n\n    // Convert the provided private and public keys to bytes.\n    const privateKeyABytes = await Secp256r1.privateKeyToBytes({ privateKey: privateKeyA });\n    const publicKeyBBytes = await Secp256r1.publicKeyToBytes({ publicKey: publicKeyB });\n\n    // Compute the compact representation shared secret between the public and private keys.\n    const sharedSecret = secp256r1.getSharedSecret(privateKeyABytes, publicKeyBBytes, true);\n\n    // Remove the leading byte that indicates the sign of the y-coordinate\n    // of the point on the elliptic curve.  See note above.\n    return sharedSecret.slice(1);\n  }\n\n  /**\n   * Generates an RFC6979-compliant ECDSA signature of given data using a secp256r1 private key.\n   *\n   * @remarks\n   * This method signs the provided data with a specified private key using the ECDSA\n   * (Elliptic Curve Digital Signature Algorithm) signature algorithm, as defined in RFC6979.\n   * The data to be signed is first hashed using the SHA-256 algorithm, and this hash is then\n   * signed using the private key. The output is a digital signature in the form of a\n   * Uint8Array, which uniquely corresponds to both the data and the private key used for signing.\n   *\n   * This method is commonly used in cryptographic applications to ensure data integrity and\n   * authenticity. The signature can later be verified by parties with access to the corresponding\n   * public key, ensuring that the data has not been tampered with and was indeed signed by the\n   * holder of the private key.\n   *\n   * @example\n   * ```ts\n   * const data = new TextEncoder().encode('Messsage'); // Data to be signed\n   * const privateKey = { ... }; // A Jwk object representing a secp256r1 private key\n   * const signature = await Secp256r1.sign({\n   *   key: privateKey,\n   *   data\n   * });\n   * ```\n   *\n   * @param params - The parameters for the signing operation.\n   * @param params.key - The private key to use for signing, represented in JWK format.\n   * @param params.data - The data to sign, represented as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the signature as a Uint8Array.\n   */\n  public static async sign({ data, key }:\n    SignParams\n  ): Promise<Uint8Array> {\n    // Convert the private key from JWK format to bytes.\n    const privateKeyBytes = await Secp256r1.privateKeyToBytes({ privateKey: key });\n\n    // Generate a digest of the data using the SHA-256 hash function.\n    const digest = sha256(data);\n\n    // Sign the provided data using the ECDSA algorithm.\n    // The `Secp256r1.sign` operation returns a signature object with { r, s, recovery } properties.\n    const signature = secp256r1.sign(digest, privateKeyBytes, { prehash: false });\n\n    return signature;\n  }\n\n  /**\n   * Validates a given private key to ensure its compliance with the secp256r1 curve standards.\n   *\n   * @remarks\n   * This method checks whether a provided private key is a valid 32-byte number and falls within\n   * the range defined by the secp256r1 curve's order. It is essential for ensuring the private\n   * key's mathematical correctness in the context of secp256r1-based cryptographic operations.\n   *\n   * Note that this validation strictly pertains to the key's format and numerical validity; it does\n   * not assess whether the key corresponds to a known entity or its security status (e.g., whether\n   * it has been compromised).\n   *\n   * @example\n   * ```ts\n   * const privateKeyBytes = new Uint8Array([...]); // A 32-byte private key\n   * const isValid = await Secp256r1.validatePrivateKey({ privateKeyBytes });\n   * console.log(isValid); // true or false based on the key's validity\n   * ```\n   *\n   * @param params - The parameters for the key validation.\n   * @param params.privateKeyBytes - The private key to validate, represented as a Uint8Array.\n   *\n   * @returns A Promise that resolves to a boolean indicating whether the private key is valid.\n   */\n  public static async validatePrivateKey({ privateKeyBytes }: {\n    privateKeyBytes: Uint8Array;\n  }): Promise<boolean> {\n    return secp256r1.utils.isValidSecretKey(privateKeyBytes);\n  }\n\n  /**\n   * Validates a given public key to confirm its mathematical correctness on the secp256r1 curve.\n   *\n   * @remarks\n   * This method checks if the provided public key represents a valid point on the secp256r1 curve.\n   * It decodes the key's Weierstrass points (x and y coordinates) and verifies their validity\n   * against the curve's parameters. A valid point must lie on the curve and meet specific\n   * mathematical criteria defined by the curve's equation.\n   *\n   * It's important to note that this method does not verify the key's ownership or whether it has\n   * been compromised; it solely focuses on the key's adherence to the curve's mathematical\n   * principles.\n   *\n   * @example\n   * ```ts\n   * const publicKeyBytes = new Uint8Array([...]); // A public key in byte format\n   * const isValid = await Secp256r1.validatePublicKey({ publicKeyBytes });\n   * console.log(isValid); // true if the key is valid on the secp256r1 curve, false otherwise\n   * ```\n   *\n   * @param params - The parameters for the key validation.\n   * @param params.publicKeyBytes - The public key to validate, represented as a Uint8Array.\n   *\n   * @returns A Promise that resolves to a boolean indicating the public key's validity on\n   *          the secp256r1 curve.\n   */\n  public static async validatePublicKey({ publicKeyBytes }: {\n    publicKeyBytes: Uint8Array;\n  }): Promise<boolean> {\n    try {\n      // Decode Weierstrass points from key bytes.\n      const point = secp256r1.Point.fromBytes(publicKeyBytes);\n\n      // Check if points are on the Short Weierstrass curve.\n      point.assertValidity();\n\n    } catch {\n      return false;\n    }\n\n    return true;\n  }\n\n  /**\n   * Verifies an RFC6979-compliant ECDSA signature against given data and a secp256r1 public key.\n   *\n   * @remarks\n   * This method validates a digital signature to ensure that it was generated by the holder of the\n   * corresponding private key and that the signed data has not been altered. The signature\n   * verification is performed using the ECDSA (Elliptic Curve Digital Signature Algorithm) as\n   * specified in RFC6979. The data to be verified is first hashed using the SHA-256 algorithm, and\n   * this hash is then used along with the public key to verify the signature.\n   *\n   * The method returns a boolean value indicating whether the signature is valid. A valid signature\n   * proves that the signed data was indeed signed by the owner of the private key corresponding to\n   * the provided public key and that the data has not been tampered with since it was signed.\n   *\n   * Note: The verification process does not consider the malleability of low-s signatures, which\n   * may be relevant in certain contexts, such as Bitcoin transactions.\n   *\n   * @example\n   * ```ts\n   * const data = new TextEncoder().encode('Messsage'); // Data that was signed\n   * const publicKey = { ... }; // Public key in JWK format corresponding to the private key that signed the data\n   * const signature = new Uint8Array([...]); // Signature to verify\n   * const isSignatureValid = await Secp256r1.verify({\n   *   key: publicKey,\n   *   signature,\n   *   data\n   * });\n   * console.log(isSignatureValid); // true if the signature is valid, false otherwise\n   * ```\n   *\n   * @param params - The parameters for the signature verification.\n   * @param params.key - The public key used for verification, represented in JWK format.\n   * @param params.signature - The signature to verify, represented as a Uint8Array.\n   * @param params.data - The data that was signed, represented as a Uint8Array.\n   *\n   * @returns A Promise that resolves to a boolean indicating whether the signature is valid.\n   */\n  public static async verify({ key, signature, data }:\n    VerifyParams\n  ): Promise<boolean> {\n    // Convert the public key from JWK format to bytes.\n    const publicKeyBytes = await Secp256r1.publicKeyToBytes({ publicKey: key });\n\n    // Generate a digest of the data using the SHA-256 hash function.\n    const digest = sha256(data);\n\n    /** Perform the verification of the signature.\n     * This verify operation has the malleability check disabled. Guaranteed support\n     * for low-s signatures across languages is unlikely especially in the context\n     * of SSI. Notable Cloud KMS providers do not natively support it either. It is\n     * also worth noting that low-s signatures are a requirement for Bitcoin. */\n    const isValid = secp256r1.verify(signature, digest, publicKeyBytes, { lowS: false, prehash: false });\n\n    return isValid;\n  }\n\n  /**\n   * Returns the elliptic curve point (x and y coordinates) for a given secp256r1 key.\n   *\n   * @remarks\n   * This method extracts the elliptic curve point from a given secp256r1 key, whether\n   * it's a private or a public key. For a private key, the method first computes the\n   * corresponding public key and then extracts the x and y coordinates. For a public key,\n   * it directly returns these coordinates. The coordinates are represented as Uint8Array.\n   *\n   * The x and y coordinates represent the key's position on the elliptic curve and can be\n   * used in various cryptographic operations, such as digital signatures or key agreement\n   * protocols.\n   *\n   * @example\n   * ```ts\n   * // For a private key\n   * const privateKey = new Uint8Array([...]); // A 32-byte private key\n   * const { x: xFromPrivateKey, y: yFromPrivateKey } = await Secp256r1.getCurvePoint({ keyBytes: privateKey });\n   *\n   * // For a public key\n   * const publicKey = new Uint8Array([...]); // A 33-byte or 65-byte public key\n   * const { x: xFromPublicKey, y: yFromPublicKey } = await Secp256r1.getCurvePoint({ keyBytes: publicKey });\n   * ```\n   *\n   * @param params - The parameters for the curve point decoding operation.\n   * @param params.keyBytes - The key for which to get the elliptic curve point.\n   *                          Can be either a private key or a public key.\n   *                          The key should be passed as a `Uint8Array`.\n   *\n   * @returns A Promise that resolves to an object with properties 'x' and 'y',\n   *          each being a Uint8Array representing the x and y coordinates of the key point on the\n   *          elliptic curve.\n   */\n  private static async getCurvePoint({ keyBytes }: {\n    keyBytes: Uint8Array;\n  }): Promise<AffinePoint<Uint8Array>> {\n    // If key is a private key, first compute the public key.\n    if (keyBytes.byteLength === 32) {\n      keyBytes = secp256r1.getPublicKey(keyBytes);\n    }\n\n    // Decode Weierstrass affine point from key bytes.\n    const point = secp256r1.Point.fromBytes(keyBytes);\n\n    // Get x- and y-coordinate values and convert to Uint8Array.\n    const x = numberToBytesBE(point.x, 32);\n    const y = numberToBytesBE(point.y, 32);\n\n    return { x, y };\n  }\n}\n\nexport { Secp256r1 as P256 };\n", "import type { AsymmetricKeyGenerator } from '../types/key-generator.js';\nimport type { Jwk } from '../jose/jwk.js';\nimport type { Signer } from '../types/signer.js';\nimport type { AsymmetricKeyConverter, KeyConverter } from '../types/key-converter.js';\nimport type {\n  BytesToPrivateKeyParams,\n  BytesToPublicKeyParams,\n  ComputePublicKeyParams,\n  GenerateKeyParams,\n  GetPublicKeyParams,\n  PrivateKeyToBytesParams,\n  PublicKeyToBytesParams,\n  SignParams,\n  VerifyParams,\n} from '../types/params-direct.js';\n\nimport { CryptoAlgorithm } from './crypto-algorithm.js';\nimport { Secp256k1 } from '../primitives/secp256k1.js';\nimport { Secp256r1 } from '../primitives/secp256r1.js';\nimport { CryptoError, CryptoErrorCode } from '../crypto-error.js';\nimport { isEcPrivateJwk, isEcPublicJwk } from '../jose/jwk.js';\n\n/**\n * The `EcdsaGenerateKeyParams` interface defines the algorithm-specific parameters that should be\n * passed into the `generateKey()` method when using the ECDSA algorithm.\n */\nexport interface EcdsaGenerateKeyParams extends GenerateKeyParams {\n  /**\n   * A string defining the type of key to generate. The value must be one of the following:\n   * - `\"ES256\"`: ECDSA using the secp256r1 (P-256) curve and SHA-256.\n   * - `\"ES256K\"`: ECDSA using the secp256k1 curve and SHA-256.\n   * - `\"secp256k1\"`: ECDSA using the secp256k1 curve and SHA-256.\n   * - `\"secp256r1\"`: ECDSA using the secp256r1 (P-256) curve and SHA-256.\n   */\n  algorithm: 'ES256' | 'ES256K' | 'secp256k1' | 'secp256r1';\n}\n\n/**\n * The `EcdsaAlgorithm` class provides a concrete implementation for cryptographic operations using\n * the Elliptic Curve Digital Signature Algorithm (ECDSA). This class implements both\n * {@link Signer | `Signer`} and { @link AsymmetricKeyGenerator | `AsymmetricKeyGenerator`}\n * interfaces, providing private key generation, public key derivation, and creation/verification\n * of signatures.\n *\n * This class is typically accessed through implementations that extend the\n * {@link DsaApi | `DsaApi`} interface.\n */\nexport class EcdsaAlgorithm extends CryptoAlgorithm\n  implements AsymmetricKeyGenerator<EcdsaGenerateKeyParams, Jwk, GetPublicKeyParams>,\n             KeyConverter, AsymmetricKeyConverter,\n             Signer<SignParams, VerifyParams> {\n\n  /**\n   * Converts a private key from a byte array to JWK format, setting the `alg` property based on\n   * the algorithm.\n   *\n   * @param params - The parameters for the private key conversion.\n   * @param params.algorithm - The ECDSA algorithm identifier.\n   * @param params.privateKeyBytes - The raw private key as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the private key in JWK format.\n   */\n  public async bytesToPrivateKey({ algorithm, privateKeyBytes }:\n    BytesToPrivateKeyParams & { algorithm: 'ES256' | 'ES256K' | 'secp256k1' | 'secp256r1' }\n  ): Promise<Jwk> {\n    switch (algorithm) {\n\n      case 'ES256K':\n      case 'secp256k1': {\n        const privateKey = await Secp256k1.bytesToPrivateKey({ privateKeyBytes });\n        privateKey.alg = 'ES256K';\n        return privateKey;\n      }\n\n      case 'ES256':\n      case 'secp256r1': {\n        const privateKey = await Secp256r1.bytesToPrivateKey({ privateKeyBytes });\n        privateKey.alg = 'ES256';\n        return privateKey;\n      }\n\n      default: {\n        throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Algorithm not supported: ${algorithm}`);\n      }\n    }\n  }\n\n  /**\n   * Converts a public key from a byte array to JWK format, setting the `alg` property based on\n   * the algorithm.\n   *\n   * @param params - The parameters for the public key conversion.\n   * @param params.algorithm - The ECDSA algorithm identifier.\n   * @param params.publicKeyBytes - The raw public key as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the public key in JWK format.\n   */\n  public async bytesToPublicKey({ algorithm, publicKeyBytes }:\n    BytesToPublicKeyParams & { algorithm: 'ES256' | 'ES256K' | 'secp256k1' | 'secp256r1' }\n  ): Promise<Jwk> {\n    switch (algorithm) {\n\n      case 'ES256K':\n      case 'secp256k1': {\n        const publicKey = await Secp256k1.bytesToPublicKey({ publicKeyBytes });\n        publicKey.alg = 'ES256K';\n        return publicKey;\n      }\n\n      case 'ES256':\n      case 'secp256r1': {\n        const publicKey = await Secp256r1.bytesToPublicKey({ publicKeyBytes });\n        publicKey.alg = 'ES256';\n        return publicKey;\n      }\n\n      default: {\n        throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Algorithm not supported: ${algorithm}`);\n      }\n    }\n  }\n\n  /**\n   * Derives the public key in JWK format from a given private key.\n   *\n   * @remarks\n   * This method takes a private key in JWK format and derives its corresponding public key,\n   * also in JWK format. The process ensures that the derived public key correctly corresponds to\n   * the given private key.\n   *\n   * @example\n   * ```ts\n   * const ecdsa = new EcdsaAlgorithm();\n   * const privateKey = { ... }; // A Jwk object representing a private key\n   * const publicKey = await ecdsa.computePublicKey({ key: privateKey });\n   * ```\n   *\n   * @param params - The parameters for the public key derivation.\n   * @param params.key - The private key in JWK format from which to derive the public key.\n   *\n   * @returns A Promise that resolves to the derived public key in JWK format.\n   */\n  public async computePublicKey({ key }:\n    ComputePublicKeyParams\n  ): Promise<Jwk> {\n    if (!isEcPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be an elliptic curve (EC) private key.');}\n\n    switch (key.crv) {\n\n      case 'secp256k1': {\n        const publicKey = await Secp256k1.computePublicKey({ key });\n        publicKey.alg = 'ES256K';\n        return publicKey;\n      }\n\n      case 'P-256': {\n        const publicKey = await Secp256r1.computePublicKey({ key });\n        publicKey.alg = 'ES256';\n        return publicKey;\n      }\n\n      default: {\n        throw new Error(`Unsupported curve: ${key.crv}`);\n      }\n    }\n  }\n\n  /**\n   * Generates a new private key with the specified algorithm in JSON Web Key (JWK) format.\n   *\n   * @example\n   * ```ts\n   * const ecdsa = new EcdsaAlgorithm();\n   * const privateKey = await ecdsa.generateKey({ algorithm: 'ES256K' });\n   * ```\n   *\n   * @param params - The parameters for key generation.\n   * @param params.algorithm - The algorithm to use for key generation.\n   *\n   * @returns A Promise that resolves to the generated private key in JWK format.\n   */\n  public async generateKey({ algorithm }:\n    EcdsaGenerateKeyParams\n  ): Promise<Jwk> {\n    switch (algorithm) {\n\n      case 'ES256K':\n      case 'secp256k1': {\n        const privateKey = await Secp256k1.generateKey();\n        privateKey.alg = 'ES256K';\n        return privateKey;\n      }\n\n      case 'ES256':\n      case 'secp256r1': {\n        const privateKey = await Secp256r1.generateKey();\n        privateKey.alg = 'ES256';\n        return privateKey;\n      }\n    }\n  }\n\n  /**\n   * Retrieves the public key properties from a given private key in JWK format.\n   *\n   * @remarks\n   * This method extracts the public key portion from an ECDSA private key in JWK format. It does\n   * so by removing the private key property 'd' and making a shallow copy, effectively yielding the\n   * public key.\n   *\n   * Note: This method offers a significant performance advantage, being about 200 times faster\n   * than `computePublicKey()`. However, it does not mathematically validate the private key, nor\n   * does it derive the public key from the private key. It simply extracts existing public key\n   * properties from the private key object. This makes it suitable for scenarios where speed is\n   * critical and the private key's integrity is already assured.\n   *\n   * @example\n   * ```ts\n   * const ecdsa = new EcdsaAlgorithm();\n   * const privateKey = { ... }; // A Jwk object representing a private key\n   * const publicKey = await ecdsa.getPublicKey({ key: privateKey });\n   * ```\n   *\n   * @param params - The parameters for retrieving the public key properties.\n   * @param params.key - The private key in JWK format.\n   *\n   * @returns A Promise that resolves to the public key in JWK format.\n   */\n  public async getPublicKey({ key }:\n    GetPublicKeyParams\n  ): Promise<Jwk> {\n    if (!isEcPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be an elliptic curve (EC) private key.');}\n\n    switch (key.crv) {\n\n      case 'secp256k1': {\n        const publicKey = await Secp256k1.getPublicKey({ key });\n        publicKey.alg = 'ES256K';\n        return publicKey;\n      }\n\n      case 'P-256': {\n        const publicKey = await Secp256r1.getPublicKey({ key });\n        publicKey.alg = 'ES256';\n        return publicKey;\n      }\n\n      default: {\n        throw new Error(`Unsupported curve: ${key.crv}`);\n      }\n    }\n  }\n\n  /**\n   * Generates an ECDSA signature of given data using a private key.\n   *\n   * @remarks\n   * This method uses the signature algorithm determined by the given `algorithm` to sign the\n   * provided data.\n   *\n   * The signature can later be verified by parties with access to the corresponding\n   * public key, ensuring that the data has not been tampered with and was indeed signed by the\n   * holder of the private key.\n   *\n   * @example\n   * ```ts\n   * const ecdsa = new EcdsaAlgorithm();\n   * const data = new TextEncoder().encode('Message');\n   * const privateKey = { ... }; // A Jwk object representing a private key\n   * const signature = await ecdsa.sign({\n   *   key: privateKey,\n   *   data\n   * });\n   * ```\n   *\n   * @param params - The parameters for the signing operation.\n   * @param params.key - The private key to use for signing, represented in JWK format.\n   * @param params.data - The data to sign.\n   *\n   * @returns A Promise resolving to the digital signature as a `Uint8Array`.\n   */\n  public async sign({ key, data }:\n    SignParams\n  ): Promise<Uint8Array> {\n    if (!isEcPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be an elliptic curve (EC) private key.');}\n\n    switch (key.crv) {\n\n      case 'secp256k1': {\n        return await Secp256k1.sign({ key, data });\n      }\n\n      case 'P-256': {\n        return await Secp256r1.sign({ key, data });\n      }\n\n      default: {\n        throw new Error(`Unsupported curve: ${key.crv}`);\n      }\n    }\n  }\n\n  /**\n   * Verifies an ECDSA signature associated with the provided data using the provided key.\n   *\n   * @remarks\n   * This method uses the signature algorithm determined by the `crv` property of the provided key\n   * to check the validity of a digital signature against the original data. It confirms whether the\n   * signature was created by the holder of the corresponding private key and that the data has not\n   * been tampered with.\n   *s\n   * @example\n   * ```ts\n   * const ecdsa = new EcdsaAlgorithm();\n   * const publicKey = { ... }; // Public key in JWK format corresponding to the private key that signed the data\n   * const signature = new Uint8Array([...]); // Signature to verify\n   * const data = new TextEncoder().encode('Message');\n   * const isValid = await ecdsa.verify({\n   *   key: publicKey,\n   *   signature,\n   *   data\n   * });\n   * ```\n   *\n   * @param params - The parameters for the verification operation.\n   * @param params.key - The key to use for verification.\n   * @param params.signature - The signature to verify.\n   * @param params.data - The data to verify.\n   *\n   * @returns A Promise resolving to a boolean indicating whether the signature is valid.\n   */\n  public async verify({ key, signature, data }:\n    VerifyParams\n  ): Promise<boolean> {\n    if (!isEcPublicJwk(key)) {throw new TypeError('Invalid key provided. Must be an elliptic curve (EC) public key.');}\n\n    switch (key.crv) {\n\n      case 'secp256k1': {\n        return await Secp256k1.verify({ key, signature, data });\n      }\n\n      case 'P-256': {\n        return await Secp256r1.verify({ key, signature, data });\n      }\n\n      default: {\n        throw new Error(`Unsupported curve: ${key.crv}`);\n      }\n    }\n  }\n\n  /**\n   * Converts a private key from JWK format to a byte array.\n   *\n   * @param params - The parameters for the private key conversion.\n   * @param params.privateKey - The private key in JWK format.\n   *\n   * @returns A Promise that resolves to the private key as a Uint8Array.\n   */\n  public async privateKeyToBytes({ privateKey }:\n    PrivateKeyToBytesParams\n  ): Promise<Uint8Array> {\n    switch (privateKey.crv) {\n\n      case 'secp256k1': {\n        return await Secp256k1.privateKeyToBytes({ privateKey });\n      }\n\n      case 'P-256': {\n        return await Secp256r1.privateKeyToBytes({ privateKey });\n      }\n\n      default: {\n        throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Curve not supported: ${privateKey.crv}`);\n      }\n    }\n  }\n\n  /**\n   * Converts a public key from JWK format to a byte array.\n   *\n   * @param params - The parameters for the public key conversion.\n   * @param params.publicKey - The public key in JWK format.\n   *\n   * @returns A Promise that resolves to the public key as a Uint8Array.\n   */\n  public async publicKeyToBytes({ publicKey }:\n    PublicKeyToBytesParams\n  ): Promise<Uint8Array> {\n    switch (publicKey.crv) {\n\n      case 'secp256k1': {\n        return await Secp256k1.publicKeyToBytes({ publicKey });\n      }\n\n      case 'P-256': {\n        return await Secp256r1.publicKeyToBytes({ publicKey });\n      }\n\n      default: {\n        throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Curve not supported: ${publicKey.crv}`);\n      }\n    }\n  }\n}", "/**\n * Twisted Edwards curve. The formula is: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2.\n * For design rationale of types / exports, see weierstrass module documentation.\n * Untwisted Edwards curves exist, but they aren't used in real-world protocols.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n  abool,\n  abytes,\n  aInRange,\n  asafenumber,\n  bytesToHex,\n  bytesToNumberLE,\n  concatBytes,\n  copyBytes,\n  hexToBytes,\n  isBytes,\n  notImplemented,\n  validateObject,\n  randomBytes as wcRandomBytes,\n  type FHash,\n  type Signer,\n  type TArg,\n  type TRet,\n} from '../utils.ts';\nimport {\n  createCurveFields,\n  createKeygen,\n  normalizeZ,\n  wNAF,\n  type AffinePoint,\n  type CurveLengths,\n  type CurvePoint,\n  type CurvePointCons,\n} from './curve.ts';\nimport { type IField } from './modular.ts';\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), _8n = /* @__PURE__ */ BigInt(8);\n\n/** Extended Edwards point with X/Y/Z/T coordinates. */\nexport interface EdwardsPoint extends CurvePoint<bigint, EdwardsPoint> {\n  /** extended X coordinate. Different from affine x. */\n  readonly X: bigint;\n  /** extended Y coordinate. Different from affine y. */\n  readonly Y: bigint;\n  /** extended Z coordinate */\n  readonly Z: bigint;\n  /** extended T coordinate */\n  readonly T: bigint;\n}\n/** Constructor and decoding helpers for extended Edwards points. */\nexport interface EdwardsPointCons extends CurvePointCons<EdwardsPoint> {\n  /** Create a point from extended X/Y/Z/T coordinates without validation. */\n  new (X: bigint, Y: bigint, Z: bigint, T: bigint): EdwardsPoint;\n  /**\n   * Return the curve parameters used by this point constructor.\n   * @returns Curve parameters.\n   */\n  CURVE(): EdwardsOpts;\n  /**\n   * Decode a point from bytes, optionally using ZIP-215 rules.\n   * @param bytes - Encoded point bytes.\n   * @param zip215 - Whether to accept ZIP-215 encodings.\n   * @returns Decoded Edwards point.\n   */\n  fromBytes(bytes: Uint8Array, zip215?: boolean): EdwardsPoint;\n  /**\n   * Decode a point from hex, optionally using ZIP-215 rules.\n   * @param hex - Encoded point hex.\n   * @param zip215 - Whether to accept ZIP-215 encodings.\n   * @returns Decoded Edwards point.\n   */\n  fromHex(hex: string, zip215?: boolean): EdwardsPoint;\n}\n\n/**\n * Twisted Edwards curve options.\n *\n * * a: formula param\n * * d: formula param\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. h*n is group order; n is subgroup order\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type EdwardsOpts = Readonly<{\n  /** Base-field modulus. */\n  p: bigint;\n  /** Prime subgroup order. */\n  n: bigint;\n  /** Curve cofactor. */\n  h: bigint;\n  /** Edwards curve parameter `a`. */\n  a: bigint;\n  /** Edwards curve parameter `d`. */\n  d: bigint;\n  /** Generator x coordinate. */\n  Gx: bigint;\n  /** Generator y coordinate. */\n  Gy: bigint;\n}>;\n\n/**\n * Extra curve options for Twisted Edwards.\n *\n * * Fp: redefined Field over curve.p\n * * Fn: redefined Field over curve.n\n * * uvRatio: helper function for decompression, calculating \u221A(u/v)\n */\nexport type EdwardsExtraOpts = Partial<{\n  /** Optional base-field override. */\n  Fp: IField<bigint>;\n  /** Optional scalar-field override. */\n  Fn: IField<bigint>;\n  /** Whether field encodings are little-endian. */\n  FpFnLE: boolean;\n  /** Square-root ratio helper used during point decompression. */\n  uvRatio: (u: bigint, v: bigint) => { isValid: boolean; value: bigint };\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) options.\n *\n * * hash: hash function used to hash secret keys and messages\n * * adjustScalarBytes: clears bits to get valid field element\n * * domain: Used for hashing\n * * mapToCurve: for hash-to-curve standard\n * * prehash: RFC 8032 pre-hashing of messages to sign() / verify()\n * * randomBytes: function generating random bytes, used for randomSecretKey\n */\nexport type EdDSAOpts = Partial<{\n  /** Clamp or otherwise normalize secret-scalar bytes before reducing mod `n`. */\n  adjustScalarBytes: (bytes: TArg<Uint8Array>) => TRet<Uint8Array>;\n  /** Domain-separation helper for contexts and prehash mode. */\n  domain: (data: TArg<Uint8Array>, ctx: TArg<Uint8Array>, phflag: boolean) => TRet<Uint8Array>;\n  /** Optional hash-to-curve mapper for protocols like Ristretto hash-to-group. */\n  mapToCurve: (scalar: bigint[]) => AffinePoint<bigint>;\n  /** Optional prehash function used before signing or verifying messages. */\n  prehash: FHash;\n  /** Default verification decoding policy. ZIP-215 is more permissive than RFC 8032 / NIST. */\n  zip215: boolean;\n  /** RNG override used by helper constructors. */\n  randomBytes: (bytesLength?: number) => TRet<Uint8Array>;\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) helper namespace.\n * Allows creating and verifying signatures, and deriving public keys.\n */\nexport interface EdDSA {\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   * @returns Encoded public key.\n   */\n  getPublicKey: (secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;\n  /**\n   * Sign a message with an EdDSA secret key.\n   * @param message - Message bytes.\n   * @param secretKey - Secret key bytes.\n   * @param options - Optional signature tweaks:\n   *   - `context` (optional): Domain-separation context for Ed25519ctx/Ed448.\n   * @returns Encoded signature bytes.\n   */\n  sign: (\n    message: TArg<Uint8Array>,\n    secretKey: TArg<Uint8Array>,\n    options?: TArg<{ context?: Uint8Array }>\n  ) => TRet<Uint8Array>;\n  /**\n   * Verify a signature against a message and public key.\n   * @param sig - Encoded signature bytes.\n   * @param message - Message bytes.\n   * @param publicKey - Encoded public key.\n   * @param options - Optional verification tweaks:\n   *   - `context` (optional): Domain-separation context for Ed25519ctx/Ed448.\n   *   - `zip215` (optional): Whether to accept ZIP-215 encodings.\n   * @returns Whether the signature is valid.\n   */\n  verify: (\n    sig: TArg<Uint8Array>,\n    message: TArg<Uint8Array>,\n    publicKey: TArg<Uint8Array>,\n    options?: TArg<{ context?: Uint8Array; zip215?: boolean }>\n  ) => boolean;\n  /** Point constructor used by this signature scheme. */\n  Point: EdwardsPointCons;\n  /** Helper utilities for key validation and Montgomery conversion. */\n  utils: {\n    /**\n     * Generate a valid random secret key.\n     * Optional seed bytes are only length-checked and returned unchanged.\n     */\n    randomSecretKey: (seed?: TArg<Uint8Array>) => TRet<Uint8Array>;\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>, zip215?: boolean) => boolean;\n\n    /**\n     * Converts ed public key to x public key.\n     *\n     * There is NO `fromMontgomery`:\n     * - There are 2 valid ed25519 points for every x25519, with flipped coordinate\n     * - Sometimes there are 0 valid ed25519 points, because x25519 *additionally*\n     *   accepts inputs on the quadratic twist, which can't be moved to ed25519\n     *\n     * @example\n     * Converts ed public key to x public key.\n     *\n     * ```js\n     * const someonesPub_ed = ed25519.getPublicKey(ed25519.utils.randomSecretKey());\n     * const someonesPub = ed25519.utils.toMontgomery(someonesPub);\n     * const aPriv = x25519.utils.randomSecretKey();\n     * const shared = x25519.getSharedSecret(aPriv, someonesPub)\n     * ```\n     */\n    toMontgomery: (publicKey: TArg<Uint8Array>) => TRet<Uint8Array>;\n    /**\n     * Converts ed secret key to x secret key.\n     * @example\n     * Converts ed secret key to x secret key.\n     *\n     * ```js\n     * const someonesPub = x25519.getPublicKey(x25519.utils.randomSecretKey());\n     * const aPriv_ed = ed25519.utils.randomSecretKey();\n     * const aPriv = ed25519.utils.toMontgomerySecret(aPriv_ed);\n     * const shared = x25519.getSharedSecret(aPriv, someonesPub)\n     * ```\n     */\n    toMontgomerySecret: (secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;\n    /** Return the expanded private key components used by RFC8032 signing. */\n    getExtendedPublicKey: (key: TArg<Uint8Array>) => {\n      head: TRet<Uint8Array>;\n      prefix: TRet<Uint8Array>;\n      scalar: bigint;\n      point: EdwardsPoint;\n      pointBytes: TRet<Uint8Array>;\n    };\n  };\n  /** Byte lengths for keys and signatures exposed by this scheme. */\n  lengths: CurveLengths;\n}\n\n// Affine Edwards-equation check only; this does not prove subgroup membership, canonical\n// encoding, prime-order base-point requirements, or identity exclusion.\nfunction isEdValidXY(Fp: TArg<IField<bigint>>, CURVE: EdwardsOpts, x: bigint, y: bigint): boolean {\n  const x2 = Fp.sqr(x);\n  const y2 = Fp.sqr(y);\n  const left = Fp.add(Fp.mul(CURVE.a, x2), y2);\n  const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));\n  return Fp.eql(left, right);\n}\n\n/**\n * @param params - Curve parameters. See {@link EdwardsOpts}.\n * @param extraOpts - Optional helpers and overrides. See {@link EdwardsExtraOpts}.\n * @returns Edwards point constructor. Generator validation here only checks\n *   that `(Gx, Gy)` satisfies the affine Edwards equation.\n *   RFC 8032 base-point constraints like `B != (0,1)` and `[L]B = 0`\n *   are left to the caller's chosen parameters, since eager subgroup\n *   validation here adds about 10-15ms to heavyweight imports like ed448.\n *   The returned constructor also eagerly marks `Point.BASE` for W=8\n *   precompute caching. Some code paths still assume\n *   `Fp.BYTES === Fn.BYTES`, so mismatched byte lengths are not fully audited here.\n * @throws If the curve parameters or Edwards overrides are invalid. {@link Error}\n * @example\n * ```ts\n * import { edwards } from '@noble/curves/abstract/edwards.js';\n * import { jubjub } from '@noble/curves/misc.js';\n * // Build a point constructor from explicit curve parameters, then use its base point.\n * const Point = edwards(jubjub.Point.CURVE());\n * Point.BASE.toHex();\n * ```\n */\nexport function edwards(\n  params: TArg<EdwardsOpts>,\n  extraOpts: TArg<EdwardsExtraOpts> = {}\n): EdwardsPointCons {\n  const opts = extraOpts as EdwardsExtraOpts;\n  const validated = createCurveFields('edwards', params as EdwardsOpts, opts, opts.FpFnLE);\n  const { Fp, Fn } = validated;\n  let CURVE = validated.CURVE as EdwardsOpts;\n  const { h: cofactor } = CURVE;\n  validateObject(opts, {}, { uvRatio: 'function' });\n\n  // Important:\n  // There are some places where Fp.BYTES is used instead of nByteLength.\n  // So far, everything has been tested with curves of Fp.BYTES == nByteLength.\n  // TODO: test and find curves which behave otherwise.\n  const MASK = _2n << (BigInt(Fn.BYTES * 8) - _1n);\n  const modP = (n: bigint) => Fp.create(n); // Function overrides\n\n  // sqrt(u/v)\n  const uvRatio =\n    opts.uvRatio === undefined\n      ? (u: bigint, v: bigint) => {\n          try {\n            return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };\n          } catch (e) {\n            return { isValid: false, value: _0n };\n          }\n        }\n      : opts.uvRatio;\n\n  // Validate whether the passed curve params are valid.\n  // equation ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2 should work for generator point.\n  if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))\n    throw new Error('bad curve params: generator point');\n\n  /**\n   * Asserts coordinate is valid: 0 <= n < MASK.\n   * Coordinates >= Fp.ORDER are allowed for zip215.\n   */\n  function acoord(title: string, n: bigint, banZero = false) {\n    const min = banZero ? _1n : _0n;\n    aInRange('coordinate ' + title, n, min, MASK);\n    return n;\n  }\n\n  function aedpoint(other: unknown) {\n    if (!(other instanceof Point)) throw new Error('EdwardsPoint expected');\n  }\n\n  // Extended Point works in extended coordinates: (X, Y, Z, T) \u220B (x=X/Z, y=Y/Z, T=xy).\n  // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n  class Point implements EdwardsPoint {\n    // base / generator point\n    static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n    // zero / infinity / identity point\n    static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n    // math field\n    static readonly Fp = Fp;\n    // scalar field\n    static readonly Fn = Fn;\n\n    readonly X: bigint;\n    readonly Y: bigint;\n    readonly Z: bigint;\n    readonly T: bigint;\n\n    constructor(X: bigint, Y: bigint, Z: bigint, T: bigint) {\n      this.X = acoord('x', X);\n      this.Y = acoord('y', Y);\n      this.Z = acoord('z', Z, true);\n      this.T = acoord('t', T);\n      Object.freeze(this);\n    }\n\n    static CURVE(): EdwardsOpts {\n      return CURVE;\n    }\n\n    /**\n     * Create one extended Edwards point from affine coordinates.\n     * Does NOT validate that the point is on-curve or torsion-free.\n     * Use `.assertValidity()` on adversarial inputs.\n     */\n    static fromAffine(p: AffinePoint<bigint>): Point {\n      if (p instanceof Point) throw new Error('extended point not allowed');\n      const { x, y } = p || {};\n      acoord('x', x);\n      acoord('y', y);\n      return new Point(x, y, _1n, modP(x * y));\n    }\n\n    // Uses algo from RFC8032 5.1.3.\n    static fromBytes(bytes: Uint8Array, zip215 = false): Point {\n      const len = Fp.BYTES;\n      const { a, d } = CURVE;\n      bytes = copyBytes(abytes(bytes, len, 'point'));\n      abool(zip215, 'zip215');\n      const normed = copyBytes(bytes); // copy again, we'll manipulate it\n      const lastByte = bytes[len - 1]; // select last byte\n      normed[len - 1] = lastByte & ~0x80; // clear last bit\n      const y = bytesToNumberLE(normed);\n\n      // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n      // RFC8032 prohibits >= p, but ZIP215 doesn't\n      // zip215=true:  0 <= y < MASK (2^256 for ed25519)\n      // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n      const max = zip215 ? MASK : Fp.ORDER;\n      aInRange('point.y', y, _0n, max);\n\n      // Ed25519: x\u00B2 = (y\u00B2-1)/(dy\u00B2+1) mod p. Ed448: x\u00B2 = (y\u00B2-1)/(dy\u00B2-1) mod p. Generic case:\n      // ax\u00B2+y\u00B2=1+dx\u00B2y\u00B2 => y\u00B2-1=dx\u00B2y\u00B2-ax\u00B2 => y\u00B2-1=x\u00B2(dy\u00B2-a) => x\u00B2=(y\u00B2-1)/(dy\u00B2-a)\n      const y2 = modP(y * y); // denominator is always non-0 mod p.\n      const u = modP(y2 - _1n); // u = y\u00B2 - 1\n      const v = modP(d * y2 - a); // v = d y\u00B2 + 1.\n      let { isValid, value: x } = uvRatio(u, v); // \u221A(u/v)\n      if (!isValid) throw new Error('bad point: invalid y coordinate');\n      const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n      const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n      if (!zip215 && x === _0n && isLastByteOdd)\n        // if x=0 and x_0 = 1, fail\n        throw new Error('bad point: x=0 and x_0=1');\n      if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x\n      return Point.fromAffine({ x, y });\n    }\n\n    static fromHex(hex: string, zip215 = false): Point {\n      return Point.fromBytes(hexToBytes(hex), zip215);\n    }\n\n    get x(): bigint {\n      return this.toAffine().x;\n    }\n    get y(): bigint {\n      return this.toAffine().y;\n    }\n\n    precompute(windowSize: number = 8, isLazy = true) {\n      wnaf.createCache(this, windowSize);\n      if (!isLazy) this.multiply(_2n); // random number\n      return this;\n    }\n\n    // Useful in fromAffine() - not for fromBytes(), which always created valid points.\n    assertValidity(): void {\n      const p = this;\n      const { a, d } = CURVE;\n      // Keep generic Edwards validation fail-closed on the neutral point.\n      // Even though ZERO is algebraically valid and can roundtrip through encodings, higher-level\n      // callers often reach it only through broken hash/scalar plumbing; rejecting it here avoids\n      // silently treating that degenerate state as an ordinary public point.\n      if (p.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n      // Equation in affine coordinates: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2\n      // Equation in projective coordinates (X/Z, Y/Z, Z):  (aX\u00B2 + Y\u00B2)Z\u00B2 = Z\u2074 + dX\u00B2Y\u00B2\n      const { X, Y, Z, T } = p;\n      const X2 = modP(X * X); // X\u00B2\n      const Y2 = modP(Y * Y); // Y\u00B2\n      const Z2 = modP(Z * Z); // Z\u00B2\n      const Z4 = modP(Z2 * Z2); // Z\u2074\n      const aX2 = modP(X2 * a); // aX\u00B2\n      const left = modP(Z2 * modP(aX2 + Y2)); // (aX\u00B2 + Y\u00B2)Z\u00B2\n      const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z\u2074 + dX\u00B2Y\u00B2\n      if (left !== right) throw new Error('bad point: equation left != right (1)');\n      // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n      const XY = modP(X * Y);\n      const ZT = modP(Z * T);\n      if (XY !== ZT) throw new Error('bad point: equation left != right (2)');\n    }\n\n    // Compare one point to another.\n    equals(other: Point): boolean {\n      aedpoint(other);\n      const { X: X1, Y: Y1, Z: Z1 } = this;\n      const { X: X2, Y: Y2, Z: Z2 } = other;\n      const X1Z2 = modP(X1 * Z2);\n      const X2Z1 = modP(X2 * Z1);\n      const Y1Z2 = modP(Y1 * Z2);\n      const Y2Z1 = modP(Y2 * Z1);\n      return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n    }\n\n    is0(): boolean {\n      return this.equals(Point.ZERO);\n    }\n\n    negate(): Point {\n      // Flips point sign to a negative one (-x, y in affine coords)\n      return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));\n    }\n\n    // Fast algo for doubling Extended Point.\n    // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n    // Cost: 4M + 4S + 1*a + 6add + 1*2.\n    double(): Point {\n      const { a } = CURVE;\n      const { X: X1, Y: Y1, Z: Z1 } = this;\n      const A = modP(X1 * X1); // A = X12\n      const B = modP(Y1 * Y1); // B = Y12\n      const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n      const D = modP(a * A); // D = a*A\n      const x1y1 = X1 + Y1;\n      const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n      const G = D + B; // G = D+B\n      const F = G - C; // F = G-C\n      const H = D - B; // H = D-B\n      const X3 = modP(E * F); // X3 = E*F\n      const Y3 = modP(G * H); // Y3 = G*H\n      const T3 = modP(E * H); // T3 = E*H\n      const Z3 = modP(F * G); // Z3 = F*G\n      return new Point(X3, Y3, Z3, T3);\n    }\n\n    // Fast algo for adding 2 Extended Points.\n    // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n    // Cost: 9M + 1*a + 1*d + 7add.\n    add(other: Point) {\n      aedpoint(other);\n      const { a, d } = CURVE;\n      const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n      const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;\n      const A = modP(X1 * X2); // A = X1*X2\n      const B = modP(Y1 * Y2); // B = Y1*Y2\n      const C = modP(T1 * d * T2); // C = T1*d*T2\n      const D = modP(Z1 * Z2); // D = Z1*Z2\n      const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n      const F = D - C; // F = D-C\n      const G = D + C; // G = D+C\n      const H = modP(B - a * A); // H = B-a*A\n      const X3 = modP(E * F); // X3 = E*F\n      const Y3 = modP(G * H); // Y3 = G*H\n      const T3 = modP(E * H); // T3 = E*H\n      const Z3 = modP(F * G); // Z3 = F*G\n      return new Point(X3, Y3, Z3, T3);\n    }\n\n    subtract(other: Point): Point {\n      // Validate before calling `negate()` so wrong inputs fail with the point guard\n      // instead of leaking a foreign `negate()` error.\n      aedpoint(other);\n      return this.add(other.negate());\n    }\n\n    // Constant-time multiplication.\n    multiply(scalar: bigint): Point {\n      // 1 <= scalar < L\n      // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.\n      // In keygen/signing-style callers, those values usually mean broken hash/scalar plumbing,\n      // and failing closed is safer than silently producing the identity point.\n      if (!Fn.isValidNot0(scalar))\n        throw new RangeError('invalid scalar: expected 1 <= sc < curve.n');\n      const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));\n      return normalizeZ(Point, [p, f])[0];\n    }\n\n    // Non-constant-time multiplication. Uses double-and-add algorithm.\n    // It's faster, but should only be used when you don't care about\n    // an exposed private key e.g. sig verification.\n    // Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but\n    // n and larger values are rejected instead of being reduced mod n to the identity point.\n    multiplyUnsafe(scalar: bigint): Point {\n      // 0 <= scalar < L\n      if (!Fn.isValid(scalar)) throw new RangeError('invalid scalar: expected 0 <= sc < curve.n');\n      if (scalar === _0n) return Point.ZERO;\n      if (this.is0() || scalar === _1n) return this;\n      return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p));\n    }\n\n    // Checks if point is of small order.\n    // If you add something to small order point, you will have \"dirty\"\n    // point with torsion component.\n    // Clears cofactor and checks if the result is 0.\n    isSmallOrder(): boolean {\n      return this.clearCofactor().is0();\n    }\n\n    // Multiplies point by curve order and checks if the result is 0.\n    // Returns `false` is the point is dirty.\n    isTorsionFree(): boolean {\n      return wnaf.unsafe(this, CURVE.n).is0();\n    }\n\n    // Converts Extended point to default (x, y) coordinates.\n    // Can accept precomputed Z^-1 - for example, from invertBatch.\n    toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n      const p = this;\n      let iz = invertedZ;\n      const { X, Y, Z } = p;\n      const is0 = p.is0();\n      if (iz == null) iz = is0 ? _8n : (Fp.inv(Z) as bigint); // 8 was chosen arbitrarily\n      const x = modP(X * iz);\n      const y = modP(Y * iz);\n      const zz = Fp.mul(Z, iz);\n      if (is0) return { x: _0n, y: _1n };\n      if (zz !== _1n) throw new Error('invZ was invalid');\n      return { x, y };\n    }\n\n    clearCofactor(): Point {\n      if (cofactor === _1n) return this;\n      return this.multiplyUnsafe(cofactor);\n    }\n\n    toBytes(): Uint8Array {\n      const { x, y } = this.toAffine();\n      // Fp.toBytes() allows non-canonical encoding of y (>= p).\n      const bytes = Fp.toBytes(y);\n      // Each y has 2 valid points: (x, y), (x,-y).\n      // When compressing, it's enough to store y and use the last byte to encode sign of x\n      bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0;\n      return bytes;\n    }\n    toHex(): string {\n      return bytesToHex(this.toBytes());\n    }\n\n    toString() {\n      return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n    }\n  }\n  const wnaf = new wNAF(Point, Fn.BITS);\n  // Keep constructor work cheap: subgroup/generator validation belongs to the caller's curve\n  // parameters, and doing the extra checks here adds about 10-15ms to heavy module imports.\n  // Callers that construct custom curves are responsible for supplying the correct base point.\n  // try {\n  //   Point.BASE.assertValidity();\n  //   if (!Point.BASE.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n  // } catch {\n  //   throw new Error('bad curve params: generator point');\n  // }\n  // 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 (Fn.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/**\n * Base class for prime-order points like Ristretto255 and Decaf448.\n * These points eliminate cofactor issues by representing equivalence classes\n * of Edwards curve points. Multiple Edwards representatives can describe the\n * same abstract wrapper element, so wrapper validity is not the same thing as\n * the hidden representative being torsion-free.\n * @param ep - Backing Edwards point.\n * @example\n * Base class for prime-order points like Ristretto255 and Decaf448.\n *\n * ```ts\n * import { ristretto255 } from '@noble/curves/ed25519.js';\n * const point = ristretto255.Point.BASE.multiply(2n);\n * ```\n */\nexport abstract class PrimeEdwardsPoint<T extends PrimeEdwardsPoint<T>>\n  implements CurvePoint<bigint, T>\n{\n  static BASE: PrimeEdwardsPoint<any>;\n  static ZERO: PrimeEdwardsPoint<any>;\n  static Fp: IField<bigint>;\n  static Fn: IField<bigint>;\n\n  protected readonly ep: EdwardsPoint;\n\n  /**\n   * Wrap one internal Edwards representative directly.\n   * This is not a canonical encoding boundary: alternate Edwards\n   * representatives may still describe the same abstract wrapper element.\n   */\n  constructor(ep: EdwardsPoint) {\n    this.ep = ep;\n  }\n\n  // Abstract methods that must be implemented by subclasses\n  abstract toBytes(): Uint8Array;\n  abstract equals(other: T): boolean;\n\n  // Static methods that must be implemented by subclasses\n  static fromBytes(_bytes: Uint8Array): any {\n    notImplemented();\n  }\n\n  static fromHex(_hex: string): any {\n    notImplemented();\n  }\n\n  get x(): bigint {\n    return this.toAffine().x;\n  }\n  get y(): bigint {\n    return this.toAffine().y;\n  }\n\n  // Common implementations\n  clearCofactor(): T {\n    // no-op for the abstract prime-order wrapper group; this is about the\n    // wrapper element, not the hidden Edwards representative.\n    return this as any;\n  }\n\n  assertValidity(): void {\n    // Keep wrapper validity at the abstract-group boundary. Canonical decode\n    // may choose Edwards representatives that differ by small torsion, so\n    // checking `this.ep.isTorsionFree()` here would reject valid wrapper points.\n    this.ep.assertValidity();\n  }\n\n  /**\n   * Return affine coordinates of the current internal Edwards representative.\n   * This is a convenience helper, not a canonical Ristretto/Decaf encoding.\n   * Equal abstract elements may expose different `x` / `y`; use\n   * `toBytes()` / `fromBytes()` for canonical roundtrips.\n   */\n  toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n    return this.ep.toAffine(invertedZ);\n  }\n\n  toHex(): string {\n    return bytesToHex(this.toBytes());\n  }\n\n  toString(): string {\n    return this.toHex();\n  }\n\n  isTorsionFree(): boolean {\n    // Abstract Ristretto/Decaf elements are already prime-order even when the\n    // hidden Edwards representative is not torsion-free.\n    return true;\n  }\n\n  isSmallOrder(): boolean {\n    return false;\n  }\n\n  add(other: T): T {\n    this.assertSame(other);\n    return this.init(this.ep.add(other.ep));\n  }\n\n  subtract(other: T): T {\n    this.assertSame(other);\n    return this.init(this.ep.subtract(other.ep));\n  }\n\n  multiply(scalar: bigint): T {\n    return this.init(this.ep.multiply(scalar));\n  }\n\n  multiplyUnsafe(scalar: bigint): T {\n    return this.init(this.ep.multiplyUnsafe(scalar));\n  }\n\n  double(): T {\n    return this.init(this.ep.double());\n  }\n\n  negate(): T {\n    return this.init(this.ep.negate());\n  }\n\n  precompute(windowSize?: number, isLazy?: boolean): T {\n    this.ep.precompute(windowSize, isLazy);\n    // Keep the wrapper identity stable like the backing Edwards API instead of\n    // allocating a fresh wrapper around the same cached point.\n    return this as unknown as T;\n  }\n\n  // Helper methods\n  abstract is0(): boolean;\n  protected abstract assertSame(other: T): void;\n  protected abstract init(ep: EdwardsPoint): T;\n}\n\n/**\n * Initializes EdDSA signatures over given Edwards curve.\n * @param Point - Edwards point constructor.\n * @param cHash - Hash function.\n * @param eddsaOpts - Optional signature helpers. See {@link EdDSAOpts}.\n * @returns EdDSA helper namespace.\n * @throws If the hash function, options, or derived point operations are invalid. {@link Error}\n * @example\n * Initializes EdDSA signatures over given Edwards curve.\n *\n * ```ts\n * import { eddsa } from '@noble/curves/abstract/edwards.js';\n * import { jubjub } from '@noble/curves/misc.js';\n * import { sha512 } from '@noble/hashes/sha2.js';\n * const sigs = eddsa(jubjub.Point, sha512);\n * const { secretKey, publicKey } = sigs.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = sigs.sign(msg, secretKey);\n * const isValid = sigs.verify(sig, msg, publicKey);\n * ```\n */\nexport function eddsa(\n  Point: EdwardsPointCons,\n  cHash: TArg<FHash>,\n  eddsaOpts: TArg<EdDSAOpts> = {}\n): EdDSA {\n  if (typeof cHash !== 'function') throw new Error('\"hash\" function param is required');\n  const hash = cHash as FHash;\n  const opts = eddsaOpts as EdDSAOpts;\n  validateObject(\n    opts,\n    {},\n    {\n      adjustScalarBytes: 'function',\n      randomBytes: 'function',\n      domain: 'function',\n      prehash: 'function',\n      zip215: 'boolean',\n      mapToCurve: 'function',\n    }\n  );\n\n  const { prehash } = opts;\n  const { BASE, Fp, Fn } = Point;\n  const outputLen = (hash as FHash & { outputLen?: number }).outputLen;\n  const expectedLen = 2 * Fp.BYTES;\n  // When hash metadata is available, reject incompatible EdDSA wrappers at construction time\n  // instead of deferring the mismatch until the first keygen/sign call.\n  if (outputLen !== undefined) {\n    asafenumber(outputLen, 'hash.outputLen');\n    if (outputLen !== expectedLen)\n      throw new Error(`hash.outputLen must be ${expectedLen}, got ${outputLen}`);\n  }\n\n  const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes;\n  const adjustScalarBytes =\n    opts.adjustScalarBytes === undefined\n      ? (bytes: TArg<Uint8Array>) => bytes as TRet<Uint8Array>\n      : opts.adjustScalarBytes;\n  const domain =\n    opts.domain === undefined\n      ? (data: TArg<Uint8Array>, ctx: TArg<Uint8Array>, phflag: boolean) => {\n          abool(phflag, 'phflag');\n          if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported');\n          return data as TRet<Uint8Array>;\n        }\n      : opts.domain; // NOOP\n\n  // Parse an EdDSA digest as a little-endian integer and reduce it modulo the scalar field order.\n  function modN_LE(hash: TArg<Uint8Array>): bigint {\n    return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit\n  }\n\n  // Get the hashed private scalar per RFC8032 5.1.5\n  function getPrivateScalar(key: TArg<Uint8Array>) {\n    const len = lengths.secretKey;\n    abytes(key, lengths.secretKey, 'secretKey');\n    // Hash private key with curve's hash function to produce uniformingly random input\n    // Check byte lengths: ensure(64, h(ensure(32, key)))\n    const hashed = abytes(hash(key), 2 * len, 'hashedSecretKey');\n    // Slice before clamping so in-place adjustors don't corrupt the prefix half.\n    const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n    const prefix = hashed.slice(len, 2 * len) as TRet<Uint8Array>; // second half is called key prefix (5.1.6)\n    const scalar = modN_LE(head); // The actual private scalar\n    return { head, prefix, scalar };\n  }\n\n  /** Convenience method that creates public key from scalar. RFC8032 5.1.5\n   * Also exposes the derived scalar/prefix tuple and point form reused by sign().\n   */\n  function getExtendedPublicKey(secretKey: TArg<Uint8Array>) {\n    const { head, prefix, scalar } = getPrivateScalar(secretKey);\n    const point = BASE.multiply(scalar); // Point on Edwards curve aka public key\n    const pointBytes = point.toBytes() as TRet<Uint8Array>;\n    return { head, prefix, scalar, point, pointBytes };\n  }\n\n  /** Calculates EdDSA pub key. RFC8032 5.1.5. */\n  function getPublicKey(secretKey: TArg<Uint8Array>): TRet<Uint8Array> {\n    return getExtendedPublicKey(secretKey).pointBytes;\n  }\n\n  // Hash domain-separated chunks into a little-endian scalar modulo the group order.\n  function hashDomainToScalar(\n    context: TArg<Uint8Array> = Uint8Array.of(),\n    ...msgs: TArg<Uint8Array[]>\n  ) {\n    const msg = concatBytes(...msgs);\n    return modN_LE(hash(domain(msg, abytes(context, undefined, 'context'), !!prehash)));\n  }\n\n  /** Signs message with secret key. RFC8032 5.1.6 */\n  function sign(\n    msg: TArg<Uint8Array>,\n    secretKey: TArg<Uint8Array>,\n    options: TArg<{ context?: Uint8Array }> = {}\n  ): TRet<Uint8Array> {\n    msg = abytes(msg, undefined, 'message');\n    if (prehash) msg = prehash(msg); // for ed25519ph etc.\n    const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);\n    const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n    // RFC 8032 5.1.6 allows r mod L = 0, and SUPERCOP ref10 accepts the resulting identity-point\n    // signature.\n    // We intentionally keep the safe multiply() rejection here so a miswired all-zero hash provider\n    // fails loudly instead of silently producing a degenerate signature.\n    const R = BASE.multiply(r).toBytes(); // R = rG\n    const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n    const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L\n    if (!Fn.isValid(s)) throw new Error('sign failed: invalid s'); // 0 <= s < L\n    const rs = concatBytes(R, Fn.toBytes(s));\n    return abytes(rs, lengths.signature, 'result') as TRet<Uint8Array>;\n  }\n\n  // Keep the shared helper strict by default: RFC 8032 / NIST-style wrappers should reject\n  // non-canonical encodings unless they explicitly opt into ZIP-215's more permissive decode rules.\n  const verifyOpts: TArg<{ context?: Uint8Array; zip215?: boolean }> = {\n    zip215: opts.zip215,\n  };\n\n  /**\n   * Verifies EdDSA signature against message and public key. RFC 8032 \u00A7\u00A75.1.7 and 5.2.7.\n   * A cofactored verification equation is checked.\n   */\n  function verify(\n    sig: TArg<Uint8Array>,\n    msg: TArg<Uint8Array>,\n    publicKey: TArg<Uint8Array>,\n    options = verifyOpts\n  ): boolean {\n    // Preserve the wrapper-selected default for `{}` / `{ zip215: undefined }`, not just omitted opts.\n    const { context } = options;\n    const zip215 = options.zip215 === undefined ? !!verifyOpts.zip215 : options.zip215;\n    const len = lengths.signature;\n    sig = abytes(sig, len, 'signature');\n    msg = abytes(msg, undefined, 'message');\n    publicKey = abytes(publicKey, lengths.publicKey, 'publicKey');\n    if (zip215 !== undefined) abool(zip215, 'zip215');\n    if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n    const mid = len / 2;\n    const r = sig.subarray(0, mid);\n    const s = bytesToNumberLE(sig.subarray(mid, len));\n    let A, R, SB;\n    try {\n      // ZIP-215 is more permissive than RFC 8032 / NIST186-5. Use it only for wrappers that\n      // explicitly want consensus-style unreduced encoding acceptance.\n      // zip215=true:  0 <= y < MASK (2^256 for ed25519)\n      // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n      A = Point.fromBytes(publicKey, zip215);\n      R = Point.fromBytes(r, zip215);\n      SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside\n    } catch (error) {\n      return false;\n    }\n    // RFC 8032 \u00A7\u00A75.1.7/5.2.7 and FIPS 186-5 \u00A7\u00A77.7.2/7.8.2 only decode A' and check the cofactored\n    // verification equation; they do not add a separate low-order-public-key rejection here.\n    // Strict mode still rejects small-order A' intentionally for SBS-style non-repudiation and to\n    // avoid ambiguous verification outcomes where unusual low-order keys can make distinct\n    // key/signature/message combinations verify.\n    if (!zip215 && A.isSmallOrder()) return false;\n\n    // ZIP-215 accepts noncanonical / unreduced point encodings, so the challenge hash must use the\n    // exact signature/public-key bytes rather than canonicalized re-encodings of the decoded points.\n    const k = hashDomainToScalar(context, r, publicKey, msg);\n    const RkA = R.add(A.multiplyUnsafe(k));\n    // Check the cofactored verification equation via the curve cofactor h.\n    // [h][S]B = [h]R + [h][k]A'\n    return RkA.subtract(SB).clearCofactor().is0();\n  }\n\n  const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448\n  const lengths = {\n    secretKey: _size,\n    publicKey: _size,\n    signature: 2 * _size,\n    seed: _size,\n  };\n  function randomSecretKey(seed?: TArg<Uint8Array>): TRet<Uint8Array> {\n    seed = seed === undefined ? randomBytes(lengths.seed) : seed;\n    return abytes(seed, lengths.seed, 'seed') as TRet<Uint8Array>;\n  }\n\n  function isValidSecretKey(key: TArg<Uint8Array>): boolean {\n    return isBytes(key) && key.length === lengths.secretKey;\n  }\n\n  function isValidPublicKey(key: TArg<Uint8Array>, zip215?: boolean): boolean {\n    try {\n      // Preserve the wrapper-selected default for omitted / `undefined` ZIP-215 flags here too.\n      return !!Point.fromBytes(key, zip215 === undefined ? verifyOpts.zip215 : zip215);\n    } catch (error) {\n      return false;\n    }\n  }\n\n  const utils = {\n    getExtendedPublicKey,\n    randomSecretKey,\n    isValidSecretKey,\n    isValidPublicKey,\n    /**\n     * Converts ed public key to x public key. Uses formula:\n     * - ed25519:\n     *   - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n     *   - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n     * - ed448:\n     *   - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`\n     *   - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`\n     */\n    toMontgomery(publicKey: TArg<Uint8Array>): TRet<Uint8Array> {\n      const { y } = Point.fromBytes(publicKey);\n      const size = lengths.publicKey;\n      const is25519 = size === 32;\n      if (!is25519 && size !== 57) throw new Error('only defined for 25519 and 448');\n      const u = is25519 ? Fp.div(_1n + y, _1n - y) : Fp.div(y - _1n, y + _1n);\n      return Fp.toBytes(u) as TRet<Uint8Array>;\n    },\n    toMontgomerySecret(secretKey: TArg<Uint8Array>): TRet<Uint8Array> {\n      const size = lengths.secretKey;\n      abytes(secretKey, size);\n      const hashed = hash(secretKey.subarray(0, size));\n      return adjustScalarBytes(hashed).subarray(0, size) as TRet<Uint8Array>;\n    },\n  };\n  Object.freeze(lengths);\n  Object.freeze(utils);\n\n  return Object.freeze({\n    keygen: createKeygen(randomSecretKey, getPublicKey),\n    getPublicKey,\n    sign,\n    verify,\n    utils,\n    Point,\n    lengths,\n  }) satisfies Signer;\n}\n", "/**\n * Montgomery curve methods. It's not really whole montgomery curve,\n * just bunch of very specific methods for X25519 / X448 from\n * [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748)\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n  abytes,\n  aInRange,\n  bytesToNumberLE,\n  copyBytes,\n  numberToBytesLE,\n  randomBytes,\n  validateObject,\n  type CryptoKeys,\n  type TArg,\n  type TRet,\n} from '../utils.ts';\nimport { createKeygen, type CurveLengths } from './curve.ts';\nimport { mod } from './modular.ts';\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\n\n/** Curve-specific hooks required to build one X25519/X448 helper. */\nexport type MontgomeryOpts = {\n  /** Prime field modulus. */\n  P: bigint;\n  /** RFC 7748 variant name. */\n  type: 'x25519' | 'x448';\n  /**\n   * Clamp or otherwise normalize one scalar byte string before use.\n   * @param bytes - Raw secret scalar bytes.\n   * @returns Adjusted scalar bytes ready for Montgomery multiplication.\n   */\n  adjustScalarBytes: (bytes: TArg<Uint8Array>) => TRet<Uint8Array>;\n  /**\n   * Invert one field element with exponentiation by `p - 2`.\n   * @param x - Field element to invert.\n   * @returns Multiplicative inverse of `x`.\n   */\n  powPminus2: (x: bigint) => bigint;\n  /**\n   * Optional randomness source for `keygen()` and `utils.randomSecretKey()`.\n   * Receives the requested byte length and returns fresh random bytes.\n   */\n  randomBytes?: (bytesLength?: number) => TRet<Uint8Array>;\n};\n\n/** Public X25519/X448 ECDH API built on a Montgomery ladder. */\nexport type MontgomeryECDH = {\n  /**\n   * Multiply one scalar by one Montgomery `u` coordinate.\n   * @param scalar - Secret scalar bytes.\n   * @param u - Public Montgomery `u` coordinate.\n   * @returns Shared point encoded as bytes.\n   */\n  scalarMult: (scalar: TArg<Uint8Array>, u: TArg<Uint8Array>) => TRet<Uint8Array>;\n  /**\n   * Multiply one scalar by the curve base point.\n   * @param scalar - Secret scalar bytes.\n   * @returns Public key bytes.\n   */\n  scalarMultBase: (scalar: TArg<Uint8Array>) => TRet<Uint8Array>;\n  /**\n   * Derive a shared secret from a local secret key and peer public key.\n   * @param secretKeyA - Local secret key bytes.\n   * @param publicKeyB - Peer public key bytes.\n   * Rejects low-order public inputs instead of returning the all-zero shared secret.\n   * @returns Shared secret bytes.\n   */\n  getSharedSecret: (secretKeyA: TArg<Uint8Array>, publicKeyB: TArg<Uint8Array>) => TRet<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: TArg<Uint8Array>) => TRet<Uint8Array>;\n  /** Utility helpers for secret-key generation. */\n  utils: {\n    /** Generate one random secret key with the curve's expected byte length. */\n    randomSecretKey: () => TRet<Uint8Array>;\n  };\n  /** Encoded Montgomery base point `u`. */\n  GuBytes: TRet<Uint8Array>;\n  /** Public lengths for keys and seeds. */\n  lengths: CurveLengths;\n  /**\n   * Generate one random secret/public keypair.\n   * @param seed - Optional seed bytes to use instead of random generation.\n   * @returns Fresh secret/public keypair.\n   */\n  keygen: (seed?: TArg<Uint8Array>) => {\n    secretKey: TRet<Uint8Array>;\n    publicKey: TRet<Uint8Array>;\n  };\n};\n\nfunction validateOpts(curve: TArg<MontgomeryOpts>) {\n  // Validate constructor config eagerly, but do not call user-provided hooks here:\n  // `randomBytes` may be transcript-backed or otherwise contextual. Runtime type checks are\n  // enough to fail fast on malformed configs without consuming user state.\n  validateObject(\n    curve,\n    {\n      P: 'bigint',\n      type: 'string',\n      adjustScalarBytes: 'function',\n      powPminus2: 'function',\n    },\n    {\n      randomBytes: 'function',\n    }\n  );\n  return Object.freeze({ ...curve } as const);\n}\n\n/**\n * @param curveDef - Montgomery curve definition.\n * @returns ECDH helper namespace.\n * @throws If the curve definition or derived shared point is invalid. {@link Error}\n * @example\n * Perform one X25519 key exchange through the generic Montgomery helper.\n *\n * ```ts\n * import { x25519 } from '@noble/curves/ed25519.js';\n * const alice = x25519.keygen();\n * const shared = x25519.getSharedSecret(alice.secretKey, alice.publicKey);\n * ```\n */\nexport function montgomery(curveDef: TArg<MontgomeryOpts>): TRet<MontgomeryECDH> {\n  const CURVE = validateOpts(curveDef);\n  const { P, type, adjustScalarBytes, powPminus2, randomBytes: rand } = CURVE;\n  const is25519 = type === 'x25519';\n  if (!is25519 && type !== 'x448') throw new Error('invalid type');\n  const randomBytes_ = rand === undefined ? randomBytes : rand;\n\n  const montgomeryBits = is25519 ? 255 : 448;\n  const fieldLen = is25519 ? 32 : 56;\n  const Gu = is25519 ? BigInt(9) : BigInt(5);\n  // RFC 7748 #5:\n  // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 and\n  // (156326 - 2) / 4 = 39081 for curve448/X448\n  // const a = is25519 ? 486662n : 156326n;\n  const a24 = is25519 ? BigInt(121665) : BigInt(39081);\n  // RFC: x25519 \"the resulting integer is of the form 2^254 plus\n  // eight times a value between 0 and 2^251 - 1 (inclusive)\"\n  // x448: \"2^447 plus four times a value between 0 and 2^445 - 1 (inclusive)\"\n  const minScalar = is25519 ? _2n ** BigInt(254) : _2n ** BigInt(447);\n  const maxAdded = is25519\n    ? BigInt(8) * _2n ** BigInt(251) - _1n\n    : BigInt(4) * _2n ** BigInt(445) - _1n;\n  const maxScalar = minScalar + maxAdded + _1n; // (inclusive)\n  const modP = (n: bigint) => mod(n, P);\n  const GuBytes = encodeU(Gu);\n  function encodeU(u: bigint): TRet<Uint8Array> {\n    return numberToBytesLE(modP(u), fieldLen);\n  }\n  function decodeU(u: TArg<Uint8Array>): bigint {\n    const _u = copyBytes(abytes(u, fieldLen, 'uCoordinate'));\n    // RFC: When receiving such an array, implementations of X25519\n    // (but not X448) MUST mask the most significant bit in the final byte.\n    if (is25519) _u[31] &= 127; // 0b0111_1111\n    // RFC: Implementations MUST accept non-canonical values and process them as\n    // if they had been reduced modulo the field prime.  The non-canonical\n    // values are 2^255 - 19 through 2^255 - 1 for X25519 and 2^448 - 2^224\n    // - 1 through 2^448 - 1 for X448.\n    return modP(bytesToNumberLE(_u));\n  }\n  function decodeScalar(scalar: TArg<Uint8Array>): bigint {\n    return bytesToNumberLE(adjustScalarBytes(copyBytes(abytes(scalar, fieldLen, 'scalar'))));\n  }\n  function scalarMult(scalar: TArg<Uint8Array>, u: TArg<Uint8Array>): TRet<Uint8Array> {\n    const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));\n    // Some public keys are useless, of low-order. Curve author doesn't think\n    // it needs to be validated, but we do it nonetheless.\n    // https://cr.yp.to/ecdh.html#validate\n    if (pu === _0n) throw new Error('invalid private or public key received');\n    return encodeU(pu);\n  }\n  // Computes public key from private. By doing scalar multiplication of base point.\n  function scalarMultBase(scalar: TArg<Uint8Array>): TRet<Uint8Array> {\n    return scalarMult(scalar, GuBytes);\n  }\n  const getPublicKey = scalarMultBase;\n  const getSharedSecret = scalarMult;\n\n  // cswap from RFC7748 \"example code\"\n  function cswap(swap: bigint, x_2: bigint, x_3: bigint): { x_2: bigint; x_3: bigint } {\n    // dummy = mask(swap) AND (x_2 XOR x_3)\n    // Where mask(swap) is the all-1 or all-0 word of the same length as x_2\n    // and x_3, computed, e.g., as mask(swap) = 0 - swap.\n    const dummy = modP(swap * (x_2 - x_3));\n    x_2 = modP(x_2 - dummy); // x_2 = x_2 XOR dummy\n    x_3 = modP(x_3 + dummy); // x_3 = x_3 XOR dummy\n    return { x_2, x_3 };\n  }\n\n  /**\n   * Montgomery x-only multiplication ladder for the selected X25519/X448 curve.\n   * @param pointU - decoded Montgomery u coordinate for the selected curve\n   * @param scalar - decoded clamped scalar by which the point is multiplied\n   * @returns resulting Montgomery u coordinate for the selected curve\n   */\n  function montgomeryLadder(u: bigint, scalar: bigint): bigint {\n    aInRange('u', u, _0n, P);\n    aInRange('scalar', scalar, minScalar, maxScalar);\n    const k = scalar;\n    const x_1 = u;\n    let x_2 = _1n;\n    let z_2 = _0n;\n    let x_3 = u;\n    let z_3 = _1n;\n    let swap = _0n;\n    for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n      const k_t = (k >> t) & _1n;\n      swap ^= k_t;\n      ({ x_2, x_3 } = cswap(swap, x_2, x_3));\n      ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));\n      swap = k_t;\n\n      const A = x_2 + z_2;\n      const AA = modP(A * A);\n      const B = x_2 - z_2;\n      const BB = modP(B * B);\n      const E = AA - BB;\n      const C = x_3 + z_3;\n      const D = x_3 - z_3;\n      const DA = modP(D * A);\n      const CB = modP(C * B);\n      const dacb = DA + CB;\n      const da_cb = DA - CB;\n      x_3 = modP(dacb * dacb);\n      z_3 = modP(x_1 * modP(da_cb * da_cb));\n      x_2 = modP(AA * BB);\n      z_2 = modP(E * (AA + modP(a24 * E)));\n    }\n    ({ x_2, x_3 } = cswap(swap, x_2, x_3));\n    ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));\n    const z2 = powPminus2(z_2); // `Fp.pow(x, P - _2n)` is much slower equivalent\n    return modP(x_2 * z2); // Return x_2 * (z_2^(p - 2))\n  }\n  const lengths = {\n    secretKey: fieldLen,\n    publicKey: fieldLen,\n    seed: fieldLen,\n  };\n  const randomSecretKey = (seed?: TArg<Uint8Array>): TRet<Uint8Array> => {\n    seed = seed === undefined ? randomBytes_(fieldLen) : seed;\n    abytes(seed, lengths.seed, 'seed');\n    // Reuse caller-supplied seed bytes verbatim; clamping is deferred until\n    // decodeScalar(...) when the secret key is actually used.\n    return seed as TRet<Uint8Array>;\n  };\n  const utils = { randomSecretKey };\n  Object.freeze(lengths);\n  Object.freeze(utils);\n\n  return Object.freeze({\n    keygen: createKeygen(randomSecretKey, getPublicKey),\n    getSharedSecret,\n    getPublicKey,\n    scalarMult,\n    scalarMultBase,\n    utils,\n    GuBytes: GuBytes.slice() as TRet<Uint8Array>,\n    lengths,\n  }) satisfies CryptoKeys;\n}\n", "/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, hexToBytes } from '@noble/hashes/utils.js';\nimport { type AffinePoint } from './abstract/curve.ts';\nimport {\n  eddsa,\n  edwards,\n  PrimeEdwardsPoint,\n  type EdDSA,\n  type EdDSAOpts,\n  type EdwardsOpts,\n  type EdwardsPoint,\n  type EdwardsPointCons,\n} from './abstract/edwards.ts';\nimport { createFROST, type FROST } from './abstract/frost.ts';\nimport {\n  _DST_scalar,\n  createHasher,\n  expand_message_xmd,\n  type H2CDSTOpts,\n  type H2CHasher,\n  type H2CHasherBase,\n} from './abstract/hash-to-curve.ts';\nimport {\n  FpInvertBatch,\n  FpSqrtEven,\n  isNegativeLE,\n  mod,\n  pow2,\n  type IField,\n} from './abstract/modular.ts';\nimport { montgomery, type MontgomeryECDH } from './abstract/montgomery.ts';\nimport { createOPRF, type OPRF } from './abstract/oprf.ts';\nimport { asciiToBytes, bytesToNumberLE, equalBytes, type TArg, type TRet } from './utils.ts';\n\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);\n\n// P = 2n**255n - 19n\nconst ed25519_CURVE_p = /* @__PURE__ */ BigInt(\n  '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed'\n);\n// N = 2n**252n + 27742317777372353535851937790883648493n\n// a = Fp.create(BigInt(-1))\n// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\nconst ed25519_CURVE: EdwardsOpts = /* @__PURE__ */ (() => ({\n  p: ed25519_CURVE_p,\n  n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),\n  h: _8n,\n  a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),\n  d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),\n  Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),\n  Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),\n}))();\n\nfunction ed25519_pow_2_252_3(x: bigint) {\n  // prettier-ignore\n  const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n  const P = ed25519_CURVE_p;\n  const x2 = (x * x) % P;\n  const b2 = (x2 * x) % P; // x^3, 11\n  const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n  const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n  const b10 = (pow2(b5, _5n, P) * b5) % P;\n  const b20 = (pow2(b10, _10n, P) * b10) % P;\n  const b40 = (pow2(b20, _20n, P) * b20) % P;\n  const b80 = (pow2(b40, _40n, P) * b40) % P;\n  const b160 = (pow2(b80, _80n, P) * b80) % P;\n  const b240 = (pow2(b160, _80n, P) * b80) % P;\n  const b250 = (pow2(b240, _10n, P) * b10) % P;\n  const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n  // ^ This is x^((p-5)/8); multiply by x once more to get x^((p+3)/8).\n  return { pow_p_5_8, b2 };\n}\n\n// Mutates and returns the provided 32-byte buffer in place.\nfunction adjustScalarBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array> {\n  // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n  // set the three least significant bits of the first byte\n  bytes[0] &= 248; // 0b1111_1000\n  // and the most significant bit of the last to zero,\n  bytes[31] &= 127; // 0b0111_1111\n  // set the second most significant bit of the last byte to 1\n  bytes[31] |= 64; // 0b0100_0000\n  return bytes as TRet<Uint8Array>;\n}\n\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\n// Fp.sqrt(Fp.neg(1))\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt(\n  '19681161376707505956807079304988542015446066515923890162744021073123829784752'\n);\n// sqrt(u/v). Returns `{ isValid, value }`; on non-squares `value` is still a\n// dummy root-shaped field element so callers can stay constant-time.\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n  const P = ed25519_CURVE_p;\n  const v3 = mod(v * v * v, P); // v\u00B3\n  const v7 = mod(v3 * v3 * v, P); // v\u2077\n  // (p+3)/8 and (p-5)/8\n  const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n  let x = mod(u * v3 * pow, P); // (uv\u00B3)(uv\u2077)^(p-5)/8\n  const vx2 = mod(v * x * x, P); // vx\u00B2\n  const root1 = x; // First root candidate\n  const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n  const useRoot1 = vx2 === u; // If vx\u00B2 = u (mod p), x is a square root\n  const useRoot2 = vx2 === mod(-u, P); // If vx\u00B2 = -u, set x <-- x * 2^((p-1)/4)\n  const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx\u00B2 = -u\u221A(-1)\n  if (useRoot1) x = root1;\n  if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n  if (isNegativeLE(x, P)) x = mod(-x, P);\n  return { isValid: useRoot1 || useRoot2, value: x };\n}\n\nconst ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });\n// Public field alias stays stricter than the RFC 8032 Appendix A sample code:\n// `Fp.inv(0)` throws instead of returning `0`.\nconst Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();\nconst Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();\n\n// RFC 8032 `dom2` helper for ctx/ph variants only. Plain Ed25519 keeps the\n// empty-domain path in `ed()` and would be wrong if routed through this helper.\nfunction ed25519_domain(\n  data: TArg<Uint8Array>,\n  ctx: TArg<Uint8Array>,\n  phflag: boolean\n): TRet<Uint8Array> {\n  if (ctx.length > 255) throw new Error('Context is too big');\n  return concatBytes(\n    asciiToBytes('SigEd25519 no Ed25519 collisions'),\n    new Uint8Array([phflag ? 1 : 0, ctx.length]),\n    ctx,\n    data\n  ) as TRet<Uint8Array>;\n}\n\nfunction ed(opts: TArg<EdDSAOpts>) {\n  // Ed25519 keeps ZIP-215 default verification semantics for consensus compatibility.\n  return eddsa(\n    ed25519_Point,\n    sha512,\n    Object.assign({ adjustScalarBytes, zip215: true }, opts as EdDSAOpts)\n  );\n}\n\n/**\n * ed25519 curve with EdDSA signatures.\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Generate one Ed25519 keypair, sign a message, and verify it.\n *\n * ```js\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * const { secretKey, publicKey } = ed25519.keygen();\n * // const publicKey = ed25519.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519.sign(msg, secretKey);\n * const isValid = ed25519.verify(sig, msg, publicKey); // ZIP215\n * // RFC8032 / FIPS 186-5\n * const isValid2 = ed25519.verify(sig, msg, publicKey, { zip215: false });\n * ```\n */\nexport const ed25519: EdDSA = /* @__PURE__ */ ed({});\n/**\n * Context version of ed25519 (ctx for domain separation). See {@link ed25519}\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Sign and verify with Ed25519ctx under one explicit context.\n *\n * ```ts\n * const context = new TextEncoder().encode('docs');\n * const { secretKey, publicKey } = ed25519ctx.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519ctx.sign(msg, secretKey, { context });\n * const isValid = ed25519ctx.verify(sig, msg, publicKey, { context });\n * ```\n */\nexport const ed25519ctx: EdDSA = /* @__PURE__ */ ed({ domain: ed25519_domain });\n/**\n * Prehashed version of ed25519. See {@link ed25519}\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Use the prehashed Ed25519 variant for one message.\n *\n * ```ts\n * const { secretKey, publicKey } = ed25519ph.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519ph.sign(msg, secretKey);\n * const isValid = ed25519ph.verify(sig, msg, publicKey);\n * ```\n */\nexport const ed25519ph: EdDSA = /* @__PURE__ */ ed({ domain: ed25519_domain, prehash: sha512 });\n/**\n * FROST threshold signatures over ed25519. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 ed25519 signing.\n *\n * ```ts\n * const alice = ed25519_FROST.Identifier.derive('alice@example.com');\n * const bob = ed25519_FROST.Identifier.derive('bob@example.com');\n * const carol = ed25519_FROST.Identifier.derive('carol@example.com');\n * const deal = ed25519_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const ed25519_FROST: TRet<FROST> = /* @__PURE__ */ (() =>\n  createFROST({\n    name: 'FROST-ED25519-SHA512-v1',\n    Point: ed25519_Point,\n    validatePoint: (p) => {\n      p.assertValidity();\n      if (!p.isTorsionFree()) throw new Error('bad point: not torsion-free');\n    },\n    hash: sha512,\n    // RFC 9591 keeps H2 undecorated here for RFC 8032 compatibility. In createFROST(),\n    // `H2: ''` becomes an empty DST prefix; the built-in hashToScalar fallback treats\n    // that the same as omitted DST, even though custom hooks can still observe the empty bag.\n    H2: '',\n  }))();\n\n/**\n * ECDH using curve25519 aka x25519.\n * `getSharedSecret()` rejects low-order peer inputs by default, and seeded\n * `keygen(seed)` reuses the provided 32-byte seed buffer instead of copying it.\n * @example\n * Derive one shared secret between two X25519 peers.\n *\n * ```js\n * import { x25519 } from '@noble/curves/ed25519.js';\n * const alice = x25519.keygen();\n * const bob = x25519.keygen();\n * const shared = x25519.getSharedSecret(alice.secretKey, bob.publicKey);\n * ```\n */\nexport const x25519: TRet<MontgomeryECDH> = /* @__PURE__ */ (() => {\n  const P = ed25519_CURVE_p;\n  return montgomery({\n    P,\n    type: 'x25519',\n    powPminus2: (x: bigint): bigint => {\n      // x^(p-2) aka x^(2^255-21)\n      const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n      return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n    },\n    adjustScalarBytes,\n  });\n})();\n\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// RFC 9380 Appendix G.2.2 / Err4730 requires `sgn0(c1) = 0` for the Edwards\n// map constant below, so use the even root explicitly.\n// 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)();\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n\n/**\n * RFC 9380 method `map_to_curve_elligator2_curve25519`. Experimental name: may be renamed later.\n * @private\n */\n// prettier-ignore\nexport function _map_to_curve_elligator2_curve25519(u: bigint): {\n  xMn: bigint, xMd: bigint, yMn: bigint, yMd: bigint\n} {\n  const ELL2_C4 = (ed25519_CURVE_p - _5n) / _8n; // 4. c4 = (q - 5) / 8       # Integer arithmetic\n  const ELL2_J = BigInt(486662);\n\n  let tv1 = Fp.sqr(u);          //  1.  tv1 = u^2\n  tv1 = Fp.mul(tv1, _2n);       //  2.  tv1 = 2 * tv1\n  // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n  let xd = Fp.add(tv1, Fp.ONE);\n  let x1n = Fp.neg(ELL2_J);     //  4.  x1n = -J              # x1 = x1n / xd = -J / (1 + 2 * u^2)\n  let tv2 = Fp.sqr(xd);         //  5.  tv2 = xd^2\n  let gxd = Fp.mul(tv2, xd);    //  6.  gxd = tv2 * xd        # gxd = xd^3\n  let gx1 = Fp.mul(tv1, ELL2_J);//  7.  gx1 = J * tv1         # x1n + J * xd\n  gx1 = Fp.mul(gx1, x1n);       //  8.  gx1 = gx1 * x1n       # x1n^2 + J * x1n * xd\n  gx1 = Fp.add(gx1, tv2);       //  9.  gx1 = gx1 + tv2       # x1n^2 + J * x1n * xd + xd^2\n  gx1 = Fp.mul(gx1, x1n);       //  10. gx1 = gx1 * x1n       # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n  let tv3 = Fp.sqr(gxd);        //  11. tv3 = gxd^2\n  tv2 = Fp.sqr(tv3);            //  12. tv2 = tv3^2           # gxd^4\n  tv3 = Fp.mul(tv3, gxd);       //  13. tv3 = tv3 * gxd       # gxd^3\n  tv3 = Fp.mul(tv3, gx1);       //  14. tv3 = tv3 * gx1       # gx1 * gxd^3\n  tv2 = Fp.mul(tv2, tv3);       //  15. tv2 = tv2 * tv3       # gx1 * gxd^7\n  let y11 = Fp.pow(tv2, ELL2_C4); //  16. y11 = tv2^c4        # (gx1 * gxd^7)^((p - 5) / 8)\n  y11 = Fp.mul(y11, tv3);       //  17. y11 = y11 * tv3       # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n  let y12 = Fp.mul(y11, ELL2_C3); //  18. y12 = y11 * c3\n  tv2 = Fp.sqr(y11);            //  19. tv2 = y11^2\n  tv2 = Fp.mul(tv2, gxd);       //  20. tv2 = tv2 * gxd\n  let e1 = Fp.eql(tv2, gx1);    //  21.  e1 = tv2 == gx1\n  // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n  let y1 = Fp.cmov(y12, y11, e1);\n  let x2n = Fp.mul(x1n, tv1);   //  23. x2n = x1n * tv1       # x2 = x2n / xd = 2 * u^2 * x1n / xd\n  let y21 = Fp.mul(y11, u);     //  24. y21 = y11 * u\n  y21 = Fp.mul(y21, ELL2_C2);   //  25. y21 = y21 * c2\n  let y22 = Fp.mul(y21, ELL2_C3); //  26. y22 = y21 * c3\n  let gx2 = Fp.mul(gx1, tv1);   //  27. gx2 = gx1 * tv1       # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n  tv2 = Fp.sqr(y21);            //  28. tv2 = y21^2\n  tv2 = Fp.mul(tv2, gxd);       //  29. tv2 = tv2 * gxd\n  let e2 = Fp.eql(tv2, gx2);    //  30.  e2 = tv2 == gx2\n  // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n  let y2 = Fp.cmov(y22, y21, e2);\n  tv2 = Fp.sqr(y1);             //  32. tv2 = y1^2\n  tv2 = Fp.mul(tv2, gxd);       //  33. tv2 = tv2 * gxd\n  let e3 = Fp.eql(tv2, gx1);    //  34.  e3 = tv2 == gx1\n  let xn = Fp.cmov(x2n, x1n, e3); //  35.  xn = CMOV(x2n, x1n, e3)  # If e3, x = x1, else x = x2\n  let y = Fp.cmov(y2, y1, e3);  //  36.   y = CMOV(y2, y1, e3)    # If e3, y = y1, else y = y2\n  let e4 = Fp.isOdd!(y);         //  37.  e4 = sgn0(y) == 1        # Fix sign of y\n  y = Fp.cmov(y, Fp.neg(y), e3 !== e4); //  38.   y = CMOV(y, -y, e3 XOR e4)\n  return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; //  39. return (xn, xd, y, 1)\n}\n\n// sgn0(c1) MUST equal 0\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))();\nfunction map_to_curve_elligator2_edwards25519(u: bigint) {\n  // 1. (xMn, xMd, yMn, yMd) = map_to_curve_elligator2_curve25519(u)\n  const { xMn, xMd, yMn, yMd } = _map_to_curve_elligator2_curve25519(u);\n  // map_to_curve_elligator2_curve25519(u)\n  let xn = Fp.mul(xMn, yMd); //  2.  xn = xMn * yMd\n  xn = Fp.mul(xn, ELL2_C1_EDWARDS); //  3.  xn = xn * c1\n  let xd = Fp.mul(xMd, yMn); //  4.  xd = xMd * yMn    # xn / xd = c1 * xM / yM\n  let yn = Fp.sub(xMn, xMd); //  5.  yn = xMn - xMd\n  // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n  let yd = Fp.add(xMn, xMd);\n  let tv1 = Fp.mul(xd, yd); //  7. tv1 = xd * yd\n  let e = Fp.eql(tv1, Fp.ZERO); //  8.   e = tv1 == 0\n  xn = Fp.cmov(xn, Fp.ZERO, e); //  9.  xn = CMOV(xn, 0, e)\n  xd = Fp.cmov(xd, Fp.ONE, e); //  10. xd = CMOV(xd, 1, e)\n  yn = Fp.cmov(yn, Fp.ONE, e); //  11. yn = CMOV(yn, 1, e)\n  yd = Fp.cmov(yd, Fp.ONE, e); //  12. yd = CMOV(yd, 1, e)\n  const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division\n  // Noble normalizes the RFC rational representation to affine `{ x, y }`\n  // before returning from the internal helper.\n  return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; //  13. return (xn, xd, yn, yd)\n}\n\n/**\n * Hashing to ed25519 points / field. RFC 9380 methods.\n * Public `mapToCurve()` returns the cofactor-cleared subgroup point; the\n * internal map callback below consumes one field element bigint, not `[bigint]`.\n * @example\n * Hash one message onto the ed25519 curve.\n *\n * ```ts\n * const point = ed25519_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const ed25519_hasher: H2CHasher<EdwardsPointCons> = /* @__PURE__ */ (() =>\n  createHasher(\n    ed25519_Point,\n    (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]),\n    {\n      DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n      encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n      p: ed25519_CURVE_p,\n      m: 1,\n      k: 128,\n      expand: 'xmd',\n      hash: sha512,\n    }\n  ))();\n\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// \u221A(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt(\n  '25063068953384623474111414158702152701244531502492656460079210482610430750235'\n);\n// 1 / \u221A(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt(\n  '54469307008909316920995813868745141605393597292927456921205312896311721017578'\n);\n// 1-d\u00B2\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt(\n  '1159843021668779879193775521855586647937357759715417654439879720876111806838'\n);\n// (d-1)\u00B2\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt(\n  '40440834346308536858101042469323190826248399146238708352240133220865137265952'\n);\n// `SQRT_RATIO_M1(1, number)` specialization. Returns `{ isValid, value }`,\n// where non-squares get the nonnegative `sqrt(SQRT_M1 / number)` branch.\nconst invertSqrt = (number: bigint) => uvRatio(_1n, number);\n\nconst MAX_255B = /* @__PURE__ */ BigInt(\n  '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'\n);\n// RFC 9496 \u00A74.3.4 MAP parser: masks bit 255 and reduces modulo p for element\n// derivation. The decode path has the opposite contract and rejects that bit.\nconst bytes255ToNumberLE = (bytes: TArg<Uint8Array>) =>\n  Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\n/**\n * Computes Elligator map for Ristretto255.\n * Primary formula source is RFC 9496 \u00A74.3.4 MAP; RFC 9380 Appendix B builds\n * `hash_to_ristretto255` on top of this helper.\n * Returns an internal Edwards representative, not a public `_RistrettoPoint`.\n */\nfunction calcElligatorRistrettoMap(r0: bigint): EdwardsPoint {\n  const { d } = ed25519_CURVE;\n  const P = ed25519_CURVE_p;\n  const mod = (n: bigint) => Fp.create(n);\n  const r = mod(SQRT_M1 * r0 * r0); // 1\n  const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n  let c = BigInt(-1); // 3\n  const D = mod((c - d * r) * mod(r + d)); // 4\n  let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n  let s_ = mod(s * r0); // 6\n  if (!isNegativeLE(s_, P)) s_ = mod(-s_);\n  if (!Ns_D_is_sq) s = s_; // 7\n  if (!Ns_D_is_sq) c = r; // 8\n  const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n  const s2 = s * s;\n  const W0 = mod((s + s) * D); // 10\n  const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n  const W2 = mod(_1n - s2); // 12\n  const W3 = mod(_1n + s2); // 13\n  return new ed25519_Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\n/**\n * Wrapper over Edwards Point for ristretto255.\n *\n * Each ed25519/EdwardsPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like EdwardsPoint,\n * but it should work in its own namespace: do not combine those two.\n * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nclass _RistrettoPoint extends PrimeEdwardsPoint<_RistrettoPoint> {\n  // Do NOT change syntax: the following gymnastics is done,\n  // because typescript strips comments, which makes bundlers disable tree-shaking.\n  // prettier-ignore\n  static BASE: _RistrettoPoint =\n    /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.BASE))();\n  // prettier-ignore\n  static ZERO: _RistrettoPoint =\n    /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.ZERO))();\n  // prettier-ignore\n  static Fp: IField<bigint> =\n    /* @__PURE__ */ (() => Fp)();\n  // prettier-ignore\n  static Fn: IField<bigint> =\n    /* @__PURE__ */ (() => Fn)();\n\n  constructor(ep: EdwardsPoint) {\n    super(ep);\n  }\n\n  /**\n   * Create one Ristretto255 point from affine Edwards coordinates.\n   * This wraps the internal Edwards representative directly and is not a\n   * canonical ristretto255 decoding path.\n   * Use `toBytes()` / `fromBytes()` if canonical ristretto255 bytes matter.\n   */\n  static fromAffine(ap: AffinePoint<bigint>): _RistrettoPoint {\n    return new _RistrettoPoint(ed25519_Point.fromAffine(ap));\n  }\n\n  protected assertSame(other: _RistrettoPoint): void {\n    if (!(other instanceof _RistrettoPoint)) throw new Error('RistrettoPoint expected');\n  }\n\n  protected init(ep: EdwardsPoint): _RistrettoPoint {\n    return new _RistrettoPoint(ep);\n  }\n\n  static fromBytes(bytes: TArg<Uint8Array>): _RistrettoPoint {\n    abytes(bytes, 32);\n    const { a, d } = ed25519_CURVE;\n    const P = ed25519_CURVE_p;\n    const mod = (n: bigint) => Fp.create(n);\n    const s = bytes255ToNumberLE(bytes);\n    // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n    // 3. Check that s is non-negative, or else abort\n    if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))\n      throw new Error('invalid ristretto255 encoding 1');\n    const s2 = mod(s * s);\n    const u1 = mod(_1n + a * s2); // 4 (a is -1)\n    const u2 = mod(_1n - a * s2); // 5\n    const u1_2 = mod(u1 * u1);\n    const u2_2 = mod(u2 * u2);\n    const v = mod(a * d * u1_2 - u2_2); // 6\n    const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n    const Dx = mod(I * u2); // 8\n    const Dy = mod(I * Dx * v); // 9\n    let x = mod((s + s) * Dx); // 10\n    if (isNegativeLE(x, P)) x = mod(-x); // 10\n    const y = mod(u1 * Dy); // 11\n    const t = mod(x * y); // 12\n    if (!isValid || isNegativeLE(t, P) || y === _0n)\n      throw new Error('invalid ristretto255 encoding 2');\n    return new _RistrettoPoint(new ed25519_Point(x, y, _1n, t));\n  }\n\n  /**\n   * Converts ristretto-encoded string to ristretto point.\n   * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).\n   * @param hex - Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n   */\n  static fromHex(hex: string): _RistrettoPoint {\n    return _RistrettoPoint.fromBytes(hexToBytes(hex));\n  }\n\n  /**\n   * Encodes ristretto point to Uint8Array.\n   * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n   */\n  toBytes(): TRet<Uint8Array> {\n    let { X, Y, Z, T } = this.ep;\n    const P = ed25519_CURVE_p;\n    const mod = (n: bigint) => Fp.create(n);\n    const u1 = mod(mod(Z + Y) * mod(Z - Y)); // 1\n    const u2 = mod(X * Y); // 2\n    // Square root always exists\n    const u2sq = mod(u2 * u2);\n    const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n    const D1 = mod(invsqrt * u1); // 4\n    const D2 = mod(invsqrt * u2); // 5\n    const zInv = mod(D1 * D2 * T); // 6\n    let D: bigint; // 7\n    if (isNegativeLE(T * zInv, P)) {\n      let _x = mod(Y * SQRT_M1);\n      let _y = mod(X * SQRT_M1);\n      X = _x;\n      Y = _y;\n      D = mod(D1 * INVSQRT_A_MINUS_D);\n    } else {\n      D = D2; // 8\n    }\n    if (isNegativeLE(X * zInv, P)) Y = mod(-Y); // 9\n    let s = mod((Z - Y) * D); // 10 (check footer's note, no sqrt(-a))\n    if (isNegativeLE(s, P)) s = mod(-s);\n    return Fp.toBytes(s) as TRet<Uint8Array>; // 11\n  }\n\n  /**\n   * Compares two Ristretto points.\n   * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).\n   */\n  equals(other: _RistrettoPoint): boolean {\n    this.assertSame(other);\n    const { X: X1, Y: Y1 } = this.ep;\n    const { X: X2, Y: Y2 } = other.ep;\n    const mod = (n: bigint) => Fp.create(n);\n    // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n    const one = mod(X1 * Y2) === mod(Y1 * X2);\n    const two = mod(Y1 * Y2) === mod(X1 * X2);\n    return one || two;\n  }\n\n  is0(): boolean {\n    return this.equals(_RistrettoPoint.ZERO);\n  }\n}\nObject.freeze(_RistrettoPoint.BASE);\nObject.freeze(_RistrettoPoint.ZERO);\nObject.freeze(_RistrettoPoint.prototype);\nObject.freeze(_RistrettoPoint);\n\n/** Prime-order Ristretto255 group bundle. */\nexport const ristretto255: {\n  Point: typeof _RistrettoPoint;\n} = /* @__PURE__ */ Object.freeze({ Point: _RistrettoPoint });\n\n/**\n * Hashing to ristretto255 points / field. RFC 9380 methods.\n * `hashToCurve()` is RFC 9380 Appendix B, `deriveToCurve()` is the RFC 9496\n * \u00A74.3.4 element-derivation building block, and `hashToScalar()` is a\n * library-specific helper for OPRF-style use.\n * @example\n * Hash one message onto ristretto255.\n *\n * ```ts\n * const point = ristretto255_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const ristretto255_hasher: H2CHasherBase<typeof _RistrettoPoint> = Object.freeze({\n  Point: _RistrettoPoint,\n  /**\n  * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:\n  * * There are no test vectors\n  * * encodeToCurve / mapToCurve is undefined\n  * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map!\n  * * hashToScalar is undefined too, so we just use OPRF implementation\n  * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC\n    (os2ip -> bytes255ToNumberLE)\n  * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map\n  * * hashToScalar is undefined in RFC9380 for ristretto, so we use the OPRF\n    version here. Using `bytes255ToNumblerLE` will create a different result\n    if we use `bytes255ToNumberLE` as os2ip\n  * * current version is closest to spec.\n  */\n  hashToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): _RistrettoPoint {\n    // == 'hash_to_ristretto255'\n    // Preserve explicit empty/invalid DST overrides so expand_message_xmd() can reject them.\n    const DST = options?.DST === undefined ? 'ristretto255_XMD:SHA-512_R255MAP_RO_' : options.DST;\n    const xmd = expand_message_xmd(msg, DST, 64, sha512);\n    // NOTE: RFC 9380 incorrectly calls this function `ristretto255_map`.\n    // In RFC 9496, `map` was the per-point function inside the construction.\n    // That also led to confusion that `ristretto255_map` is `mapToCurve`.\n    // It is not: it is the older hash-to-curve construction.\n    return ristretto255_hasher.deriveToCurve!(xmd);\n  },\n  hashToScalar(msg: TArg<Uint8Array>, options: TArg<H2CDSTOpts> = { DST: _DST_scalar }) {\n    const xmd = expand_message_xmd(msg, options.DST, 64, sha512);\n    return Fn.create(bytesToNumberLE(xmd));\n  },\n  /**\n   * HashToCurve-like construction based on RFC 9496 (Element Derivation).\n   * Converts 64 uniform random bytes into a curve point.\n   *\n   * WARNING: This represents an older hash-to-curve construction from before\n   * RFC 9380 was finalized.\n   * It was later reused as a component in the newer\n   * `hash_to_ristretto255` function defined in RFC 9380.\n   */\n  deriveToCurve(bytes: TArg<Uint8Array>): _RistrettoPoint {\n    // https://www.rfc-editor.org/rfc/rfc9496.html#name-element-derivation\n    abytes(bytes, 64);\n    const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));\n    const R1 = calcElligatorRistrettoMap(r1);\n    const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));\n    const R2 = calcElligatorRistrettoMap(r2);\n    return new _RistrettoPoint(R1.add(R2));\n  },\n});\n\n/**\n * ristretto255 OPRF/VOPRF/POPRF bundle, defined in RFC 9497.\n * @example\n * Run one blind/evaluate/finalize OPRF round over ristretto255.\n *\n * ```ts\n * const input = new TextEncoder().encode('hello noble');\n * const keys = ristretto255_oprf.oprf.generateKeyPair();\n * const blind = ristretto255_oprf.oprf.blind(input);\n * const evaluated = ristretto255_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded);\n * const output = ristretto255_oprf.oprf.finalize(input, blind.blind, evaluated);\n * ```\n */\nexport const ristretto255_oprf: TRet<OPRF> = /* @__PURE__ */ (() =>\n  createOPRF({\n    name: 'ristretto255-SHA512',\n    Point: _RistrettoPoint,\n    hash: sha512,\n    hashToGroup: ristretto255_hasher.hashToCurve,\n    hashToScalar: ristretto255_hasher.hashToScalar,\n  }))();\n/**\n * FROST threshold signatures over ristretto255. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 ristretto255 signing.\n *\n * ```ts\n * const alice = ristretto255_FROST.Identifier.derive('alice@example.com');\n * const bob = ristretto255_FROST.Identifier.derive('bob@example.com');\n * const carol = ristretto255_FROST.Identifier.derive('carol@example.com');\n * const deal = ristretto255_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const ristretto255_FROST: TRet<FROST> = /* @__PURE__ */ (() =>\n  createFROST({\n    name: 'FROST-RISTRETTO255-SHA512-v1',\n    Point: _RistrettoPoint,\n    validatePoint: (p) => {\n      // Prime-order wrappers are torsion-free at the abstract-group level.\n      p.assertValidity();\n    },\n    hash: sha512,\n  }))();\n\n/**\n * Weird / bogus points, useful for debugging.\n * All 8 ed25519 points of 8-torsion subgroup can be generated from the point\n * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.\n * The subgroup generated by `T` is `{ O, T, 2T, 3T, 4T, 5T, 6T, 7T }`; the\n * array below is that set, not the powers in that exact index order.\n * @example\n * Decode one known torsion point for debugging.\n *\n * ```ts\n * import { ED25519_TORSION_SUBGROUP, ed25519 } from '@noble/curves/ed25519.js';\n * const point = ed25519.Point.fromHex(ED25519_TORSION_SUBGROUP[1]);\n * ```\n */\nexport const ED25519_TORSION_SUBGROUP: readonly string[] = /* @__PURE__ */ Object.freeze([\n  '0100000000000000000000000000000000000000000000000000000000000000',\n  'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n  '0000000000000000000000000000000000000000000000000000000000000080',\n  '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n  'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n  '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n  '0000000000000000000000000000000000000000000000000000000000000000',\n  'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n]);\n", "import { Convert } from '@enbox/common';\nimport { ed25519, x25519 } from '@noble/curves/ed25519.js';\n\nimport type { Jwk } from '../jose/jwk.js';\nimport type { ComputePublicKeyParams, GetPublicKeyParams, SignParams, VerifyParams } from '../types/params-direct.js';\n\nimport { computeJwkThumbprint, isOkpPrivateJwk, isOkpPublicJwk } from '../jose/jwk.js';\n\n/**\n * The `Ed25519` class provides a comprehensive suite of utilities for working with the Ed25519\n * elliptic curve, widely used in modern cryptographic applications. This class includes methods for\n * key generation, conversion, signing, verification, and public key derivation.\n *\n * The class supports conversions between raw byte formats and JSON Web Key (JWK) formats. It\n * follows the guidelines and specifications outlined in RFC8032 for EdDSA (Edwards-curve Digital\n * Signature Algorithm) operations.\n *\n * Key Features:\n * - Key Generation: Generate Ed25519 private keys in JWK format.\n * - Key Conversion: Transform keys between raw byte arrays and JWK formats.\n * - Public Key Derivation: Derive public keys from private keys.\n * - Signing and Verification: Sign data and verify signatures with Ed25519 keys.\n * - Key Validation: Validate the mathematical correctness of Ed25519 keys.\n *\n * The methods in this class are asynchronous, returning Promises to accommodate various\n * JavaScript environments, and use `Uint8Array` for binary data handling.\n *\n * @example\n * ```ts\n * // Key Generation\n * const privateKey = await Ed25519.generateKey();\n *\n * // Public Key Derivation\n * const publicKey = await Ed25519.computePublicKey({ key: privateKey });\n * console.log(publicKey === await Ed25519.getPublicKey({ key: privateKey })); // Output: true\n *\n * // EdDSA Signing\n * const signature = await Ed25519.sign({\n *   key: privateKey,\n *   data: new TextEncoder().encode('Message')\n * });\n *\n * // EdDSA Signature Verification\n * const isValid = await Ed25519.verify({\n *   key: publicKey,\n *   signature: signature,\n *   data: new TextEncoder().encode('Message')\n * });\n *\n * // Key Conversion\n * const privateKeyBytes = await Ed25519.privateKeyToBytes({ privateKey });\n * const publicKeyBytes = await Ed25519.publicKeyToBytes({ publicKey });\n *\n * // Key Validation\n * const isPublicKeyValid = await Ed25519.validatePublicKey({ publicKeyBytes });\n * ```\n */\nexport class Ed25519 {\n  /**\n   * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method accepts a private key as a byte array (Uint8Array) for the Curve25519 curve in\n   * Twisted Edwards form and transforms it into a JWK object. The process involves first deriving\n   * the public key from the private key, then encoding both the private and public keys into\n   * base64url format.\n   *\n   * The resulting JWK object includes the following properties:\n   * - `kty`: Key Type, set to 'OKP' for Octet Key Pair.\n   * - `crv`: Curve Name, set to 'Ed25519'.\n   * - `d`: The private key component, base64url-encoded.\n   * - `x`: The computed public key, base64url-encoded.\n   *\n   * @example\n   * ```ts\n   * const privateKeyBytes = new Uint8Array([...]); // Replace with actual private key bytes\n   * const privateKey = await Ed25519.bytesToPrivateKey({ privateKeyBytes });\n   * ```\n   *\n   * @param params - The parameters for the private key conversion.\n   * @param params.privateKeyBytes - The raw private key as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the private key in JWK format.\n   */\n  public static async bytesToPrivateKey({ privateKeyBytes }: {\n    privateKeyBytes: Uint8Array;\n  }): Promise<Jwk> {\n    // Derive the public key from the private key.\n    const publicKeyBytes = ed25519.getPublicKey(privateKeyBytes);\n\n    // Construct the private key in JWK format.\n    const privateKey: Jwk = {\n      crv : 'Ed25519',\n      d   : Convert.uint8Array(privateKeyBytes).toBase64Url(),\n      kty : 'OKP',\n      x   : Convert.uint8Array(publicKeyBytes).toBase64Url(),\n    };\n\n    // Compute the JWK thumbprint and set as the key ID.\n    privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n    return privateKey;\n  }\n\n  /**\n   * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method accepts a public key as a byte array (Uint8Array) for the Curve25519 curve in\n   * Twisted Edwards form and transforms it into a JWK object. The process involves encoding the\n   * public key bytes into base64url format.\n   *\n   * The resulting JWK object includes the following properties:\n   * - `kty`: Key Type, set to 'OKP' for Octet Key Pair.\n   * - `crv`: Curve Name, set to 'X25519'.\n   * - `x`: The public key, base64url-encoded.\n   *\n   * @example\n   * ```ts\n   * const publicKeyBytes = new Uint8Array([...]); // Replace with actual public key bytes\n   * const publicKey = await X25519.bytesToPublicKey({ publicKeyBytes });\n   * ```\n   *\n   * @param params - The parameters for the public key conversion.\n   * @param params.publicKeyBytes - The raw public key as a `Uint8Array`.\n   *\n   * @returns A Promise that resolves to the public key in JWK format.\n   */\n  public static async bytesToPublicKey({ publicKeyBytes }: {\n    publicKeyBytes: Uint8Array;\n  }): Promise<Jwk> {\n    // Construct the public key in JWK format.\n    const publicKey: Jwk = {\n      kty : 'OKP',\n      crv : 'Ed25519',\n      x   : Convert.uint8Array(publicKeyBytes).toBase64Url(),\n    };\n\n    // Compute the JWK thumbprint and set as the key ID.\n    publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n    return publicKey;\n  }\n\n  /**\n   * Derives the public key in JWK format from a given Ed25519 private key.\n   *\n   * @remarks\n   * This method takes a private key in JWK format and derives its corresponding public key,\n   * also in JWK format.  The derivation process involves converting the private key to a\n   * raw byte array and then computing the corresponding public key on the Curve25519 curve in\n   * Twisted Edwards form. The public key is then encoded into base64url format to construct\n   * a JWK representation.\n   *\n   * @example\n   * ```ts\n   * const privateKey = { ... }; // A Jwk object representing an Ed25519 private key\n   * const publicKey = await Ed25519.computePublicKey({ key: privateKey });\n   * ```\n   *\n   * @param params - The parameters for the public key derivation.\n   * @param params.key - The private key in JWK format from which to derive the public key.\n   *\n   * @returns A Promise that resolves to the computed public key in JWK format.\n   */\n  public static async computePublicKey({ key }:\n    ComputePublicKeyParams\n  ): Promise<Jwk> {\n    // Convert the provided private key to a byte array.\n    const privateKeyBytes = await Ed25519.privateKeyToBytes({ privateKey: key });\n\n    // Derive the public key from the private key.\n    const publicKeyBytes = ed25519.getPublicKey(privateKeyBytes);\n\n    // Construct the public key in JWK format.\n    const publicKey: Jwk = {\n      kty : 'OKP',\n      crv : 'Ed25519',\n      x   : Convert.uint8Array(publicKeyBytes).toBase64Url()\n    };\n\n    // Compute the JWK thumbprint and set as the key ID.\n    publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n    return publicKey;\n  }\n\n  /**\n   * Converts an Ed25519 private key to its X25519 counterpart.\n   *\n   * @remarks\n   * This method enables the use of the same key pair for both digital signature (Ed25519)\n   * and key exchange (X25519) operations. It takes an Ed25519 private key and converts it\n   * to the corresponding X25519 format, facilitating interoperability between signing\n   * and encryption protocols.\n   *\n   * @example\n   * ```ts\n   * const ed25519PrivateKey = { ... }; // An Ed25519 private key in JWK format\n   * const x25519PrivateKey = await Ed25519.convertPrivateKeyToX25519({\n   *   privateKey: ed25519PrivateKey\n   * });\n   * ```\n   *\n   * @param params - The parameters for the private key conversion.\n   * @param params.privateKey - The Ed25519 private key to convert, in JWK format.\n   *\n   * @returns A Promise that resolves to the X25519 private key in JWK format.\n   */\n  public static async convertPrivateKeyToX25519({ privateKey }: {\n    privateKey: Jwk;\n  }): Promise<Jwk> {\n    // Convert the provided Ed25519 private key to bytes.\n    const ed25519PrivateKeyBytes = await Ed25519.privateKeyToBytes({ privateKey });\n\n    // Convert the Ed25519 private key to an X25519 private key.\n    const x25519PrivateKeyBytes = ed25519.utils.toMontgomerySecret(ed25519PrivateKeyBytes);\n\n    // Derive the X25519 public key from the X25519 private key.\n    const x25519PublicKeyBytes = x25519.getPublicKey(x25519PrivateKeyBytes);\n\n    // Construct the X25519 private key in JWK format.\n    const x25519PrivateKey: Jwk = {\n      kty : 'OKP',\n      crv : 'X25519',\n      d   : Convert.uint8Array(x25519PrivateKeyBytes).toBase64Url(),\n      x   : Convert.uint8Array(x25519PublicKeyBytes).toBase64Url(),\n    };\n\n    // Compute the JWK thumbprint and set as the key ID.\n    x25519PrivateKey.kid = await computeJwkThumbprint({ jwk: x25519PrivateKey });\n\n    return x25519PrivateKey;\n  }\n\n  /**\n   * Converts an Ed25519 public key to its X25519 counterpart.\n   *\n   * @remarks\n   * This method enables the use of the same key pair for both digital signature (Ed25519)\n   * and key exchange (X25519) operations. It takes an Ed25519 public key and converts it\n   * to the corresponding X25519 format, facilitating interoperability between signing\n   * and encryption protocols.\n   *\n   * @example\n   * ```ts\n   * const ed25519PublicKey = { ... }; // An Ed25519 public key in JWK format\n   * const x25519PublicKey = await Ed25519.convertPublicKeyToX25519({\n   *   publicKey: ed25519PublicKey\n   * });\n   * ```\n   *\n   * @param params - The parameters for the public key conversion.\n   * @param params.publicKey - The Ed25519 public key to convert, in JWK format.\n   *\n   * @returns A Promise that resolves to the X25519 public key in JWK format.\n   */\n  public static async convertPublicKeyToX25519({ publicKey }: {\n    publicKey: Jwk;\n  }): Promise<Jwk> {\n    // Convert the provided private key to a byte array.\n    const ed25519PublicKeyBytes = await Ed25519.publicKeyToBytes({ publicKey });\n\n    // Verify Edwards public key is valid.\n    const isValid = await Ed25519.validatePublicKey({ publicKeyBytes: ed25519PublicKeyBytes });\n    if (!isValid) {\n      throw new Error('Ed25519: Invalid public key.');\n    }\n\n    // Convert the Ed25519 public key to an X25519 private key.\n    const x25519PublicKeyBytes = ed25519.utils.toMontgomery(ed25519PublicKeyBytes);\n\n    // Construct the X25519 private key in JWK format.\n    const x25519PublicKey: Jwk = {\n      kty : 'OKP',\n      crv : 'X25519',\n      x   : Convert.uint8Array(x25519PublicKeyBytes).toBase64Url(),\n    };\n\n    // Compute the JWK thumbprint and set as the key ID.\n    x25519PublicKey.kid = await computeJwkThumbprint({ jwk: x25519PublicKey });\n\n    return x25519PublicKey;\n  }\n\n  /**\n   * Generates an Ed25519 private key in JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method creates a new private key suitable for use with the Curve25519 elliptic curve in\n   * Twisted Edwards form. The key generation process involves using cryptographically secure\n   * random number generation to ensure the uniqueness and security of the key. The resulting\n   * private key adheres to the JWK format making it compatible with common cryptographic\n   * standards and easy to use in various cryptographic processes.\n   *\n   * The generated private key in JWK format includes the following components:\n   * - `kty`: Key Type, set to 'OKP' for Octet Key Pair.\n   * - `crv`: Curve Name, set to 'Ed25519'.\n   * - `d`: The private key component, base64url-encoded.\n   * - `x`: The derived public key, base64url-encoded.\n   *\n   * @example\n   * ```ts\n   * const privateKey = await Ed25519.generateKey();\n   * ```\n   *\n   * @returns A Promise that resolves to the generated private key in JWK format.\n   */\n  public static async generateKey(): Promise<Jwk> {\n    // Generate a random private key.\n    const privateKeyBytes = ed25519.utils.randomSecretKey();\n\n    // Convert private key from bytes to JWK format.\n    const privateKey = await Ed25519.bytesToPrivateKey({ privateKeyBytes });\n\n    // Compute the JWK thumbprint and set as the key ID.\n    privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n    return privateKey;\n  }\n\n  /**\n   * Retrieves the public key properties from a given private key in JWK format.\n   *\n   * @remarks\n   * This method extracts the public key portion from an Ed25519 private key in JWK format. It does\n   * so by removing the private key property 'd' and making a shallow copy, effectively yielding the\n   * public key. The method sets the 'kid' (key ID) property using the JWK thumbprint if it is not\n   * already defined. This approach is used under the assumption that a private key in JWK format\n   * always contains the corresponding public key properties.\n   *\n   * Note: This method offers a significant performance advantage, being about 100 times faster\n   * than `computePublicKey()`. However, it does not mathematically validate the private key, nor\n   * does it derive the public key from the private key. It simply extracts existing public key\n   * properties from the private key object. This makes it suitable for scenarios where speed is\n   * critical and the private key's integrity is already assured.\n   *\n   * @example\n   * ```ts\n   * const privateKey = { ... }; // A Jwk object representing an Ed25519 private key\n   * const publicKey = await Ed25519.getPublicKey({ key: privateKey });\n   * ```\n   *\n   * @param params - The parameters for retrieving the public key properties.\n   * @param params.key - The private key in JWK format.\n   *\n   * @returns A Promise that resolves to the public key in JWK format.\n   */\n  public static async getPublicKey({ key }:\n    GetPublicKeyParams\n  ): Promise<Jwk> {\n  // Verify the provided JWK represents an octet key pair (OKP) Ed25519 private key.\n    if (!(isOkpPrivateJwk(key) && key.crv === 'Ed25519')) {\n      throw new Error(`Ed25519: The provided key is not an Ed25519 private JWK.`);\n    }\n\n    // Remove the private key property ('d') and make a shallow copy of the provided key.\n    const { d, ...publicKey } = key;\n\n    // If the key ID is undefined, set it to the JWK thumbprint.\n    publicKey.kid ??= await computeJwkThumbprint({ jwk: publicKey });\n\n    return publicKey;\n  }\n\n  /**\n   * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n   *\n   * @remarks\n   * This method accepts a private key in JWK format and extracts its raw byte representation.\n   *\n   * This method accepts a public key in JWK format and converts it into its raw binary\n   * form. The conversion process involves decoding the 'd' parameter of the JWK\n   * from base64url format into a byte array.\n   *\n   * @example\n   * ```ts\n   * const privateKey = { ... }; // An Ed25519 private key in JWK format\n   * const privateKeyBytes = await Ed25519.privateKeyToBytes({ privateKey });\n   * ```\n   *\n   * @param params - The parameters for the private key conversion.\n   * @param params.privateKey - The private key in JWK format.\n   *\n   * @returns A Promise that resolves to the private key as a Uint8Array.\n   */\n  public static async privateKeyToBytes({ privateKey }: {\n    privateKey: Jwk;\n  }): Promise<Uint8Array> {\n    // Verify the provided JWK represents a valid OKP private key.\n    if (!isOkpPrivateJwk(privateKey)) {\n      throw new Error(`Ed25519: The provided key is not a valid OKP private key.`);\n    }\n\n    // Decode the provided private key to bytes.\n    const privateKeyBytes = Convert.base64Url(privateKey.d).toUint8Array();\n\n    return privateKeyBytes;\n  }\n\n  /**\n   * Converts a public key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n   *\n   * @remarks\n   * This method accepts a public key in JWK format and converts it into its raw binary form.\n   * The conversion process involves decoding the 'x' parameter of the JWK (which represent the\n   * x coordinate of the elliptic curve point) from base64url format into a byte array.\n   *\n   * @example\n   * ```ts\n   * const publicKey = { ... }; // An Ed25519 public key in JWK format\n   * const publicKeyBytes = await Ed25519.publicKeyToBytes({ publicKey });\n   * ```\n   *\n   * @param params - The parameters for the public key conversion.\n   * @param params.publicKey - The public key in JWK format.\n   *\n   * @returns A Promise that resolves to the public key as a Uint8Array.\n   */\n  public static async publicKeyToBytes({ publicKey }: {\n    publicKey: Jwk;\n  }): Promise<Uint8Array> {\n    // Verify the provided JWK represents a valid OKP public key.\n    if (!isOkpPublicJwk(publicKey)) {\n      throw new Error(`Ed25519: The provided key is not a valid OKP public key.`);\n    }\n\n    // Decode the provided public key to bytes.\n    const publicKeyBytes = Convert.base64Url(publicKey.x).toUint8Array();\n\n    return publicKeyBytes;\n  }\n\n  /**\n   * Generates an RFC8032-compliant EdDSA signature of given data using an Ed25519 private key.\n   *\n   * @remarks\n   * This method signs the provided data with a specified private key using the EdDSA\n   * (Edwards-curve Digital Signature Algorithm) as defined in RFC8032. It\n   * involves converting the private key from JWK format to a byte array and then employing\n   * the Ed25519 algorithm to sign the data. The output is a digital signature in the form\n   * of a Uint8Array, uniquely corresponding to both the data and the private key used for\n   * signing.\n   *\n   * @example\n   * ```ts\n   * const data = new TextEncoder().encode('Messsage'); // Data to be signed\n   * const privateKey = { ... }; // A Jwk object representing an Ed25519 private key\n   * const signature = await Ed25519.sign({ key: privateKey, data });\n   * ```\n   *\n   * @param params - The parameters for the signing operation.\n   * @param params.key - The private key to use for signing, represented in JWK format.\n   * @param params.data - The data to sign, represented as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the signature as a Uint8Array.\n   */\n  public static async sign({ key, data }:\n    SignParams\n  ): Promise<Uint8Array> {\n    // Convert the private key from JWK format to bytes.\n    const privateKeyBytes = await Ed25519.privateKeyToBytes({ privateKey: key });\n\n    // Sign the provided data using the EdDSA algorithm.\n    const signature = ed25519.sign(data, privateKeyBytes);\n\n    return signature;\n  }\n\n  /**\n   * Validates a given public key to confirm its mathematical correctness on the Edwards curve.\n   *\n   * @remarks\n   * This method decodes the Edwards points from the key bytes and asserts their validity on the\n   * Curve25519 curve in Twisted Edwards form. If the points are not valid, the method returns\n   * false. If the points are valid, the method returns true.\n   *\n   * Note that this validation strictly pertains to the key's format and numerical validity; it does\n   * not assess whether the key corresponds to a known entity or its security status (e.g., whether\n   * it has been compromised).\n   *\n   * @example\n   * ```ts\n   * const publicKeyBytes = new Uint8Array([...]); // A public key in byte format\n   * const isValid = await Ed25519.validatePublicKey({ publicKeyBytes });\n   * console.log(isValid); // true if the key is valid on the Edwards curve, false otherwise\n   * ```\n   *\n   * @param params - The parameters for the public key validation.\n   * @param params.publicKeyBytes - The public key to validate, represented as a Uint8Array.\n   *\n   * @returns A Promise that resolves to a boolean indicating whether the key\n   *          corresponds to a valid point on the Edwards curve.\n   */\n  public static async validatePublicKey({ publicKeyBytes }: {\n    publicKeyBytes: Uint8Array;\n  }): Promise<boolean> {\n    try {\n    // Decode Edwards points from key bytes.\n      const point = ed25519.Point.fromBytes(publicKeyBytes);\n\n      // Check if points are on the Twisted Edwards curve.\n      point.assertValidity();\n\n    } catch {\n      return false;\n    }\n\n    return true;\n  }\n\n  /**\n   * Verifies an RFC8032-compliant EdDSA signature against given data using an Ed25519 public key.\n   *\n   * @remarks\n   * This method validates a digital signature to ensure its authenticity and integrity.\n   * It uses the EdDSA (Edwards-curve Digital Signature Algorithm) as specified in RFC8032.\n   * The verification process involves converting the public key from JWK format to a raw\n   * byte array and using the Ed25519 algorithm to validate the signature against the provided data.\n   *\n   * @example\n   * ```ts\n   * const data = new TextEncoder().encode('Messsage'); // Data that was signed\n   * const publicKey = { ... }; // A Jwk object representing an Ed25519 public key\n   * const signature = new Uint8Array([...]); // Signature to verify\n   * const isValid = await Ed25519.verify({ key: publicKey, signature, data });\n   * console.log(isValid); // true if the signature is valid, false otherwise\n   * ```\n   *\n   * @param params - The parameters for the signature verification.\n   * @param params.key - The public key in JWK format used for verification.\n   * @param params.signature - The signature to verify, represented as a Uint8Array.\n   * @param params.data - The data that was signed, represented as a Uint8Array.\n   *\n   * @returns A Promise that resolves to a boolean indicating whether the signature is valid.\n   */\n  public static async verify({ key, signature, data }:\n    VerifyParams\n  ): Promise<boolean> {\n    // Convert the public key from JWK format to bytes.\n    const publicKeyBytes = await Ed25519.publicKeyToBytes({ publicKey: key });\n\n    // Perform the verification of the signature.\n    const isValid = ed25519.verify(signature, data, publicKeyBytes);\n\n    return isValid;\n  }\n}\n", "import type { AsymmetricKeyGenerator } from '../types/key-generator.js';\nimport type { Jwk } from '../jose/jwk.js';\nimport type { Signer } from '../types/signer.js';\nimport type { AsymmetricKeyConverter, KeyConverter } from '../types/key-converter.js';\nimport type {\n  BytesToPrivateKeyParams,\n  BytesToPublicKeyParams,\n  ComputePublicKeyParams,\n  GenerateKeyParams,\n  GetPublicKeyParams,\n  PrivateKeyToBytesParams,\n  PublicKeyToBytesParams,\n  SignParams,\n  VerifyParams,\n} from '../types/params-direct.js';\n\nimport { CryptoAlgorithm } from './crypto-algorithm.js';\nimport { Ed25519 } from '../primitives/ed25519.js';\nimport { CryptoError, CryptoErrorCode } from '../crypto-error.js';\nimport { isOkpPrivateJwk, isOkpPublicJwk } from '../jose/jwk.js';\n\n/**\n * The `EdDsaGenerateKeyParams` interface defines the algorithm-specific parameters that should be\n * passed into the `generateKey()` method when using the EdDSA algorithm.\n */\nexport interface EdDsaGenerateKeyParams extends GenerateKeyParams {\n  /**\n   * A string defining the type of key to generate. The value must be one of the following:\n   * - `\"Ed25519\"`: EdDSA using the Ed25519 curve.\n   */\n  algorithm: 'Ed25519';\n}\n\n/**\n * The `EdDsaAlgorithm` class provides a concrete implementation for cryptographic operations using\n * the Edwards-curve Digital Signature Algorithm (EdDSA). This class implements both\n * {@link Signer | `Signer`} and { @link AsymmetricKeyGenerator | `AsymmetricKeyGenerator`}\n * interfaces, providing private key generation, public key derivation, and creation/verification\n * of signatures.\n *\n * This class is typically accessed through implementations that extend the\n * {@link DsaApi | `DsaApi`} interface.\n */\nexport class EdDsaAlgorithm extends CryptoAlgorithm\n  implements AsymmetricKeyGenerator<EdDsaGenerateKeyParams, Jwk, GetPublicKeyParams>,\n             KeyConverter, AsymmetricKeyConverter,\n             Signer<SignParams, VerifyParams> {\n\n  /**\n   * Converts a private key from a byte array to JWK format, setting the `alg` property to\n   * `'EdDSA'`.\n   *\n   * @param params - The parameters for the private key conversion.\n   * @param params.algorithm - The EdDSA algorithm identifier (`'Ed25519'`).\n   * @param params.privateKeyBytes - The raw private key as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the private key in JWK format.\n   */\n  public async bytesToPrivateKey({ algorithm, privateKeyBytes }:\n    BytesToPrivateKeyParams & { algorithm: 'Ed25519' }\n  ): Promise<Jwk> {\n    switch (algorithm) {\n\n      case 'Ed25519': {\n        const privateKey = await Ed25519.bytesToPrivateKey({ privateKeyBytes });\n        privateKey.alg = 'EdDSA';\n        return privateKey;\n      }\n\n      default: {\n        throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Algorithm not supported: ${algorithm}`);\n      }\n    }\n  }\n\n  /**\n   * Converts a public key from a byte array to JWK format, setting the `alg` property to\n   * `'EdDSA'`.\n   *\n   * @param params - The parameters for the public key conversion.\n   * @param params.algorithm - The EdDSA algorithm identifier (`'Ed25519'`).\n   * @param params.publicKeyBytes - The raw public key as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the public key in JWK format.\n   */\n  public async bytesToPublicKey({ algorithm, publicKeyBytes }:\n    BytesToPublicKeyParams & { algorithm: 'Ed25519' }\n  ): Promise<Jwk> {\n    switch (algorithm) {\n\n      case 'Ed25519': {\n        const publicKey = await Ed25519.bytesToPublicKey({ publicKeyBytes });\n        publicKey.alg = 'EdDSA';\n        return publicKey;\n      }\n\n      default: {\n        throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Algorithm not supported: ${algorithm}`);\n      }\n    }\n  }\n\n  /**\n   * Derives the public key in JWK format from a given private key.\n   *\n   * @remarks\n   * This method takes a private key in JWK format and derives its corresponding public key,\n   * also in JWK format. The process ensures that the derived public key correctly corresponds to\n   * the given private key.\n   *\n   * @example\n   * ```ts\n   * const eddsa = new EdDsaAlgorithm();\n   * const privateKey = { ... }; // A Jwk object representing a private key\n   * const publicKey = await eddsa.computePublicKey({ key: privateKey });\n   * ```\n   *\n   * @param params - The parameters for the public key derivation.\n   * @param params.key - The private key in JWK format from which to derive the public key.\n   *\n   * @returns A Promise that resolves to the derived public key in JWK format.\n   */\n  public async computePublicKey({ key }:\n    ComputePublicKeyParams\n  ): Promise<Jwk> {\n    if (!isOkpPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be an octet key pair (OKP) private key.');}\n\n    switch (key.crv) {\n\n      case 'Ed25519': {\n        const publicKey = await Ed25519.computePublicKey({ key });\n        publicKey.alg = 'EdDSA';\n        return publicKey;\n      }\n\n      default: {\n        throw new Error(`Unsupported curve: ${key.crv}`);\n      }\n    }\n  }\n\n  /**\n   * Generates a new private key with the specified algorithm in JSON Web Key (JWK) format.\n   *\n   * @example\n   * ```ts\n   * const eddsa = new EdDsaAlgorithm();\n   * const privateKey = await eddsa.generateKey({ algorithm: 'Ed25519' });\n   * ```\n   *\n   * @param params - The parameters for key generation.\n   * @param params.algorithm - The algorithm to use for key generation.\n   *\n   * @returns A Promise that resolves to the generated private key in JWK format.\n   */\n  async generateKey({ algorithm }:\n    EdDsaGenerateKeyParams\n  ): Promise<Jwk> {\n    switch (algorithm) {\n\n      case 'Ed25519': {\n        const privateKey = await Ed25519.generateKey();\n        privateKey.alg = 'EdDSA';\n        return privateKey;\n      }\n    }\n  }\n\n  /**\n   * Retrieves the public key properties from a given private key in JWK format.\n   *\n   * @remarks\n   * This method extracts the public key portion from an EdDSA private key in JWK format. It does\n   * so by removing the private key property 'd' and making a shallow copy, effectively yielding the\n   * public key.\n   *\n   * Note: This method offers a significant performance advantage, being about 100 times faster\n   * than `computePublicKey()`. However, it does not mathematically validate the private key, nor\n   * does it derive the public key from the private key. It simply extracts existing public key\n   * properties from the private key object. This makes it suitable for scenarios where speed is\n   * critical and the private key's integrity is already assured.\n   *\n   * @example\n   * ```ts\n   * const eddsa = new EdDsaAlgorithm();\n   * const privateKey = { ... }; // A Jwk object representing a private key\n   * const publicKey = await eddsa.getPublicKey({ key: privateKey });\n   * ```\n   *\n   * @param params - The parameters for retrieving the public key properties.\n   * @param params.key - The private key in JWK format.\n   *\n   * @returns A Promise that resolves to the public key in JWK format.\n   */\n  public async getPublicKey({ key }:\n    GetPublicKeyParams\n  ): Promise<Jwk> {\n    if (!isOkpPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be an octet key pair (OKP) private key.');}\n\n    switch (key.crv) {\n\n      case 'Ed25519': {\n        const publicKey = await Ed25519.getPublicKey({ key });\n        publicKey.alg = 'EdDSA';\n        return publicKey;\n      }\n\n      default: {\n        throw new Error(`Unsupported curve: ${key.crv}`);\n      }\n    }\n  }\n\n  /**\n   * Generates an EdDSA signature of given data using a private key.\n   *\n   * @remarks\n   * This method uses the signature algorithm determined by the given `algorithm` to sign the\n   * provided data.\n   *\n   * The signature can later be verified by parties with access to the corresponding\n   * public key, ensuring that the data has not been tampered with and was indeed signed by the\n   * holder of the private key.\n   *\n   * @example\n   * ```ts\n   * const eddsa = new EdDsaAlgorithm();\n   * const data = new TextEncoder().encode('Message');\n   * const privateKey = { ... }; // A Jwk object representing a private key\n   * const signature = await eddsa.sign({\n   *   key: privateKey,\n   *   data\n   * });\n   * ```\n   *\n   * @param params - The parameters for the signing operation.\n   * @param params.key - The private key to use for signing, represented in JWK format.\n   * @param params.data - The data to sign.\n   *\n   * @returns A Promise resolving to the digital signature as a `Uint8Array`.\n   */\n  public async sign({ key, data }:\n    SignParams\n  ): Promise<Uint8Array> {\n    if (!isOkpPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be an octet key pair (OKP) private key.');}\n\n    switch (key.crv) {\n\n      case 'Ed25519': {\n        return await Ed25519.sign({ key, data });\n      }\n\n      default: {\n        throw new Error(`Unsupported curve: ${key.crv}`);\n      }\n    }\n  }\n\n  /**\n   * Verifies an EdDSA signature associated with the provided data using the provided key.\n   *\n   * @remarks\n   * This method uses the signature algorithm determined by the `crv` property of the provided key\n   * to check the validity of a digital signature against the original data. It confirms whether the\n   * signature was created by the holder of the corresponding private key and that the data has not\n   * been tampered with.\n   *s\n   * @example\n   * ```ts\n   * const eddsa = new EdDsaAlgorithm();\n   * const publicKey = { ... }; // Public key in JWK format corresponding to the private key that signed the data\n   * const signature = new Uint8Array([...]); // Signature to verify\n   * const data = new TextEncoder().encode('Message');\n   * const isValid = await eddsa.verify({\n   *   key: publicKey,\n   *   signature,\n   *   data\n   * });\n   * ```\n   *\n   * @param params - The parameters for the verification operation.\n   * @param params.key - The key to use for verification.\n   * @param params.signature - The signature to verify.\n   * @param params.data - The data to verify.\n   *\n   * @returns A Promise resolving to a boolean indicating whether the signature is valid.\n   */\n  public async verify({ key, signature, data }:\n    VerifyParams\n  ): Promise<boolean> {\n    if (!isOkpPublicJwk(key)) {throw new TypeError('Invalid key provided. Must be an octet key pair (OKP) public key.');}\n\n    switch (key.crv) {\n\n      case 'Ed25519': {\n        return await Ed25519.verify({ key, signature, data });\n      }\n\n      default: {\n        throw new Error(`Unsupported curve: ${key.crv}`);\n      }\n    }\n  }\n\n  /**\n   * Converts a private key from JWK format to a byte array.\n   *\n   * @param params - The parameters for the private key conversion.\n   * @param params.privateKey - The private key in JWK format.\n   *\n   * @returns A Promise that resolves to the private key as a Uint8Array.\n   */\n  public async privateKeyToBytes({ privateKey }:\n    PrivateKeyToBytesParams\n  ): Promise<Uint8Array> {\n    switch (privateKey.crv) {\n\n      case 'Ed25519': {\n        return await Ed25519.privateKeyToBytes({ privateKey });\n      }\n\n      default: {\n        throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Curve not supported: ${privateKey.crv}`);\n      }\n    }\n  }\n\n  /**\n   * Converts a public key from JWK format to a byte array.\n   *\n   * @param params - The parameters for the public key conversion.\n   * @param params.publicKey - The public key in JWK format.\n   *\n   * @returns A Promise that resolves to the public key as a Uint8Array.\n   */\n  public async publicKeyToBytes({ publicKey }:\n    PublicKeyToBytesParams\n  ): Promise<Uint8Array> {\n    switch (publicKey.crv) {\n\n      case 'Ed25519': {\n        return await Ed25519.publicKeyToBytes({ publicKey });\n      }\n\n      default: {\n        throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Curve not supported: ${publicKey.crv}`);\n      }\n    }\n  }\n}", "import type { DigestParams } from '../types/params-direct.js';\nimport type { Hasher } from '../types/hasher.js';\n\nimport { CryptoAlgorithm } from './crypto-algorithm.js';\nimport { Sha256 } from '../primitives/sha256.js';\n\n/**\n * The `Sha2DigestParams` interface defines the algorithm-specific parameters that should be\n * passed into the `digest()` method when using the SHA-2 algorithm.\n */\nexport interface Sha2DigestParams extends DigestParams {\n  /**\n   * A string defining the name of hash function to use. The value must be one of the following:\n   * - `\"SHA-256\"`: Generates a 256-bit digest.\n   */\n  algorithm: 'SHA-256';\n}\n\n/**\n * The `Sha2Algorithm` class is an implementation of the {@link Hasher | `Hasher`} interface for the\n * SHA-2 family of cryptographic hash functions. The `digest` method takes the algorithm identifier\n * of the hash function and arbitrary data as input and returns the hash digest of the data.\n *\n * This class is typically accessed through implementations that extend the\n * {@link DsaApi | `DsaApi`} interface.\n */\nexport class Sha2Algorithm extends CryptoAlgorithm\n  implements Hasher<Sha2DigestParams> {\n\n  /**\n   * Generates a hash digest of the provided data.\n   *\n   * @remarks\n   * A digest is the output of the hash function. It's a fixed-size string of bytes\n   * that uniquely represents the data input into the hash function. The digest is often used for\n   * data integrity checks, as any alteration in the input data results in a significantly\n   * different digest.\n   *\n   * It takes the algorithm identifier of the hash function and data to digest as input and returns\n   * the digest of the data.\n   *\n   * @example\n   * ```ts\n   * const sha2 = new Sha2Algorithm();\n   * const data = new TextEncoder().encode('Messsage');\n   * const digest = await sha2.digest({ data });\n   * ```\n   *\n   * @param params - The parameters for the digest operation.\n   * @param params.algorithm - The name of hash function to use.\n   * @param params.data - The data to digest.\n   *\n   * @returns A Promise which will be fulfilled with the hash digest.\n   */\n  public async digest({ algorithm, data }: Sha2DigestParams): Promise<Uint8Array> {\n    switch (algorithm) {\n\n      case 'SHA-256': {\n        const hash = await Sha256.digest({ data });\n        return hash;\n      }\n    }\n\n  }\n}", "import { Convert } from '@enbox/common';\nimport { x25519 } from '@noble/curves/ed25519.js';\n\nimport type { Jwk } from '../jose/jwk.js';\nimport type { ComputePublicKeyParams, GetPublicKeyParams } from '../types/params-direct.js';\n\nimport { computeJwkThumbprint, isOkpPrivateJwk, isOkpPublicJwk } from '../jose/jwk.js';\n\n/**\n * The `X25519` class provides a comprehensive suite of utilities for working with the X25519\n * elliptic curve, widely used for key agreement protocols and cryptographic applications. It\n * provides methods for key generation, conversion, and Elliptic Curve Diffie-Hellman (ECDH)\n * key agreement,  all aligned with standard cryptographic practices.\n *\n * The class supports conversions between raw byte formats and JSON Web Key (JWK) formats,\n * making it versatile for various cryptographic tasks. It adheres to RFC6090 for ECDH, ensuring\n * secure and effective handling of keys and cryptographic operations.\n *\n * Key Features:\n * - Key Generation: Generate X25519 private keys in JWK format.\n * - Key Conversion: Transform keys between raw byte arrays and JWK formats.\n * - Public Key Derivation: Derive public keys from private keys.\n * - ECDH Shared Secret Computation: Securely derive shared secrets using private and public keys.\n *\n * The methods in this class are asynchronous, returning Promises to accommodate various\n * JavaScript environments.\n *\n * @example\n * ```ts\n * // Key Generation\n * const privateKey = await X25519.generateKey();\n *\n * // Public Key Derivation\n * const publicKey = await X25519.computePublicKey({ key: privateKey });\n * console.log(publicKey === await X25519.getPublicKey({ key: privateKey })); // Output: true\n *\n * // ECDH Shared Secret Computation\n * const sharedSecret = await X25519.sharedSecret({\n *   privateKeyA: privateKey,\n *   publicKeyB: anotherPublicKey\n * });\n *\n * // Key Conversion\n * const publicKeyBytes = await X25519.publicKeyToBytes({ publicKey });\n * const privateKeyBytes = await X25519.privateKeyToBytes({ privateKey });\n * ```\n */\nexport class X25519 {\n  /**\n   * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method accepts a private key as a byte array (Uint8Array) for the X25519 elliptic curve\n   * and transforms it into a JWK object. The process involves first deriving the public key from\n   * the private key, then encoding both the private and public keys into base64url format.\n   *\n   * The resulting JWK object includes the following properties:\n   * - `kty`: Key Type, set to 'OKP' for Octet Key Pair.\n   * - `crv`: Curve Name, set to 'X25519'.\n   * - `d`: The private key component, base64url-encoded.\n   * - `x`: The derived public key, base64url-encoded.\n   *\n   * This method is useful for converting raw public keys into a standardized\n   * JSON format, facilitating their use in cryptographic operations and making\n   * them easy to share and store.\n   *\n   * @example\n   * ```ts\n   * const privateKeyBytes = new Uint8Array([...]); // Replace with actual private key bytes\n   * const privateKey = await X25519.bytesToPrivateKey({ privateKeyBytes });\n   * ```\n   *\n   * @param params - The parameters for the private key conversion.\n   * @param params.privateKeyBytes - The raw private key as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the private key in JWK format.\n   */\n  public static async bytesToPrivateKey({ privateKeyBytes }: {\n    privateKeyBytes: Uint8Array;\n  }): Promise<Jwk> {\n    // Derive the public key from the private key.\n    const publicKeyBytes = x25519.getPublicKey(privateKeyBytes);\n\n    // Construct the private key in JWK format.\n    const privateKey: Jwk = {\n      kty : 'OKP',\n      crv : 'X25519',\n      d   : Convert.uint8Array(privateKeyBytes).toBase64Url(),\n      x   : Convert.uint8Array(publicKeyBytes).toBase64Url(),\n    };\n\n    // Compute the JWK thumbprint and set as the key ID.\n    privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n    return privateKey;\n  }\n\n  /**\n   * Converts a raw public key in bytes to its corresponding JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method accepts a public key as a byte array (Uint8Array) for the X25519 elliptic curve\n   * and transforms it into a JWK object. The conversion process involves encoding the public\n   * key bytes into base64url format.\n   *\n   * The resulting JWK object includes the following properties:\n   * - `kty`: Key Type, set to 'OKP' for Octet Key Pair.\n   * - `crv`: Curve Name, set to 'X25519'.\n   * - `x`: The public key, base64url-encoded.\n   *\n   * This method is useful for converting raw public keys into a standardized\n   * JSON format, facilitating their use in cryptographic operations and making\n   * them easy to share and store.\n   *\n   * @example\n   * ```ts\n   * const publicKeyBytes = new Uint8Array([...]); // Replace with actual public key bytes\n   * const publicKey = await X25519.bytesToPublicKey({ publicKeyBytes });\n   * ```\n   *\n   * @param params - The parameters for the public key conversion.\n   * @param params.publicKeyBytes - The raw public key as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the public key in JWK format.\n   */\n  public static async bytesToPublicKey({ publicKeyBytes }: {\n    publicKeyBytes: Uint8Array;\n  }): Promise<Jwk> {\n    // Construct the public key in JWK format.\n    const publicKey: Jwk = {\n      kty : 'OKP',\n      crv : 'X25519',\n      x   : Convert.uint8Array(publicKeyBytes).toBase64Url(),\n    };\n\n    // Compute the JWK thumbprint and set as the key ID.\n    publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n    return publicKey;\n  }\n\n  /**\n   * Derives the public key in JWK format from a given X25519 private key.\n   *\n   * @remarks\n   * This method takes a private key in JWK format and derives its corresponding public key,\n   * also in JWK format.  The derivation process involves converting the private key to a\n   * raw byte array and then computing the corresponding public key on the Curve25519 curve.\n   * The public key is then encoded into base64url format to construct a JWK representation.\n   *\n   * The process ensures that the derived public key correctly corresponds to the given private key,\n   * adhering to the Curve25519 elliptic curve in Twisted Edwards form standards. This method is\n   * useful in cryptographic operations where a public key is needed for operations like signature\n   * verification, but only the private key is available.\n   *\n   * @example\n   * ```ts\n   * const privateKey = { ... }; // A Jwk object representing an X25519 private key\n   * const publicKey = await X25519.computePublicKey({ key: privateKey });\n   * ```\n   *\n   * @param params - The parameters for the public key derivation.\n   * @param params.key - The private key in JWK format from which to derive the public key.\n   *\n   * @returns A Promise that resolves to the derived public key in JWK format.\n   */\n  public static async computePublicKey({ key }:\n    ComputePublicKeyParams\n  ): Promise<Jwk> {\n    // Convert the provided private key to a byte array.\n    const privateKeyBytes = await X25519.privateKeyToBytes({ privateKey: key });\n\n    // Derive the public key from the private key.\n    const publicKeyBytes = x25519.getPublicKey(privateKeyBytes);\n\n    // Construct the public key in JWK format.\n    const publicKey: Jwk = {\n      kty : 'OKP',\n      crv : 'X25519',\n      x   : Convert.uint8Array(publicKeyBytes).toBase64Url()\n    };\n\n    // Compute the JWK thumbprint and set as the key ID.\n    publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n    return publicKey;\n  }\n\n  /**\n   * Generates an X25519 private key in JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method creates a new private key suitable for use with the X25519 elliptic curve.\n   * The key generation process involves using cryptographically secure random number generation\n   * to ensure the uniqueness and security of the key. The resulting private key adheres to the\n   * JWK format making it compatible with common cryptographic standards and easy to use in various\n   * cryptographic processes.\n   *\n   * The generated private key in JWK format includes the following components:\n   * - `kty`: Key Type, set to 'OKP' for Octet Key Pair.\n   * - `crv`: Curve Name, set to 'X25519'.\n   * - `d`: The private key component, base64url-encoded.\n   * - `x`: The derived public key, base64url-encoded.\n   *\n   * The key is returned in a format suitable for direct use in key agreement operations.\n   *\n   * @example\n   * ```ts\n   * const privateKey = await X25519.generateKey();\n   * ```\n   *\n   * @returns A Promise that resolves to the generated private key in JWK format.\n   */\n  public static async generateKey(): Promise<Jwk> {\n    // Generate a random private key.\n    const privateKeyBytes = x25519.utils.randomSecretKey();\n\n    // Convert private key from bytes to JWK format.\n    const privateKey = await X25519.bytesToPrivateKey({ privateKeyBytes });\n\n    // Compute the JWK thumbprint and set as the key ID.\n    privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n    return privateKey;\n  }\n\n  /**\n   * Retrieves the public key properties from a given private key in JWK format.\n   *\n   * @remarks\n   * This method extracts the public key portion from an X25519 private key in JWK format. It does\n   * so by removing the private key property 'd' and making a shallow copy, effectively yielding the\n   * public key. The method sets the 'kid' (key ID) property using the JWK thumbprint if it is not\n   * already defined. This approach is used under the assumption that a private key in JWK format\n   * always contains the corresponding public key properties.\n   *\n   * Note: This method offers a significant performance advantage, being about 500 times faster\n   * than `computePublicKey()`. However, it does not mathematically validate the private key, nor\n   * does it derive the public key from the private key. It simply extracts existing public key\n   * properties from the private key object. This makes it suitable for scenarios where speed is\n   * critical and the private key's integrity is already assured.\n   *\n   * @example\n   * ```ts\n   * const privateKey = { ... }; // A Jwk object representing an X25519 private key\n   * const publicKey = await X25519.getPublicKey({ key: privateKey });\n   * ```\n   *\n   * @param params - The parameters for retrieving the public key properties.\n   * @param params.key - The private key in JWK format.\n   *\n   * @returns A Promise that resolves to the public key in JWK format.\n   */\n  public static async getPublicKey({ key }:\n    GetPublicKeyParams\n  ): Promise<Jwk> {\n  // Verify the provided JWK represents an octet key pair (OKP) X25519 private key.\n    if (!(isOkpPrivateJwk(key) && key.crv === 'X25519')) {\n      throw new Error(`X25519: The provided key is not an X25519 private JWK.`);\n    }\n\n    // Remove the private key property ('d') and make a shallow copy of the provided key.\n    const { d, ...publicKey } = key;\n\n    // If the key ID is undefined, set it to the JWK thumbprint.\n    publicKey.kid ??= await computeJwkThumbprint({ jwk: publicKey });\n\n    return publicKey;\n  }\n\n  /**\n   * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n   *\n   * @remarks\n   * This method accepts a private key in JWK format and extracts its raw byte representation.\n   *\n   * This method accepts a public key in JWK format and converts it into its raw binary\n   * form. The conversion process involves decoding the 'd' parameter of the JWK\n   * from base64url format into a byte array.\n   *\n   * This conversion is essential for operations that require the private key in its raw\n   * binary form, such as certain low-level cryptographic operations or when interfacing\n   * with systems and libraries that expect keys in a byte array format.\n   *\n   * @example\n   * ```ts\n   * const privateKey = { ... }; // An X25519 private key in JWK format\n   * const privateKeyBytes = await X25519.privateKeyToBytes({ privateKey });\n   * ```\n   *\n   * @param params - The parameters for the private key conversion.\n   * @param params.privateKey - The private key in JWK format.\n   *\n   * @returns A Promise that resolves to the private key as a Uint8Array.\n   */\n  public static async privateKeyToBytes({ privateKey }: {\n    privateKey: Jwk;\n  }): Promise<Uint8Array> {\n    // Verify the provided JWK represents a valid OKP private key.\n    if (!isOkpPrivateJwk(privateKey)) {\n      throw new Error(`X25519: The provided key is not a valid OKP private key.`);\n    }\n\n    // Decode the provided private key to bytes.\n    const privateKeyBytes = Convert.base64Url(privateKey.d).toUint8Array();\n\n    return privateKeyBytes;\n  }\n\n  /**\n   * Converts a public key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n   *\n   * @remarks\n   * This method accepts a public key in JWK format and converts it into its raw binary form.\n   * The conversion process involves decoding the 'x' parameter of the JWK (which represent the\n   * x coordinate of the elliptic curve point) from base64url format into a byte array.\n   *\n   * This conversion is essential for operations that require the public key in its raw\n   * binary form, such as certain low-level cryptographic operations or when interfacing\n   * with systems and libraries that expect keys in a byte array format.\n   *\n   * @example\n   * ```ts\n   * const publicKey = { ... }; // An X25519 public key in JWK format\n   * const publicKeyBytes = await X25519.publicKeyToBytes({ publicKey });\n   * ```\n   *\n   * @param params - The parameters for the public key conversion.\n   * @param params.publicKey - The public key in JWK format.\n   *\n   * @returns A Promise that resolves to the public key as a Uint8Array.\n   */\n  public static async publicKeyToBytes({ publicKey }: {\n    publicKey: Jwk;\n  }): Promise<Uint8Array> {\n    // Verify the provided JWK represents a valid OKP public key.\n    if (!isOkpPublicJwk(publicKey)) {\n      throw new Error(`X25519: The provided key is not a valid OKP public key.`);\n    }\n\n    // Decode the provided public key to bytes.\n    const publicKeyBytes = Convert.base64Url(publicKey.x).toUint8Array();\n\n    return publicKeyBytes;\n  }\n\n  /**\n   * Computes an X25519 Elliptic Curve Diffie-Hellman (ECDH) shared secret\n   * using X25519 private and public keys in JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method facilitates the ECDH key agreement protocol, which is a method of securely\n   * deriving a shared secret between two parties based on their private and public keys.\n   * It takes the private key of one party (privateKeyA) and the public key of another\n   * party (publicKeyB) to compute a shared secret. The shared secret is the raw output\n   * of the X25519 function as defined in RFC 7748.\n   *\n   * Note: Unlike Weierstrass curves (e.g., secp256k1), X25519 is a Montgomery curve\n   * where the ECDH output is a single 32-byte scalar value, not an (x, y) point.\n   * The result is used directly as the shared secret.\n   *\n   * @example\n   * ```ts\n   * const privateKeyA = { ... }; // A Jwk object for party A\n   * const publicKeyB = { ... }; // A PublicKeyJwk object for party B\n   * const sharedSecret = await X25519.sharedSecret({\n   *   privateKeyA,\n   *   publicKeyB\n   * });\n   * ```\n   *\n   * @param params - The parameters for the shared secret computation.\n   * @param params.privateKeyA - The private key in JWK format of one party.\n   * @param params.publicKeyB - The public key in JWK format of the other party.\n   *\n   * @returns A Promise that resolves to the computed shared secret as a Uint8Array.\n   */\n  public static async sharedSecret({ privateKeyA, publicKeyB }: {\n    privateKeyA: Jwk;\n    publicKeyB: Jwk;\n  }): Promise<Uint8Array> {\n    // Ensure that keys from the same key pair are not specified.\n    if ('x' in privateKeyA && 'x' in publicKeyB && privateKeyA.x === publicKeyB.x) {\n      throw new Error(`X25519: ECDH shared secret cannot be computed from a single key pair's public and private keys.`);\n    }\n\n    // Convert the provided private and public keys to bytes.\n    const privateKeyABytes = await X25519.privateKeyToBytes({ privateKey: privateKeyA });\n    const publicKeyBBytes = await X25519.publicKeyToBytes({ publicKey: publicKeyB });\n\n    // Compute the shared secret between the public and private keys.\n    const sharedSecret = x25519.getSharedSecret(privateKeyABytes, publicKeyBBytes);\n\n    return sharedSecret;\n  }\n}\n", "import type { AsymmetricKeyGenerator } from '../types/key-generator.js';\nimport type { Jwk } from '../jose/jwk.js';\nimport type { KeyConverter } from '../types/key-converter.js';\nimport type {\n  BytesToPrivateKeyParams,\n  ComputePublicKeyParams,\n  GenerateKeyParams,\n  GetPublicKeyParams,\n  PrivateKeyToBytesParams,\n} from '../types/params-direct.js';\n\nimport { CryptoAlgorithm } from './crypto-algorithm.js';\nimport { isOkpPrivateJwk } from '../jose/jwk.js';\nimport { X25519 } from '../primitives/x25519.js';\n\nimport { CryptoError, CryptoErrorCode } from '../crypto-error.js';\n\n/**\n * The `X25519GenerateKeyParams` interface defines the algorithm-specific parameters that should be\n * passed into the `generateKey()` method when using the X25519 key agreement algorithm.\n */\nexport interface X25519GenerateKeyParams extends GenerateKeyParams {\n  /**\n   * A string defining the type of key to generate. The value must be:\n   * - `\"X25519\"`: Elliptic-curve Diffie-Hellman (ECDH) using Curve25519.\n   */\n  algorithm: 'X25519';\n}\n\n/**\n * The `X25519Algorithm` class provides a concrete implementation for key generation,\n * public key derivation, and key conversion using the X25519 elliptic curve. X25519 is a\n * key agreement curve (not a signature curve) used for ECDH key exchange in JWE encryption.\n *\n * This class implements the {@link AsymmetricKeyGenerator | `AsymmetricKeyGenerator`} and\n * {@link KeyConverter | `KeyConverter`} interfaces, providing private key generation,\n * public key derivation, and byte/JWK conversion.\n */\nexport class X25519Algorithm extends CryptoAlgorithm\n  implements AsymmetricKeyGenerator<X25519GenerateKeyParams, Jwk, GetPublicKeyParams>,\n             KeyConverter {\n\n  /**\n   * Converts a raw private key in bytes to its corresponding JWK format.\n   *\n   * @param params - The parameters for the private key conversion.\n   * @param params.algorithm - Must be `'X25519'`.\n   * @param params.privateKeyBytes - The raw private key as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the private key in JWK format.\n   */\n  public async bytesToPrivateKey({ algorithm, privateKeyBytes }:\n    BytesToPrivateKeyParams & { algorithm: 'X25519' }\n  ): Promise<Jwk> {\n    switch (algorithm) {\n\n      case 'X25519': {\n        return X25519.bytesToPrivateKey({ privateKeyBytes });\n      }\n\n      default: {\n        throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Algorithm not supported: ${algorithm}`);\n      }\n    }\n  }\n\n  /**\n   * Derives the public key in JWK format from a given X25519 private key.\n   *\n   * @param params - The parameters for the public key derivation.\n   * @param params.key - The private key in JWK format from which to derive the public key.\n   *\n   * @returns A Promise that resolves to the derived public key in JWK format.\n   */\n  public async computePublicKey({ key }:\n    ComputePublicKeyParams\n  ): Promise<Jwk> {\n    if (!isOkpPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be an octet key pair (OKP) private key.');}\n\n    switch (key.crv) {\n\n      case 'X25519': {\n        return X25519.computePublicKey({ key });\n      }\n\n      default: {\n        throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Unsupported curve: ${key.crv}`);\n      }\n    }\n  }\n\n  /**\n   * Generates a new X25519 private key in JWK format.\n   *\n   * @param params - The parameters for key generation.\n   * @param params.algorithm - Must be `'X25519'`.\n   *\n   * @returns A Promise that resolves to the generated private key in JWK format.\n   */\n  async generateKey({ algorithm }:\n    X25519GenerateKeyParams\n  ): Promise<Jwk> {\n    switch (algorithm) {\n\n      case 'X25519': {\n        return X25519.generateKey();\n      }\n\n      default: {\n        throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Algorithm not supported: ${algorithm}`);\n      }\n    }\n  }\n\n  /**\n   * Retrieves the public key properties from a given X25519 private key in JWK format.\n   *\n   * @param params - The parameters for retrieving the public key properties.\n   * @param params.key - The private key in JWK format.\n   *\n   * @returns A Promise that resolves to the public key in JWK format.\n   */\n  public async getPublicKey({ key }:\n    GetPublicKeyParams\n  ): Promise<Jwk> {\n    if (!isOkpPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be an octet key pair (OKP) private key.');}\n\n    switch (key.crv) {\n\n      case 'X25519': {\n        return X25519.getPublicKey({ key });\n      }\n\n      default: {\n        throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Unsupported curve: ${key.crv}`);\n      }\n    }\n  }\n\n  /**\n   * Converts a private key from JWK format to a byte array.\n   *\n   * @param params - The parameters for the private key conversion.\n   * @param params.privateKey - The private key in JWK format.\n   *\n   * @returns A Promise that resolves to the private key as a Uint8Array.\n   */\n  public async privateKeyToBytes({ privateKey }:\n    PrivateKeyToBytesParams\n  ): Promise<Uint8Array> {\n    return X25519.privateKeyToBytes({ privateKey });\n  }\n}\n", "import type { KeyValueStore } from '@enbox/common';\nimport { MemoryStore } from '@enbox/common';\n\nimport type { CryptoAlgorithm } from './algorithms/crypto-algorithm.js';\nimport type { Hasher } from './types/hasher.js';\nimport type { Jwk } from './jose/jwk.js';\nimport type { KeyIdentifier } from './types/identifier.js';\nimport type { KeyImporterExporter } from './types/key-io.js';\nimport type { KeyManager } from './types/crypto-api.js';\nimport type { Signer } from './types/signer.js';\nimport type { AsymmetricKeyGenerator, KeyGenerator } from './types/key-generator.js';\nimport type { GetPublicKeyParams, SignParams, VerifyParams } from './types/params-direct.js';\nimport type {\n  KmsDigestParams,\n  KmsExportKeyParams,\n  KmsGenerateKeyParams,\n  KmsGetKeyUriParams,\n  KmsGetPublicKeyParams,\n  KmsImportKeyParams,\n  KmsSignParams,\n  KmsVerifyParams,\n} from './types/params-kms.js';\n\nimport { EcdsaAlgorithm } from './algorithms/ecdsa.js';\nimport { EdDsaAlgorithm } from './algorithms/eddsa.js';\nimport { Sha2Algorithm } from './algorithms/sha-2.js';\nimport { X25519Algorithm } from './algorithms/x25519.js';\nimport { computeJwkThumbprint, isPrivateJwk, KEY_URI_PREFIX_JWK } from './jose/jwk.js';\n\n/**\n * `supportedAlgorithms` is an object mapping algorithm names to their respective implementations\n * Each entry in this map specifies the algorithm name and its associated properties, including the\n * implementation class and any relevant names or identifiers for the algorithm. This structure\n * allows for easy retrieval and instantiation of algorithm implementations based on the algorithm\n * name or key specification. It facilitates the support of multiple algorithms within the\n * `LocalKeyManager` class.\n */\nconst supportedAlgorithms = {\n  'Ed25519': {\n    implementation : EdDsaAlgorithm,\n    names          : ['Ed25519'],\n  },\n  'secp256k1': {\n    implementation : EcdsaAlgorithm,\n    names          : ['ES256K', 'secp256k1'],\n  },\n  'secp256r1': {\n    implementation : EcdsaAlgorithm,\n    names          : ['ES256', 'secp256r1'],\n  },\n  'SHA-256': {\n    implementation : Sha2Algorithm,\n    names          : ['SHA-256']\n  },\n  'X25519': {\n    implementation : X25519Algorithm,\n    names          : ['X25519']\n  }\n} satisfies {\n  [key: string]: {\n    implementation : typeof CryptoAlgorithm;\n    names : string[];\n  }\n};\n\n/* Helper type for `supportedAlgorithms`. */\ntype SupportedAlgorithm = keyof typeof supportedAlgorithms;\n\n/* Helper type for `supportedAlgorithms` implementations. */\ntype AlgorithmConstructor = typeof supportedAlgorithms[SupportedAlgorithm]['implementation'];\n\n/**\n * The `LocalKeyManagerParams` interface specifies the parameters for initializing an instance of\n * `LocalKeyManager`. It allows the optional inclusion of a `KeyValueStore` instance for key\n * management. If not provided, a default `MemoryStore` instance will be used for storing keys in\n * memory. Note that the `MemoryStore` is not persistent and will be cleared when the application\n * exits.\n */\nexport type LocalKeyManagerParams = {\n  /**\n   * An optional property to specify a custom `KeyValueStore` instance for key management. If not\n   * provided, {@link LocalKeyManager | `LocalKeyManager`} uses a default `MemoryStore` instance.\n   * This store is responsible for managing cryptographic keys, allowing them to be retrieved,\n   * stored, and managed during cryptographic operations.\n   */\n  keyStore?: KeyValueStore<KeyIdentifier, Jwk>;\n};\n\n/**\n * The `LocalKeyManagerDigestParams` interface defines the algorithm-specific parameters that should\n * be passed into the {@link LocalKeyManager.digest | `LocalKeyManager.digest()`} method.\n */\nexport interface LocalKeyManagerDigestParams extends KmsDigestParams {\n  /**\n   * A string defining the name of hash function to use. The value must be one of the following:\n   * - `\"SHA-256\"`: Generates a 256-bit digest.\n   */\n  algorithm: 'SHA-256';\n}\n\n/**\n * The `LocalKeyManagerGenerateKeyParams` interface defines the algorithm-specific parameters that\n * should be passed into the {@link LocalKeyManager.generateKey | `LocalKeyManager.generateKey()`}\n * method when generating a key in the local KMS.\n */\nexport interface LocalKeyManagerGenerateKeyParams extends KmsGenerateKeyParams {\n  /**\n   * A string defining the type of key to generate. The value must be one of the following:\n   * - `\"Ed25519\"`\n   * - `\"secp256k1\"`\n   */\n  algorithm: 'Ed25519' | 'secp256k1' | 'secp256r1' | 'X25519';\n}\n\nexport class LocalKeyManager implements\n    KeyManager,\n    KeyImporterExporter<KmsImportKeyParams, KeyIdentifier, KmsExportKeyParams> {\n\n  /**\n   * A private map that stores instances of cryptographic algorithm implementations. Each key in\n   * this map is an `AlgorithmConstructor`, and its corresponding value is an instance of a class\n   * that implements a specific cryptographic algorithm. This map is used to cache and reuse\n   * instances for performance optimization, ensuring that each algorithm is instantiated only once.\n   */\n  private readonly _algorithmInstances: Map<AlgorithmConstructor, InstanceType<typeof CryptoAlgorithm>> = new Map();\n\n  /**\n   * The `_keyStore` private variable in `LocalKeyManager` is a `KeyValueStore` instance used for\n   * storing and managing cryptographic keys. It allows the `LocalKeyManager` class to save,\n   * retrieve, and handle keys efficiently within the local Key Management System (KMS) context.\n   * This variable can be configured to use different storage backends, like in-memory storage or\n   * persistent storage, providing flexibility in key management according to the application's\n   * requirements.\n   */\n  private readonly _keyStore: KeyValueStore<KeyIdentifier, Jwk>;\n\n  constructor(params?: LocalKeyManagerParams) {\n    this._keyStore = params?.keyStore ?? new MemoryStore<KeyIdentifier, Jwk>();\n  }\n\n  /**\n   * Generates a hash digest of the provided data.\n   *\n   * @remarks\n   * A digest is the output of the hash function. It's a fixed-size string of bytes\n   * that uniquely represents the data input into the hash function. The digest is often used for\n   * data integrity checks, as any alteration in the input data results in a significantly\n   * different digest.\n   *\n   * It takes the algorithm identifier of the hash function and data to digest as input and returns\n   * the digest of the data.\n   *\n   * @example\n   * ```ts\n   * const keyManager = new LocalKeyManager();\n   * const data = new Uint8Array([...]);\n   * const digest = await keyManager.digest({ algorithm: 'SHA-256', data });\n   * ```\n   *\n   * @param params - The parameters for the digest operation.\n   * @param params.algorithm - The name of hash function to use.\n   * @param params.data - The data to digest.\n   *\n   * @returns A Promise which will be fulfilled with the hash digest.\n   */\n  public async digest({ algorithm, data }:\n    LocalKeyManagerDigestParams\n  ): Promise<Uint8Array> {\n    // Get the hash function implementation based on the specified `algorithm` parameter.\n    const hasher = this.getAlgorithm({ algorithm }) as Hasher<KmsDigestParams>;\n\n    // Compute the hash.\n    const hash = await hasher.digest({ algorithm, data });\n\n    return hash;\n  }\n\n  /**\n   * Exports a private key identified by the provided key URI from the local KMS.\n   *\n   * @remarks\n   * This method retrieves the key from the key store and returns it. It is primarily used\n   * for extracting keys for backup or transfer purposes.\n   *\n   * @example\n   * ```ts\n   * const keyManager = new LocalKeyManager();\n   * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n   * const privateKey = await keyManager.exportKey({ keyUri });\n   * ```\n   *\n   * @param params - Parameters for exporting the key.\n   * @param params.keyUri - The key URI identifying the key to export.\n   *\n   * @returns A Promise resolving to the JWK representation of the exported key.\n   */\n  public async exportKey({ keyUri }:\n    KmsExportKeyParams\n  ): Promise<Jwk> {\n    // Get the private key from the key store.\n    const privateKey = await this.getPrivateKey({ keyUri });\n\n    return privateKey;\n  }\n\n  /**\n   * Generates a new cryptographic key in the local KMS with the specified algorithm and returns a\n   * unique key URI which can be used to reference the key in subsequent operations.\n   *\n   * @example\n   * ```ts\n   * const keyManager = new LocalKeyManager();\n   * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n   * console.log(keyUri); // Outputs the key URI\n   * ```\n   *\n   * @param params - The parameters for key generation.\n   * @param params.algorithm - The algorithm to use for key generation, defined in `SupportedAlgorithm`.\n   *\n   * @returns A Promise that resolves to the key URI, a unique identifier for the generated key.\n   */\n  public async generateKey({ algorithm }:\n    LocalKeyManagerGenerateKeyParams\n  ): Promise<KeyIdentifier> {\n    // Get the key generator implementation based on the specified `algorithm` parameter.\n    const keyGenerator = this.getAlgorithm({ algorithm }) as KeyGenerator<LocalKeyManagerGenerateKeyParams, Jwk>;\n\n    // Generate the key.\n    const key = await keyGenerator.generateKey({ algorithm });\n\n    if (key?.kid === undefined) {\n      throw new Error('Generated key is missing a required property: kid');\n    }\n\n    // Construct the key URI.\n    const keyUri = `${KEY_URI_PREFIX_JWK}${key.kid}`;\n\n    // Store the key in the key store.\n    await this._keyStore.set(keyUri, key);\n\n    return keyUri;\n  }\n\n  /**\n   * Computes the Key URI for a given public JWK (JSON Web Key).\n   *\n   * @remarks\n   * This method generates a {@link https://datatracker.ietf.org/doc/html/rfc3986 | URI}\n   * (Uniform Resource Identifier) for the given JWK, which uniquely identifies the key across all\n   * `KeyManager` implementations. The key URI is constructed by appending the\n   * {@link https://datatracker.ietf.org/doc/html/rfc7638 | JWK thumbprint} to the prefix\n   * `urn:jwk:`. The JWK thumbprint is deterministically computed from the JWK and is consistent\n   * regardless of property order or optional property inclusion in the JWK. This ensures that the\n   * same key material represented as a JWK will always yield the same thumbprint, and therefore,\n   * the same key URI.\n   *\n   * @example\n   * ```ts\n   * const keyManager = new LocalKeyManager();\n   * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n   * const publicKey = await keyManager.getPublicKey({ keyUri });\n   * const keyUriFromPublicKey = await keyManager.getKeyUri({ key: publicKey });\n   * console.log(keyUri === keyUriFromPublicKey); // Outputs `true`\n   * ```\n   *\n   * @param params - The parameters for getting the key URI.\n   * @param params.key - The JWK for which to compute the key URI.\n   *\n   * @returns A Promise that resolves to the key URI as a string.\n   */\n  public async getKeyUri({ key }:\n    KmsGetKeyUriParams\n  ): Promise<KeyIdentifier> {\n    // Compute the JWK thumbprint.\n    const jwkThumbprint = await computeJwkThumbprint({ jwk: key });\n\n    // Construct the key URI by appending the JWK thumbprint to the key URI prefix.\n    const keyUri = `${KEY_URI_PREFIX_JWK}${jwkThumbprint}`;\n\n    return keyUri;\n  }\n\n  /**\n   * Retrieves the public key associated with a previously generated private key, identified by\n   * the provided key URI.\n   *\n   * @example\n   * ```ts\n   * const keyManager = new LocalKeyManager();\n   * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n   * const publicKey = await keyManager.getPublicKey({ keyUri });\n   * ```\n   *\n   * @param params - The parameters for retrieving the public key.\n   * @param params.keyUri - The key URI of the private key to retrieve the public key for.\n   *\n   * @returns A Promise that resolves to the public key in JWK format.\n   */\n  public async getPublicKey({ keyUri }:\n    KmsGetPublicKeyParams\n  ): Promise<Jwk> {\n    // Get the private key from the key store.\n    const privateKey = await this.getPrivateKey({ keyUri });\n\n    // Determine the algorithm name based on the JWK's `alg` and `crv` properties.\n    const algorithm = this.getAlgorithmName({ key: privateKey });\n\n    // Get the key generator based on the algorithm name.\n    const keyGenerator = this.getAlgorithm({ algorithm }) as AsymmetricKeyGenerator<LocalKeyManagerGenerateKeyParams, Jwk, GetPublicKeyParams>;\n\n    // Get the public key properties from the private JWK.\n    const publicKey = await keyGenerator.getPublicKey({ key: privateKey });\n\n    return publicKey;\n  }\n\n  /**\n   * Imports a private key into the local KMS.\n   *\n   * @remarks\n   * This method stores the provided JWK in the key store, making it available for subsequent\n   * cryptographic operations. It is particularly useful for initializing the KMS with pre-existing\n   * keys or for restoring keys from backups.\n   *\n   * Note that, if defined, the `kid` (key ID) property of the JWK is used as the key URI for the\n   * imported key. If the `kid` property is not provided, the key URI is computed from the JWK\n   * thumbprint of the key.\n   *\n   * @example\n   * ```ts\n   * const keyManager = new LocalKeyManager();\n   * const privateKey = { ... } // A private key in JWK format\n   * const keyUri = await keyManager.importKey({ key: privateKey });\n   * ```\n   *\n   * @param params - Parameters for importing the key.\n   * @param params.key - The private key to import to in JWK format.\n   *\n   * @returns A Promise resolving to the key URI, uniquely identifying the imported key.\n   */\n  public async importKey({ key }:\n    KmsImportKeyParams\n  ): Promise<KeyIdentifier> {\n    if (!isPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be a private key in JWK format.');}\n\n    // Make a deep copy of the key to avoid mutating the original.\n    const privateKey = structuredClone(key);\n\n    // If the key ID is undefined, set it to the JWK thumbprint.\n    privateKey.kid ??= await computeJwkThumbprint({ jwk: privateKey });\n\n    // Compute the key URI for the key.\n    const keyUri = await this.getKeyUri({ key: privateKey });\n\n    // Store the key in the key store.\n    await this._keyStore.set(keyUri, privateKey);\n\n    return keyUri;\n  }\n\n  /**\n   * Signs the provided data using the private key identified by the provided key URI.\n   *\n   * @remarks\n   * This method uses the signature algorithm determined by the `alg` and/or `crv` properties of the\n   * private key identified by the provided key URI to sign the provided data. The signature can\n   * later be verified by parties with access to the corresponding public key, ensuring that the\n   * data has not been tampered with and was indeed signed by the holder of the private key.\n   *\n   * @example\n   * ```ts\n   * const keyManager = new LocalKeyManager();\n   * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n   * const data = new TextEncoder().encode('Message to sign');\n   * const signature = await keyManager.sign({ keyUri, data });\n   * ```\n   *\n   * @param params - The parameters for the signing operation.\n   * @param params.keyUri - The key URI of the private key to use for signing.\n   * @param params.data - The data to sign.\n   *\n   * @returns A Promise resolving to the digital signature as a `Uint8Array`.\n   */\n  public async sign({ keyUri, data }:\n    KmsSignParams\n  ): Promise<Uint8Array> {\n    // Get the private key from the key store.\n    const privateKey = await this.getPrivateKey({ keyUri });\n\n    // Determine the algorithm name based on the JWK's `alg` and `crv` properties.\n    const algorithm = this.getAlgorithmName({ key: privateKey });\n\n    // Get the signature algorithm based on the algorithm name.\n    const signer = this.getAlgorithm({ algorithm }) as Signer<SignParams, VerifyParams>;\n\n    // Sign the data.\n    const signature = signer.sign({ data, key: privateKey });\n\n    return signature;\n  }\n\n  /**\n   * Verifies a digital signature associated the provided data using the provided key.\n   *\n   * @remarks\n   * This method uses the signature algorithm determined by the `alg` and/or `crv` properties of the\n   * provided key to check the validity of a digital signature against the original data. It\n   * confirms whether the signature was created by the holder of the corresponding private key and\n   * that the data has not been tampered with.\n   *\n   * @example\n   * ```ts\n   * const keyManager = new LocalKeyManager();\n   * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n   * const data = new TextEncoder().encode('Message to sign');\n   * const signature = await keyManager.sign({ keyUri, data });\n   * const isSignatureValid = await keyManager.verify({ keyUri, data, signature });\n   * ```\n   *\n   * @param params - The parameters for the verification operation.\n   * @param params.key - The key to use for verification.\n   * @param params.signature - The signature to verify.\n   * @param params.data - The data to verify.\n   *\n   * @returns A Promise resolving to a boolean indicating whether the signature is valid.\n   */\n  public async verify({ key, signature, data }:\n    KmsVerifyParams\n  ): Promise<boolean> {\n    // Determine the algorithm name based on the JWK's `alg` and `crv` properties.\n    const algorithm = this.getAlgorithmName({ key });\n\n    // Get the signature algorithm based on the algorithm name.\n    const signer = this.getAlgorithm({ algorithm }) as Signer<SignParams, VerifyParams>;\n\n    // Verify the signature.\n    const isSignatureValid = signer.verify({ key, signature, data });\n\n    return isSignatureValid;\n  }\n\n  /**\n   * Retrieves an algorithm implementation instance based on the provided algorithm name.\n   *\n   * @remarks\n   * This method checks if the requested algorithm is supported and returns a cached instance\n   * if available. If an instance does not exist, it creates and caches a new one. This approach\n   * optimizes performance by reusing algorithm instances across cryptographic operations.\n   *\n   * @example\n   * ```ts\n   * const signer = this.getAlgorithm({ algorithm: 'Ed25519' });\n   * ```\n   *\n   * @param params - The parameters for retrieving the algorithm implementation.\n   * @param params.algorithm - The name of the algorithm to retrieve.\n   *\n   * @returns An instance of the requested algorithm implementation.\n   *\n   * @throws Error if the requested algorithm is not supported.\n   */\n  private getAlgorithm({ algorithm }: {\n    algorithm: SupportedAlgorithm;\n  }): InstanceType<typeof CryptoAlgorithm> {\n    // Check if algorithm is supported.\n    const AlgorithmImplementation = supportedAlgorithms[algorithm]?.['implementation'];\n    if (!AlgorithmImplementation) {\n      throw new Error(`Algorithm not supported: ${algorithm}`);\n    }\n\n    // Check if instance already exists for the `AlgorithmImplementation`.\n    if (!this._algorithmInstances.has(AlgorithmImplementation)) {\n    // If not, create a new instance and store it in the cache\n      this._algorithmInstances.set(AlgorithmImplementation, new AlgorithmImplementation());\n    }\n\n    // Return the cached instance\n    return this._algorithmInstances.get(AlgorithmImplementation)!;\n  }\n\n  /**\n   * Determines the name of the algorithm based on the key's properties.\n   *\n   * @remarks\n   * This method facilitates the identification of the correct algorithm for cryptographic\n   * operations based on the `alg` or `crv` properties of a {@link Jwk | JWK}.\n   *\n   * @example\n   * ```ts\n   * const publicKey = { ... }; // Public key in JWK format\n   * const algorithm = this.getAlgorithmName({ key: publicKey });\n   * ```\n   *\n   * @param params - The parameters for determining the algorithm name.\n   * @param params.key - A JWK containing the `alg` or `crv` properties.\n   *\n   * @returns The name of the algorithm associated with the key.\n   *\n   * @throws Error if the algorithm cannot be determined from the provided input.\n   */\n  private getAlgorithmName({ key }: {\n    key: { alg?: string, crv?: string };\n  }): SupportedAlgorithm {\n    const algProperty = key.alg;\n    const crvProperty = key.crv;\n\n    for (const algName in supportedAlgorithms) {\n      const algorithmInfo = supportedAlgorithms[algName as SupportedAlgorithm];\n      if (algProperty && algorithmInfo.names.includes(algProperty)) {\n        return algName as SupportedAlgorithm;\n      } else if (crvProperty && algorithmInfo.names.includes(crvProperty)) {\n        return algName as SupportedAlgorithm;\n      }\n    }\n\n    throw new Error(`Unable to determine algorithm based on provided input: alg=${algProperty}, crv=${crvProperty}`);\n  }\n\n  /**\n   * Retrieves a private key from the key store based on the provided key URI.\n   *\n   * @example\n   * ```ts\n   * const privateKey = this.getPrivateKey({ keyUri: 'urn:jwk:...' });\n   * ```\n   *\n   * @param params - Parameters for retrieving the private key.\n   * @param params.keyUri - The key URI identifying the private key to retrieve.\n   *\n   * @returns A Promise resolving to the JWK representation of the private key.\n   *\n   * @throws Error if the key is not found in the key store.\n   */\n  private async getPrivateKey({ keyUri }: {\n    keyUri: KeyIdentifier;\n  }): Promise<Jwk> {\n    // Get the private key from the key store.\n    const privateKey = await this._keyStore.get(keyUri);\n\n    if (!privateKey) {\n      throw new Error(`Key not found: ${keyUri}`);\n    }\n\n    return privateKey;\n  }\n}", "import type { Jwk } from '../jose/jwk.js';\n\ntype ExportedJwk = JsonWebKey & Jwk;\n\ninterface WebcryptoSubtleFacade {\n  decrypt(...args: unknown[]): Promise<ArrayBuffer>;\n  deriveBits(...args: unknown[]): Promise<ArrayBuffer>;\n  deriveKey(...args: unknown[]): Promise<CryptoKey>;\n  digest(...args: unknown[]): Promise<ArrayBuffer>;\n  encrypt(...args: unknown[]): Promise<ArrayBuffer>;\n  exportKey(format: 'jwk', ...args: unknown[]): Promise<ExportedJwk>;\n  exportKey(format: 'raw' | 'spki' | 'pkcs8', ...args: unknown[]): Promise<ArrayBuffer>;\n  generateKey(...args: unknown[]): Promise<CryptoKey>;\n  importKey(...args: unknown[]): Promise<CryptoKey>;\n  sign(...args: unknown[]): Promise<ArrayBuffer>;\n  unwrapKey(...args: unknown[]): Promise<CryptoKey>;\n  verify(...args: unknown[]): Promise<boolean>;\n  wrapKey(...args: unknown[]): Promise<ArrayBuffer>;\n}\n\ntype WebcryptoFacade = Omit<Crypto, 'subtle'> & {\n  subtle: WebcryptoSubtleFacade;\n};\n\nexport function getWebcrypto(): WebcryptoFacade {\n  const webCrypto = globalThis.crypto;\n  if (!webCrypto) {\n    throw new Error('crypto must be defined');\n  }\n\n  return webCrypto as unknown as WebcryptoFacade;\n}\n\nexport function getWebcryptoSubtle(): WebcryptoSubtleFacade {\n  const subtle = getWebcrypto().subtle;\n  if (!subtle) {\n    throw new Error('crypto.subtle must be defined');\n  }\n\n  return subtle;\n}\n", "import type { Cipher } from './types/cipher.js';\nimport type { Jwk } from './jose/jwk.js';\n\nimport { randomBytes as nobleRandomBytes } from '@noble/hashes/utils.js';\n\nimport { getWebcrypto } from './primitives/webcrypto.js';\n\n/**\n * A collection of cryptographic utility methods.\n */\nexport class CryptoUtils {\n\n  /**\n   * Determines the JOSE algorithm identifier of the digital signature algorithm based on the `alg` or\n   * `crv` property of a {@link Jwk | JWK}.\n   *\n   * If the `alg` property is present, its value takes precedence and is returned. Otherwise, the\n   * `crv` property is used to determine the algorithm.\n   *\n   * @memberof CryptoUtils\n   * @see {@link https://www.iana.org/assignments/jose/jose.xhtml#web-signature-encryption-algorithms | JOSE Algorithms}\n   * @see {@link https://datatracker.ietf.org/doc/draft-ietf-jose-fully-specified-algorithms/ | Fully-Specified Algorithms for JOSE and COSE}\n   *\n   * @example\n   * ```ts\n   * const publicKey: Jwk = {\n   *   \"kty\": \"OKP\",\n   *   \"crv\": \"Ed25519\",\n   *   \"x\": \"FEJG7OakZi500EydXxuE8uMc8uaAzEJkmQeG8khXANw\"\n   * }\n   * const algorithm = getJoseSignatureAlgorithmFromPublicKey(publicKey);\n   * console.log(algorithm); // Output: \"EdDSA\"\n   * ```\n   * @param publicKey - A JWK containing the `alg` and/or `crv` properties.\n   * @returns The name of the algorithm associated with the key.\n   * @throws Error if the algorithm cannot be determined from the provided input.\n   */\n  static getJoseSignatureAlgorithmFromPublicKey(publicKey: Jwk): string {\n    const curveToJoseAlgorithm: Record<string, string> = {\n      'Ed25519'   : 'EdDSA',\n      'P-256'     : 'ES256',\n      'P-384'     : 'ES384',\n      'P-521'     : 'ES512',\n      'secp256k1' : 'ES256K',\n    };\n\n    // If the key contains an `alg` property that matches a JOSE registered algorithm identifier,\n    // return its value.\n    if (publicKey.alg && Object.values(curveToJoseAlgorithm).includes(publicKey.alg)) {\n      return publicKey.alg;\n    }\n\n    // If the key contains a `crv` property, return the corresponding algorithm.\n    if (publicKey.crv && Object.keys(curveToJoseAlgorithm).includes(publicKey.crv)) {\n      return curveToJoseAlgorithm[publicKey.crv];\n    }\n\n    throw new Error(\n      `Unable to determine algorithm based on provided input: alg=${publicKey.alg}, crv=${publicKey.crv}. ` +\n      `Supported 'alg' values: ${Object.values(curveToJoseAlgorithm).join(', ')}. ` +\n      `Supported 'crv' values: ${Object.keys(curveToJoseAlgorithm).join(', ')}.`\n    );\n  }\n\n  /**\n   * Generates secure pseudorandom values of the specified length using\n   * `crypto.getRandomValues`, which defers to the operating system.\n   *\n   * @memberof CryptoUtils\n   * @remarks\n   * This function is a wrapper around `randomBytes` from the '@noble/hashes'\n   * package. It's designed to be cryptographically strong, suitable for\n   * generating initialization vectors, nonces, and other random values.\n   *\n   * @see {@link https://www.npmjs.com/package/@noble/hashes | @noble/hashes on NPM} for more\n   * information about the underlying implementation.\n   *\n   * @example\n   * ```ts\n   * const bytes = randomBytes(32); // Generates 32 random bytes\n   * ```\n   *\n   * @param bytesLength - The number of bytes to generate.\n   * @returns A Uint8Array containing the generated random bytes.\n   */\n  static randomBytes(bytesLength: number): Uint8Array {\n    return nobleRandomBytes(bytesLength);\n  }\n\n  /**\n   * Generates a UUID (Universally Unique Identifier) using a\n   * cryptographically strong random number generator following\n   * the version 4 format, as specified in RFC 4122.\n   *\n   * A version 4 UUID is a randomly generated UUID. The 13th character\n   * is set to '4' to denote version 4, and the 17th character is one\n   * of '8', '9', 'A', or 'B' to comply with the variant 1 format of\n   * UUIDs (the high bits are set to '10').\n   *\n   * The UUID is a 36 character string, including hyphens, and looks like this:\n   * xxxxxxxx-xxxx-4xxx-axxx-xxxxxxxxxxxx\n   *\n   * Note that while UUIDs are not guaranteed to be unique, they are\n   * practically unique\" given the large number of possible UUIDs and\n   * the randomness of generation.\n   * @memberof CryptoUtils\n   * @example\n   * ```ts\n   * const uuid = randomUuid();\n   * console.log(uuid); // Outputs a version 4 UUID, e.g., '123e4567-e89b-12d3-a456-426655440000'\n   * ```\n   *\n   * @returns A string containing a randomly generated, 36 character long v4 UUID.\n   */\n  static randomUuid(): string {\n    const uuid = getWebcrypto().randomUUID();\n\n    return uuid;\n  }\n\n\n  /**\n   * Generates a secure random PIN (Personal Identification Number) of a\n   * specified length.\n   *\n   * This function ensures that the generated PIN is cryptographically secure and\n   * uniformly distributed by using rejection sampling. It repeatedly generates\n   * random numbers until it gets one in the desired range [0, max]. This avoids\n   * bias introduced by simply taking the modulus or truncating the number.\n   *\n   * Note: The function can generate PINs of 3 to 10 digits in length.\n   * Any request for a PIN outside this range will result in an error.\n   *\n   * Example usage:\n   *\n   * ```ts\n   * const pin = randomPin({ length: 4 });\n   * console.log(pin); // Outputs a 4-digit PIN, e.g., \"0231\"\n   * ```\n   * @memberof CryptoUtils\n   * @param options - The options object containing the desired length of the generated PIN.\n   * @param options.length - The desired length of the generated PIN. The value should be\n   *                         an integer between 3 and 10 inclusive.\n   *\n   * @returns A string representing the generated PIN. The PIN will be zero-padded\n   *          to match the specified length, if necessary.\n   *\n   * @throws Will throw an error if the requested PIN length is less than 3 or greater than 10.\n   */\n  static randomPin({ length }: { length: number }): string {\n    if (3 > length || length > 10) {\n      throw new Error('randomPin() can securely generate a PIN between 3 to 10 digits.');\n    }\n\n    const pinRange = 10 ** length;\n    const byteLength = Math.ceil(Math.log2(pinRange) / 8);\n    const randomSpace = 2 ** (byteLength * 8);\n    const unbiasedLimit = randomSpace - (randomSpace % pinRange);\n\n    let randomValue: number;\n    do {\n      randomValue = 0;\n      const randomBuffer = CryptoUtils.randomBytes(byteLength);\n      for (const byte of randomBuffer) {\n        randomValue = (randomValue * 256) + byte;\n      }\n    } while (randomValue >= unbiasedLimit);\n\n    const pin = randomValue % pinRange;\n\n    // Pad the PIN with leading zeros to the desired length.\n    return pin.toString().padStart(length, '0');\n  }\n}\n\n/**\n * Type guard that checks whether the given object implements the {@link Cipher} interface.\n */\nexport function isCipher<EncryptInput, DecryptInput>(\n  obj: unknown\n): obj is Cipher<EncryptInput, DecryptInput> {\n  return (\n    obj !== null && typeof obj === 'object'\n    && 'encrypt' in obj && typeof obj.encrypt === 'function'\n    && 'decrypt' in obj && typeof obj.decrypt === 'function'\n  );\n}\n", "// This is an unfortunate replacement for @sindresorhus/is that we need to\n// re-implement for performance purposes. In particular the is.observable()\n// check is expensive, and unnecessary for our purposes. The values returned\n// are compatible with @sindresorhus/is, however.\n\n// Types that reach getObjectType() - excludes types with fast-paths above:\n// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)\nconst objectTypeNames = [\n  'Object', // for Object.create(null) and other non-plain objects\n  'RegExp',\n  'Date',\n  'Error',\n  'Map',\n  'Set',\n  'WeakMap',\n  'WeakSet',\n  'ArrayBuffer',\n  'SharedArrayBuffer',\n  'DataView',\n  'Promise',\n  'URL',\n  'HTMLElement',\n  'Int8Array',\n  'Uint8ClampedArray',\n  'Int16Array',\n  'Uint16Array',\n  'Int32Array',\n  'Uint32Array',\n  'Float32Array',\n  'Float64Array',\n  'BigInt64Array',\n  'BigUint64Array'\n]\n\n/**\n * @param {any} value\n * @returns {string}\n */\nexport function is (value) {\n  if (value === null) {\n    return 'null'\n  }\n  if (value === undefined) {\n    return 'undefined'\n  }\n  if (value === true || value === false) {\n    return 'boolean'\n  }\n  const typeOf = typeof value\n  if (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {\n    return typeOf\n  }\n  /* c8 ignore next 3 */\n  if (typeOf === 'function') {\n    return 'Function'\n  }\n  if (Array.isArray(value)) {\n    return 'Array'\n  }\n  // Also catches Node.js Buffer which extends Uint8Array\n  if (value instanceof Uint8Array) {\n    return 'Uint8Array'\n  }\n  // Fast path for plain objects (most common case after primitives/arrays/bytes)\n  if (value.constructor === Object) {\n    return 'Object'\n  }\n  const objectType = getObjectType(value)\n  if (objectType) {\n    return objectType\n  }\n  /* c8 ignore next */\n  return 'Object'\n}\n\n/**\n * @param {any} value\n * @returns {string|undefined}\n */\nfunction getObjectType (value) {\n  const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)\n  if (objectTypeNames.includes(objectTypeName)) {\n    return objectTypeName\n  }\n  /* c8 ignore next */\n  return undefined\n}\n", "class Type {\n  /**\n   * @param {number} major\n   * @param {string} name\n   * @param {boolean} terminal\n   */\n  constructor (major, name, terminal) {\n    this.major = major\n    this.majorEncoded = major << 5\n    this.name = name\n    this.terminal = terminal\n  }\n\n  /* c8 ignore next 3 */\n  toString () {\n    return `Type[${this.major}].${this.name}`\n  }\n\n  /**\n   * @param {Type} typ\n   * @returns {number}\n   */\n  compare (typ) {\n    /* c8 ignore next 1 */\n    return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0\n  }\n\n  /**\n   * Check equality between two Type instances. Safe to use across different\n   * copies of the Type class (e.g., when bundlers duplicate the module).\n   * (major, name) uniquely identifies a Type; terminal is implied by these.\n   * @param {Type} a\n   * @param {Type} b\n   * @returns {boolean}\n   */\n  static equals (a, b) {\n    return a === b || (a.major === b.major && a.name === b.name)\n  }\n}\n\n// convert to static fields when better supported\nType.uint = new Type(0, 'uint', true)\nType.negint = new Type(1, 'negint', true)\nType.bytes = new Type(2, 'bytes', true)\nType.string = new Type(3, 'string', true)\nType.array = new Type(4, 'array', false)\nType.map = new Type(5, 'map', false)\nType.tag = new Type(6, 'tag', false) // terminal?\nType.float = new Type(7, 'float', true)\nType.false = new Type(7, 'false', true)\nType.true = new Type(7, 'true', true)\nType.null = new Type(7, 'null', true)\nType.undefined = new Type(7, 'undefined', true)\nType.break = new Type(7, 'break', true)\n// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)\n\nclass Token {\n  /**\n   * @param {Type} type\n   * @param {any} [value]\n   * @param {number} [encodedLength]\n   */\n  constructor (type, value, encodedLength) {\n    this.type = type\n    this.value = value\n    this.encodedLength = encodedLength\n    /** @type {Uint8Array|undefined} */\n    this.encodedBytes = undefined\n    /** @type {Uint8Array|undefined} */\n    this.byteValue = undefined\n  }\n\n  /* c8 ignore next 3 */\n  toString () {\n    return `Token[${this.type}].${this.value}`\n  }\n}\n\nexport { Type, Token }\n", "// Use Uint8Array directly in the browser, use Buffer in Node.js but don't\n// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill\n\n// @ts-ignore\nexport const useBuffer = globalThis.process &&\n  // @ts-ignore\n  !globalThis.process.browser &&\n  // @ts-ignore\n  globalThis.Buffer &&\n  // @ts-ignore\n  typeof globalThis.Buffer.isBuffer === 'function'\n\nconst textEncoder = new TextEncoder()\n\n/**\n * @param {Uint8Array} buf\n * @returns {boolean}\n */\nfunction isBuffer (buf) {\n  // @ts-ignore\n  return useBuffer && globalThis.Buffer.isBuffer(buf)\n}\n\n/**\n * @param {Uint8Array|number[]} buf\n * @returns {Uint8Array}\n */\nexport function asU8A (buf) {\n  /* c8 ignore next */\n  if (!(buf instanceof Uint8Array)) {\n    return Uint8Array.from(buf)\n  }\n  return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf\n}\n\n// Threshold for manual UTF-8 encoding vs native methods.\n// Node.js Buffer.from: crossover ~24 chars\n// Browser TextEncoder: crossover ~200 chars\nconst FROM_STRING_THRESHOLD_BUFFER = 24\nconst FROM_STRING_THRESHOLD_TEXTENCODER = 200\n\nexport const fromString = useBuffer\n  ? // eslint-disable-line operator-linebreak\n    /**\n     * @param {string} string\n     */\n    (string) => {\n      return string.length >= FROM_STRING_THRESHOLD_BUFFER\n        ? // eslint-disable-line operator-linebreak\n      // @ts-ignore\n        globalThis.Buffer.from(string)\n        : utf8ToBytes(string)\n    }\n  /* c8 ignore next 7 */\n  : // eslint-disable-line operator-linebreak\n    /**\n     * @param {string} string\n     */\n    (string) => {\n      return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)\n    }\n\n/**\n * Buffer variant not fast enough for what we need\n * @param {number[]} arr\n * @returns {Uint8Array}\n */\nexport const fromArray = (arr) => {\n  return Uint8Array.from(arr)\n}\n\nexport const slice = useBuffer\n  ? // eslint-disable-line operator-linebreak\n    /**\n     * @param {Uint8Array} bytes\n     * @param {number} start\n     * @param {number} end\n     */\n    // Buffer.slice() returns a view, not a copy, so we need special handling\n    (bytes, start, end) => {\n      if (isBuffer(bytes)) {\n        return new Uint8Array(bytes.subarray(start, end))\n      }\n      return bytes.slice(start, end)\n    }\n  /* c8 ignore next 9 */\n  : // eslint-disable-line operator-linebreak\n    /**\n     * @param {Uint8Array} bytes\n     * @param {number} start\n     * @param {number} end\n     */\n    (bytes, start, end) => {\n      return bytes.slice(start, end)\n    }\n\nexport const concat = useBuffer\n  ? // eslint-disable-line operator-linebreak\n    /**\n     * @param {Uint8Array[]} chunks\n     * @param {number} length\n     * @returns {Uint8Array}\n     */\n    (chunks, length) => {\n      // might get a stray plain Array here\n      /* c8 ignore next 1 */\n      chunks = chunks.map((c) => c instanceof Uint8Array\n        ? c\n        // this case is occasionally missed during test runs so becomes coverage-flaky\n        /* c8 ignore next 4 */\n        : // eslint-disable-line operator-linebreak\n        // @ts-ignore\n        globalThis.Buffer.from(c))\n      // @ts-ignore\n      return asU8A(globalThis.Buffer.concat(chunks, length))\n    }\n  /* c8 ignore next 19 */\n  : // eslint-disable-line operator-linebreak\n    /**\n     * @param {Uint8Array[]} chunks\n     * @param {number} length\n     * @returns {Uint8Array}\n     */\n    (chunks, length) => {\n      const out = new Uint8Array(length)\n      let off = 0\n      for (let b of chunks) {\n        if (off + b.length > out.length) {\n          // final chunk that's bigger than we need\n          b = b.subarray(0, out.length - off)\n        }\n        out.set(b, off)\n        off += b.length\n      }\n      return out\n    }\n\nexport const alloc = useBuffer\n  ? // eslint-disable-line operator-linebreak\n    /**\n     * @param {number} size\n     * @returns {Uint8Array}\n     */\n    (size) => {\n      // we always write over the contents we expose so this should be safe\n      // @ts-ignore\n      return globalThis.Buffer.allocUnsafe(size)\n    }\n  /* c8 ignore next 8 */\n  : // eslint-disable-line operator-linebreak\n    /**\n     * @param {number} size\n     * @returns {Uint8Array}\n     */\n    (size) => {\n      return new Uint8Array(size)\n    }\n\nexport const toHex = useBuffer\n  ? // eslint-disable-line operator-linebreak\n    /**\n     * @param {Uint8Array} d\n     * @returns {string}\n     */\n    (d) => {\n      if (typeof d === 'string') {\n        return d\n      }\n      // @ts-ignore\n      return globalThis.Buffer.from(toBytes(d)).toString('hex')\n    }\n  /* c8 ignore next 12 */\n  : // eslint-disable-line operator-linebreak\n    /**\n     * @param {Uint8Array} d\n     * @returns {string}\n     */\n    (d) => {\n      if (typeof d === 'string') {\n        return d\n      }\n      // @ts-ignore not smart enough to figure this out\n      return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')\n    }\n\nexport const fromHex = useBuffer\n  ? // eslint-disable-line operator-linebreak\n  /**\n   * @param {string|Uint8Array} hex\n   * @returns {Uint8Array}\n   */\n    (hex) => {\n      if (hex instanceof Uint8Array) {\n        return hex\n      }\n      // @ts-ignore\n      return globalThis.Buffer.from(hex, 'hex')\n    }\n  /* c8 ignore next 17 */\n  : // eslint-disable-line operator-linebreak\n  /**\n   * @param {string|Uint8Array} hex\n   * @returns {Uint8Array}\n   */\n    (hex) => {\n      if (hex instanceof Uint8Array) {\n        return hex\n      }\n      if (!hex.length) {\n        return new Uint8Array(0)\n      }\n      return new Uint8Array(hex.split('')\n        .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')\n        .filter(Boolean)\n        .map((/** @type {string} */ e) => parseInt(e, 16)))\n    }\n\n/**\n * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj\n * @returns {Uint8Array}\n */\nfunction toBytes (obj) {\n  if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {\n    return obj\n  }\n  if (obj instanceof ArrayBuffer) {\n    return new Uint8Array(obj)\n  }\n  if (ArrayBuffer.isView(obj)) {\n    return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)\n  }\n  /* c8 ignore next */\n  throw new Error('Unknown type, must be binary type')\n}\n\n/**\n * @param {Uint8Array} b1\n * @param {Uint8Array} b2\n * @returns {number}\n */\nexport function compare (b1, b2) {\n  /* c8 ignore next 5 */\n  if (isBuffer(b1) && isBuffer(b2)) {\n    // probably not possible to get here in the current API\n    // @ts-ignore Buffer\n    return b1.compare(b2)\n  }\n  for (let i = 0; i < b1.length; i++) {\n    if (b1[i] === b2[i]) {\n      continue\n    }\n    return b1[i] < b2[i] ? -1 : 1\n  } /* c8 ignore next 3 */\n  return 0\n}\n\n// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143\n// Licensed Apache-2.0.\n\n/**\n * @param {string} str\n * @returns {number[]}\n */\nfunction utf8ToBytes (str) {\n  const out = []\n  let p = 0\n  for (let i = 0; i < str.length; i++) {\n    let c = str.charCodeAt(i)\n    if (c < 128) {\n      out[p++] = c\n    } else if (c < 2048) {\n      out[p++] = (c >> 6) | 192\n      out[p++] = (c & 63) | 128\n    } else if (\n      ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&\n      ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {\n      // Surrogate Pair\n      c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)\n      out[p++] = (c >> 18) | 240\n      out[p++] = ((c >> 12) & 63) | 128\n      out[p++] = ((c >> 6) & 63) | 128\n      out[p++] = (c & 63) | 128\n    } else {\n      if ((c >= 0xD800) && (c <= 0xDFFF)) {\n        c = 0xFFFD // Unpaired Surrogate\n      }\n      out[p++] = (c >> 12) | 224\n      out[p++] = ((c >> 6) & 63) | 128\n      out[p++] = (c & 63) | 128\n    }\n  }\n  return out\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\n/**\n * @param {number[]} codePoints\n * @returns {string}\n */\nexport function decodeCodePointsArray (codePoints) {\n  const len = codePoints.length\n  if (len <= MAX_ARGUMENTS_LENGTH) {\n    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n  }\n  /* c8 ignore next 10 */\n  // Decode in chunks to avoid \"call stack size exceeded\".\n  let res = ''\n  let i = 0\n  while (i < len) {\n    res += String.fromCharCode.apply(\n      String,\n      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n    )\n  }\n  return res\n}\n", "/**\n * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for\n * writing rather than reading.\n * A Bl object accepts set() operations for individual bytes and copyTo() for\n * inserting byte arrays. These write operations don't automatically increment\n * the internal cursor so its \"length\" won't be changed. Instead, increment()\n * must be called to extend its length to cover the inserted data.\n * The toBytes() call will convert all internal memory to a single Uint8Array of\n * the correct length, truncating any data that is stored but hasn't been\n * included by an increment().\n * get() can retrieve a single byte.\n * All operations (except toBytes()) take an \"offset\" argument that will perform\n * the write at the offset _from the current cursor_. For most operations this\n * will be `0` to write at the current cursor position but it can be ahead of\n * the current cursor. Negative offsets probably work but are untested.\n */\n\n// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39\nimport { alloc, concat, slice } from './byte-utils.js'\n\n// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists\n// for perf reasons. Consider better approaches to this or removing it entirely, it is quite\n// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.\n\nconst defaultChunkSize = 256\n\nexport class Bl {\n  /**\n   * @param {number} [chunkSize]\n   */\n  constructor (chunkSize = defaultChunkSize) {\n    this.chunkSize = chunkSize\n    /** @type {number} */\n    this.cursor = 0\n    /** @type {number} */\n    this.maxCursor = -1\n    /** @type {(Uint8Array|number[])[]} */\n    this.chunks = []\n    // keep the first chunk around if we can to save allocations for future encodes\n    /** @type {Uint8Array|number[]|null} */\n    this._initReuseChunk = null\n  }\n\n  reset () {\n    this.cursor = 0\n    this.maxCursor = -1\n    if (this.chunks.length) {\n      this.chunks = []\n    }\n    if (this._initReuseChunk !== null) {\n      this.chunks.push(this._initReuseChunk)\n      this.maxCursor = this._initReuseChunk.length - 1\n    }\n  }\n\n  /**\n   * @param {Uint8Array|number[]} bytes\n   */\n  push (bytes) {\n    let topChunk = this.chunks[this.chunks.length - 1]\n    const newMax = this.cursor + bytes.length\n    if (newMax <= this.maxCursor + 1) {\n      // we have at least one chunk and we can fit these bytes into that chunk\n      const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1\n      // @ts-ignore\n      topChunk.set(bytes, chunkPos)\n    } else {\n      // can't fit it in\n      if (topChunk) {\n        // trip the last chunk to `cursor` if we need to\n        const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1\n        if (chunkPos < topChunk.length) {\n          // @ts-ignore\n          this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)\n          this.maxCursor = this.cursor - 1\n        }\n      }\n      if (bytes.length < 64 && bytes.length < this.chunkSize) {\n        // make a new chunk and copy the new one into it\n        topChunk = alloc(this.chunkSize)\n        this.chunks.push(topChunk)\n        this.maxCursor += topChunk.length\n        if (this._initReuseChunk === null) {\n          this._initReuseChunk = topChunk\n        }\n        // @ts-ignore\n        topChunk.set(bytes, 0)\n      } else {\n        // push the new bytes in as its own chunk\n        this.chunks.push(bytes)\n        this.maxCursor += bytes.length\n      }\n    }\n    this.cursor += bytes.length\n  }\n\n  /**\n   * @param {boolean} [reset]\n   * @returns {Uint8Array}\n   */\n  toBytes (reset = false) {\n    let byts\n    if (this.chunks.length === 1) {\n      const chunk = this.chunks[0]\n      if (reset && this.cursor > chunk.length / 2) {\n        /* c8 ignore next 2 */\n        // @ts-ignore\n        byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)\n        this._initReuseChunk = null\n        this.chunks = []\n      } else {\n        // @ts-ignore\n        byts = slice(chunk, 0, this.cursor)\n      }\n    } else {\n      // @ts-ignore\n      byts = concat(this.chunks, this.cursor)\n    }\n    if (reset) {\n      this.reset()\n    }\n    return byts\n  }\n}\n\n/**\n * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.\n * It provides the same interface as Bl but writes to a fixed destination.\n */\nexport class U8Bl {\n  /**\n   * @param {Uint8Array} dest\n   */\n  constructor (dest) {\n    this.dest = dest\n    /** @type {number} */\n    this.cursor = 0\n    // chunks is for interface compatibility with Bl - encode.js checks chunks.length\n    // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].\n    /** @type {Uint8Array[]} */\n    this.chunks = [dest]\n  }\n\n  reset () {\n    this.cursor = 0\n  }\n\n  /**\n   * @param {Uint8Array|number[]} bytes\n   */\n  push (bytes) {\n    if (this.cursor + bytes.length > this.dest.length) {\n      throw new Error('write out of bounds, destination buffer is too small')\n    }\n    this.dest.set(bytes, this.cursor)\n    this.cursor += bytes.length\n  }\n\n  /**\n   * @param {boolean} [reset]\n   * @returns {Uint8Array}\n   */\n  toBytes (reset = false) {\n    const byts = this.dest.subarray(0, this.cursor)\n    if (reset) {\n      this.reset()\n    }\n    return byts\n  }\n}\n", "const decodeErrPrefix = 'CBOR decode error:'\nconst encodeErrPrefix = 'CBOR encode error:'\n\nconst uintMinorPrefixBytes = []\nuintMinorPrefixBytes[23] = 1\nuintMinorPrefixBytes[24] = 2\nuintMinorPrefixBytes[25] = 3\nuintMinorPrefixBytes[26] = 5\nuintMinorPrefixBytes[27] = 9\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} need\n */\nfunction assertEnoughData (data, pos, need) {\n  if (data.length - pos < need) {\n    throw new Error(`${decodeErrPrefix} not enough data for type`)\n  }\n}\n\nexport {\n  decodeErrPrefix,\n  encodeErrPrefix,\n  uintMinorPrefixBytes,\n  assertEnoughData\n}\n", "/* globals BigInt */\n\nimport { Token, Type } from './token.js'\nimport { decodeErrPrefix, assertEnoughData } from './common.js'\n\nexport const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]\n\n/**\n * @typedef {import('../interface').ByteWriter} ByteWriter\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint8 (data, offset, options) {\n  assertEnoughData(data, offset, 1)\n  const value = data[offset]\n  if (options.strict === true && value < uintBoundaries[0]) {\n    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n  }\n  return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint16 (data, offset, options) {\n  assertEnoughData(data, offset, 2)\n  const value = (data[offset] << 8) | data[offset + 1]\n  if (options.strict === true && value < uintBoundaries[1]) {\n    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n  }\n  return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint32 (data, offset, options) {\n  assertEnoughData(data, offset, 4)\n  const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]\n  if (options.strict === true && value < uintBoundaries[2]) {\n    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n  }\n  return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number|bigint}\n */\nexport function readUint64 (data, offset, options) {\n  // assume BigInt, convert back to Number if within safe range\n  assertEnoughData(data, offset, 8)\n  const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]\n  const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]\n  const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)\n  if (options.strict === true && value < uintBoundaries[3]) {\n    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n  }\n  if (value <= Number.MAX_SAFE_INTEGER) {\n    return Number(value)\n  }\n  if (options.allowBigInt === true) {\n    return value\n  }\n  throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)\n}\n\n/* not required thanks to quick[] list\nconst oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))\nexport function decodeUintCompact (data, pos, minor, options) {\n  return oneByteTokens[minor]\n}\n*/\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint8 (data, pos, _minor, options) {\n  return new Token(Type.uint, readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint16 (data, pos, _minor, options) {\n  return new Token(Type.uint, readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint32 (data, pos, _minor, options) {\n  return new Token(Type.uint, readUint32(data, pos + 1, options), 5)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint64 (data, pos, _minor, options) {\n  return new Token(Type.uint, readUint64(data, pos + 1, options), 9)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeUint (writer, token) {\n  return encodeUintValue(writer, 0, token.value)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {number} major\n * @param {number|bigint} uint\n */\nexport function encodeUintValue (writer, major, uint) {\n  if (uint < uintBoundaries[0]) {\n    const nuint = Number(uint)\n    // pack into one byte, minor=0, additional=value\n    writer.push([major | nuint])\n  } else if (uint < uintBoundaries[1]) {\n    const nuint = Number(uint)\n    // pack into two byte, minor=0, additional=24\n    writer.push([major | 24, nuint])\n  } else if (uint < uintBoundaries[2]) {\n    const nuint = Number(uint)\n    // pack into three byte, minor=0, additional=25\n    writer.push([major | 25, nuint >>> 8, nuint & 0xff])\n  } else if (uint < uintBoundaries[3]) {\n    const nuint = Number(uint)\n    // pack into five byte, minor=0, additional=26\n    writer.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])\n  } else {\n    const buint = BigInt(uint)\n    if (buint < uintBoundaries[4]) {\n      // pack into nine byte, minor=0, additional=27\n      const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]\n      // simulate bitwise above 32 bits\n      let lo = Number(buint & BigInt(0xffffffff))\n      let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))\n      set[8] = lo & 0xff\n      lo = lo >> 8\n      set[7] = lo & 0xff\n      lo = lo >> 8\n      set[6] = lo & 0xff\n      lo = lo >> 8\n      set[5] = lo & 0xff\n      set[4] = hi & 0xff\n      hi = hi >> 8\n      set[3] = hi & 0xff\n      hi = hi >> 8\n      set[2] = hi & 0xff\n      hi = hi >> 8\n      set[1] = hi & 0xff\n      writer.push(set)\n    } else {\n      throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)\n    }\n  }\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeUint.encodedSize = function encodedSize (token) {\n  return encodeUintValue.encodedSize(token.value)\n}\n\n/**\n * @param {number} uint\n * @returns {number}\n */\nencodeUintValue.encodedSize = function encodedSize (uint) {\n  if (uint < uintBoundaries[0]) {\n    return 1\n  }\n  if (uint < uintBoundaries[1]) {\n    return 2\n  }\n  if (uint < uintBoundaries[2]) {\n    return 3\n  }\n  if (uint < uintBoundaries[3]) {\n    return 5\n  }\n  return 9\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeUint.compareTokens = function compareTokens (tok1, tok2) {\n  return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : /* c8 ignore next */ 0\n}\n", "/* eslint-env es2020 */\n\nimport { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('../interface').ByteWriter} ByteWriter\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint8 (data, pos, _minor, options) {\n  return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint16 (data, pos, _minor, options) {\n  return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint32 (data, pos, _minor, options) {\n  return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)\n}\n\nconst neg1b = BigInt(-1)\nconst pos1b = BigInt(1)\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint64 (data, pos, _minor, options) {\n  const int = uint.readUint64(data, pos + 1, options)\n  if (typeof int !== 'bigint') {\n    const value = -1 - int\n    if (value >= Number.MIN_SAFE_INTEGER) {\n      return new Token(Type.negint, value, 9)\n    }\n  }\n  if (options.allowBigInt !== true) {\n    throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)\n  }\n  return new Token(Type.negint, neg1b - BigInt(int), 9)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeNegint (writer, token) {\n  const negint = token.value\n  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))\n  uint.encodeUintValue(writer, token.type.majorEncoded, unsigned)\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeNegint.encodedSize = function encodedSize (token) {\n  const negint = token.value\n  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))\n  /* c8 ignore next 4 */\n  // handled by quickEncode, we shouldn't get here but it's included for completeness\n  if (unsigned < uint.uintBoundaries[0]) {\n    return 1\n  }\n  if (unsigned < uint.uintBoundaries[1]) {\n    return 2\n  }\n  if (unsigned < uint.uintBoundaries[2]) {\n    return 3\n  }\n  if (unsigned < uint.uintBoundaries[3]) {\n    return 5\n  }\n  return 9\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeNegint.compareTokens = function compareTokens (tok1, tok2) {\n  // opposite of the uint comparison since we store the uint version in bytes\n  return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : /* c8 ignore next */ 0\n}\n", "import { Token, Type } from './token.js'\nimport { assertEnoughData, decodeErrPrefix } from './common.js'\nimport * as uint from './0uint.js'\nimport { compare, fromString } from './byte-utils.js'\n\n/**\n * @typedef {import('../interface').ByteWriter} ByteWriter\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (data, pos, prefix, length) {\n  assertEnoughData(data, pos, prefix + length)\n  const buf = data.slice(pos + prefix, pos + prefix + length)\n  return new Token(Type.bytes, buf, prefix + length)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeBytesCompact (data, pos, minor, _options) {\n  return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes8 (data, pos, _minor, options) {\n  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes16 (data, pos, _minor, options) {\n  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes32 (data, pos, _minor, options) {\n  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes64 (data, pos, _minor, options) {\n  const l = uint.readUint64(data, pos + 1, options)\n  if (typeof l === 'bigint') {\n    throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)\n  }\n  return toToken(data, pos, 9, l)\n}\n\n/**\n * `encodedBytes` allows for caching when we do a byte version of a string\n * for key sorting purposes\n * @param {Token} token\n * @returns {Uint8Array}\n */\nfunction tokenBytes (token) {\n  if (token.encodedBytes === undefined) {\n    token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value\n  }\n  // @ts-ignore c'mon\n  return token.encodedBytes\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeBytes (writer, token) {\n  const bytes = tokenBytes(token)\n  uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)\n  writer.push(bytes)\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeBytes.encodedSize = function encodedSize (token) {\n  const bytes = tokenBytes(token)\n  return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeBytes.compareTokens = function compareTokens (tok1, tok2) {\n  return compareBytes(tokenBytes(tok1), tokenBytes(tok2))\n}\n\n/**\n * @param {Uint8Array} b1\n * @param {Uint8Array} b2\n * @returns {number}\n */\nexport function compareBytes (b1, b2) {\n  return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)\n}\n", "import { Token, Type } from './token.js'\nimport { assertEnoughData, decodeErrPrefix } from './common.js'\nimport * as uint from './0uint.js'\nimport { encodeBytes } from './2bytes.js'\n\nconst textDecoder = new TextDecoder()\n\n// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for\n// map keys) are faster to decode with a simple loop than TextDecoder overhead.\nconst ASCII_THRESHOLD = 32\n\n/**\n * @typedef {import('../interface').ByteWriter} ByteWriter\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),\n * a simple loop is faster than TextDecoder.\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n * @returns {string}\n */\nfunction toStr (bytes, start, end) {\n  const len = end - start\n  if (len < ASCII_THRESHOLD) {\n    let str = ''\n    for (let i = start; i < end; i++) {\n      const c = bytes[i]\n      if (c & 0x80) { // non-ASCII, fall back to TextDecoder\n        return textDecoder.decode(bytes.subarray(start, end))\n      }\n      str += String.fromCharCode(c)\n    }\n    return str\n  }\n  return textDecoder.decode(bytes.subarray(start, end))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} prefix\n * @param {number} length\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nfunction toToken (data, pos, prefix, length, options) {\n  const totLength = prefix + length\n  assertEnoughData(data, pos, totLength)\n  const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength)\n  if (options.retainStringBytes === true) {\n    tok.byteValue = data.slice(pos + prefix, pos + totLength)\n  }\n  return tok\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeStringCompact (data, pos, minor, options) {\n  return toToken(data, pos, 1, minor, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString8 (data, pos, _minor, options) {\n  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString16 (data, pos, _minor, options) {\n  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString32 (data, pos, _minor, options) {\n  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString64 (data, pos, _minor, options) {\n  const l = uint.readUint64(data, pos + 1, options)\n  if (typeof l === 'bigint') {\n    throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)\n  }\n  return toToken(data, pos, 9, l, options)\n}\n\nexport const encodeString = encodeBytes\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('../interface').ByteWriter} ByteWriter\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (_data, _pos, prefix, length) {\n  return new Token(Type.array, length, prefix)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeArrayCompact (data, pos, minor, _options) {\n  return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray8 (data, pos, _minor, options) {\n  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray16 (data, pos, _minor, options) {\n  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray32 (data, pos, _minor, options) {\n  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray64 (data, pos, _minor, options) {\n  const l = uint.readUint64(data, pos + 1, options)\n  if (typeof l === 'bigint') {\n    throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)\n  }\n  return toToken(data, pos, 9, l)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArrayIndefinite (data, pos, _minor, options) {\n  if (options.allowIndefinite === false) {\n    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n  }\n  return toToken(data, pos, 1, Infinity)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeArray (writer, token) {\n  uint.encodeUintValue(writer, Type.array.majorEncoded, token.value)\n}\n\n// using an array as a map key, are you sure about this? we can only sort\n// by map length here, it's up to the encoder to decide to look deeper\nencodeArray.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeArray.encodedSize = function encodedSize (token) {\n  return uint.encodeUintValue.encodedSize(token.value)\n}\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('../interface').ByteWriter} ByteWriter\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (_data, _pos, prefix, length) {\n  return new Token(Type.map, length, prefix)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeMapCompact (data, pos, minor, _options) {\n  return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap8 (data, pos, _minor, options) {\n  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap16 (data, pos, _minor, options) {\n  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap32 (data, pos, _minor, options) {\n  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap64 (data, pos, _minor, options) {\n  const l = uint.readUint64(data, pos + 1, options)\n  if (typeof l === 'bigint') {\n    throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)\n  }\n  return toToken(data, pos, 9, l)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMapIndefinite (data, pos, _minor, options) {\n  if (options.allowIndefinite === false) {\n    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n  }\n  return toToken(data, pos, 1, Infinity)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeMap (writer, token) {\n  uint.encodeUintValue(writer, Type.map.majorEncoded, token.value)\n}\n\n// using a map as a map key, are you sure about this? we can only sort\n// by map length here, it's up to the encoder to decide to look deeper\nencodeMap.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeMap.encodedSize = function encodedSize (token) {\n  return uint.encodeUintValue.encodedSize(token.value)\n}\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\n\n/**\n * @typedef {import('../interface').ByteWriter} ByteWriter\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeTagCompact (_data, _pos, minor, _options) {\n  return new Token(Type.tag, minor, 1)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag8 (data, pos, _minor, options) {\n  return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag16 (data, pos, _minor, options) {\n  return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag32 (data, pos, _minor, options) {\n  return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag64 (data, pos, _minor, options) {\n  return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeTag (writer, token) {\n  uint.encodeUintValue(writer, Type.tag.majorEncoded, token.value)\n}\n\nencodeTag.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeTag.encodedSize = function encodedSize (token) {\n  return uint.encodeUintValue.encodedSize(token.value)\n}\n", "// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer\n// where possible\n\nimport { Token, Type } from './token.js'\nimport { decodeErrPrefix } from './common.js'\nimport { encodeUint } from './0uint.js'\n\n/**\n * @typedef {import('../interface').ByteWriter} ByteWriter\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n * @typedef {import('../interface').EncodeOptions} EncodeOptions\n */\n\nexport const MINOR_FALSE = 20\nexport const MINOR_TRUE = 21\nexport const MINOR_NULL = 22\nexport const MINOR_UNDEFINED = 23\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUndefined (_data, _pos, _minor, options) {\n  if (options.allowUndefined === false) {\n    throw new Error(`${decodeErrPrefix} undefined values are not supported`)\n  } else if (options.coerceUndefinedToNull === true) {\n    return new Token(Type.null, null, 1)\n  }\n  return new Token(Type.undefined, undefined, 1)\n}\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBreak (_data, _pos, _minor, options) {\n  if (options.allowIndefinite === false) {\n    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n  }\n  return new Token(Type.break, undefined, 1)\n}\n\n/**\n * @param {number} value\n * @param {number} bytes\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nfunction createToken (value, bytes, options) {\n  if (options) {\n    if (options.allowNaN === false && Number.isNaN(value)) {\n      throw new Error(`${decodeErrPrefix} NaN values are not supported`)\n    }\n    if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {\n      throw new Error(`${decodeErrPrefix} Infinity values are not supported`)\n    }\n  }\n  return new Token(Type.float, value, bytes)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat16 (data, pos, _minor, options) {\n  return createToken(readFloat16(data, pos + 1), 3, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat32 (data, pos, _minor, options) {\n  return createToken(readFloat32(data, pos + 1), 5, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat64 (data, pos, _minor, options) {\n  return createToken(readFloat64(data, pos + 1), 9, options)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n * @param {EncodeOptions} options\n */\nexport function encodeFloat (writer, token, options) {\n  const float = token.value\n\n  if (float === false) {\n    writer.push([Type.float.majorEncoded | MINOR_FALSE])\n  } else if (float === true) {\n    writer.push([Type.float.majorEncoded | MINOR_TRUE])\n  } else if (float === null) {\n    writer.push([Type.float.majorEncoded | MINOR_NULL])\n  } else if (float === undefined) {\n    writer.push([Type.float.majorEncoded | MINOR_UNDEFINED])\n  } else {\n    let decoded\n    let success = false\n    if (!options || options.float64 !== true) {\n      encodeFloat16(float)\n      decoded = readFloat16(ui8a, 1)\n      if (float === decoded || Number.isNaN(float)) {\n        ui8a[0] = 0xf9\n        writer.push(ui8a.slice(0, 3))\n        success = true\n      } else {\n        encodeFloat32(float)\n        decoded = readFloat32(ui8a, 1)\n        if (float === decoded) {\n          ui8a[0] = 0xfa\n          writer.push(ui8a.slice(0, 5))\n          success = true\n        }\n      }\n    }\n    if (!success) {\n      encodeFloat64(float)\n      decoded = readFloat64(ui8a, 1)\n      ui8a[0] = 0xfb\n      writer.push(ui8a.slice(0, 9))\n    }\n  }\n}\n\n/**\n * @param {Token} token\n * @param {EncodeOptions} options\n * @returns {number}\n */\nencodeFloat.encodedSize = function encodedSize (token, options) {\n  const float = token.value\n\n  if (float === false || float === true || float === null || float === undefined) {\n    return 1\n  }\n\n  if (!options || options.float64 !== true) {\n    encodeFloat16(float)\n    let decoded = readFloat16(ui8a, 1)\n    if (float === decoded || Number.isNaN(float)) {\n      return 3\n    }\n    encodeFloat32(float)\n    decoded = readFloat32(ui8a, 1)\n    if (float === decoded) {\n      return 5\n    }\n  }\n  return 9\n}\n\nconst buffer = new ArrayBuffer(9)\nconst dataView = new DataView(buffer, 1)\nconst ui8a = new Uint8Array(buffer, 0)\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat16 (inp) {\n  if (inp === Infinity) {\n    dataView.setUint16(0, 0x7c00, false)\n  } else if (inp === -Infinity) {\n    dataView.setUint16(0, 0xfc00, false)\n  } else if (Number.isNaN(inp)) {\n    dataView.setUint16(0, 0x7e00, false)\n  } else {\n    dataView.setFloat32(0, inp)\n    const valu32 = dataView.getUint32(0)\n    const exponent = (valu32 & 0x7f800000) >> 23\n    const mantissa = valu32 & 0x7fffff\n\n    /* c8 ignore next 6 */\n    if (exponent === 0xff) {\n      // too big, Infinity, but this should be hard (impossible?) to trigger\n      dataView.setUint16(0, 0x7c00, false)\n    } else if (exponent === 0x00) {\n      // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int\n      dataView.setUint16(0, ((inp & 0x80000000) >> 16) | (mantissa >> 13), false)\n    } else { // standard numbers\n      // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127\n      const logicalExponent = exponent - 127\n      // Now we know that 2^exponent <= 0 logically\n      /* c8 ignore next 6 */\n      if (logicalExponent < -24) {\n        /* No unambiguous representation exists, this float is not a half float\n          and is too small to be represented using a half, round off to zero.\n          Consistent with the reference implementation. */\n        // should be difficult (impossible?) to get here in JS\n        dataView.setUint16(0, 0)\n      } else if (logicalExponent < -14) {\n        /* Offset the remaining decimal places by shifting the significand, the\n          value is lost. This is an implementation decision that works around the\n          absence of standard half-float in the language. */\n        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)\n      } else {\n        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)\n      }\n    }\n  }\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat16 (ui8a, pos) {\n  if (ui8a.length - pos < 2) {\n    throw new Error(`${decodeErrPrefix} not enough data for float16`)\n  }\n\n  const half = (ui8a[pos] << 8) + ui8a[pos + 1]\n  if (half === 0x7c00) {\n    return Infinity\n  }\n  if (half === 0xfc00) {\n    return -Infinity\n  }\n  if (half === 0x7e00) {\n    return NaN\n  }\n  const exp = (half >> 10) & 0x1f\n  const mant = half & 0x3ff\n  let val\n  if (exp === 0) {\n    val = mant * (2 ** -24)\n  } else if (exp !== 31) {\n    val = (mant + 1024) * (2 ** (exp - 25))\n  /* c8 ignore next 4 */\n  } else {\n    // may not be possible to get here\n    val = mant === 0 ? Infinity : NaN\n  }\n  return (half & 0x8000) ? -val : val\n}\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat32 (inp) {\n  dataView.setFloat32(0, inp, false)\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat32 (ui8a, pos) {\n  if (ui8a.length - pos < 4) {\n    throw new Error(`${decodeErrPrefix} not enough data for float32`)\n  }\n  const offset = (ui8a.byteOffset || 0) + pos\n  return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)\n}\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat64 (inp) {\n  dataView.setFloat64(0, inp, false)\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat64 (ui8a, pos) {\n  if (ui8a.length - pos < 8) {\n    throw new Error(`${decodeErrPrefix} not enough data for float64`)\n  }\n  const offset = (ui8a.byteOffset || 0) + pos\n  return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)\n}\n\n/**\n * @param {Token} _tok1\n * @param {Token} _tok2\n * @returns {number}\n */\nencodeFloat.compareTokens = encodeUint.compareTokens\n/*\nencodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {\n  return _tok1\n  throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)\n}\n*/\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport * as negint from './1negint.js'\nimport * as bytes from './2bytes.js'\nimport * as string from './3string.js'\nimport * as array from './4array.js'\nimport * as map from './5map.js'\nimport * as tag from './6tag.js'\nimport * as float from './7float.js'\nimport { decodeErrPrefix } from './common.js'\nimport { fromArray } from './byte-utils.js'\n\n/**\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n */\nfunction invalidMinor (data, pos, minor) {\n  throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)\n}\n\n/**\n * @param {string} msg\n * @returns {()=>any}\n */\nfunction errorer (msg) {\n  return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }\n}\n\n/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */\nexport const jump = []\n\n// unsigned integer, 0x00..0x17 (0..23)\nfor (let i = 0; i <= 0x17; i++) {\n  jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]\n}\njump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows\njump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows\njump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows\njump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows\njump[0x1c] = invalidMinor\njump[0x1d] = invalidMinor\njump[0x1e] = invalidMinor\njump[0x1f] = invalidMinor\n// negative integer, -1-0x00..-1-0x17 (-1..-24)\nfor (let i = 0x20; i <= 0x37; i++) {\n  jump[i] = invalidMinor // negintDecode, handled by quick[]\n}\njump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows\njump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows\njump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows\njump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows\njump[0x3c] = invalidMinor\njump[0x3d] = invalidMinor\njump[0x3e] = invalidMinor\njump[0x3f] = invalidMinor\n// byte string, 0x00..0x17 bytes follow\nfor (let i = 0x40; i <= 0x57; i++) {\n  jump[i] = bytes.decodeBytesCompact\n}\njump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow\njump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow\njump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow\njump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow\njump[0x5c] = invalidMinor\njump[0x5d] = invalidMinor\njump[0x5e] = invalidMinor\njump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by \"break\"\n// UTF-8 string 0x00..0x17 bytes follow\nfor (let i = 0x60; i <= 0x77; i++) {\n  jump[i] = string.decodeStringCompact\n}\njump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow\njump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow\njump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow\njump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow\njump[0x7c] = invalidMinor\njump[0x7d] = invalidMinor\njump[0x7e] = invalidMinor\njump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by \"break\"\n// array, 0x00..0x17 data items follow\nfor (let i = 0x80; i <= 0x97; i++) {\n  jump[i] = array.decodeArrayCompact\n}\njump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow\njump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow\njump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow\njump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow\njump[0x9c] = invalidMinor\njump[0x9d] = invalidMinor\njump[0x9e] = invalidMinor\njump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by \"break\"\n// map, 0x00..0x17 pairs of data items follow\nfor (let i = 0xa0; i <= 0xb7; i++) {\n  jump[i] = map.decodeMapCompact\n}\njump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow\njump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow\njump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow\njump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow\njump[0xbc] = invalidMinor\njump[0xbd] = invalidMinor\njump[0xbe] = invalidMinor\njump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by \"break\"\n// tags\nfor (let i = 0xc0; i <= 0xd7; i++) {\n  jump[i] = tag.decodeTagCompact\n}\njump[0xd8] = tag.decodeTag8\njump[0xd9] = tag.decodeTag16\njump[0xda] = tag.decodeTag32\njump[0xdb] = tag.decodeTag64\njump[0xdc] = invalidMinor\njump[0xdd] = invalidMinor\njump[0xde] = invalidMinor\njump[0xdf] = invalidMinor\n// 0xe0..0xf3 simple values, unsupported\nfor (let i = 0xe0; i <= 0xf3; i++) {\n  jump[i] = errorer('simple values are not supported')\n}\njump[0xf4] = invalidMinor // false, handled by quick[]\njump[0xf5] = invalidMinor // true, handled by quick[]\njump[0xf6] = invalidMinor // null, handled by quick[]\njump[0xf7] = float.decodeUndefined // undefined\njump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported\njump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)\njump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)\njump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)\njump[0xfc] = invalidMinor\njump[0xfd] = invalidMinor\njump[0xfe] = invalidMinor\njump[0xff] = float.decodeBreak // \"break\" stop code\n\n/** @type {Token[]} */\nexport const quick = []\n// ints <24\nfor (let i = 0; i < 24; i++) {\n  quick[i] = new Token(Type.uint, i, 1)\n}\n// negints >= -24\nfor (let i = -1; i >= -24; i--) {\n  quick[31 - i] = new Token(Type.negint, i, 1)\n}\n// empty bytes\nquick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)\n// empty string\nquick[0x60] = new Token(Type.string, '', 1)\n// empty list\nquick[0x80] = new Token(Type.array, 0, 1)\n// empty map\nquick[0xa0] = new Token(Type.map, 0, 1)\n// false\nquick[0xf4] = new Token(Type.false, false, 1)\n// true\nquick[0xf5] = new Token(Type.true, true, 1)\n// null\nquick[0xf6] = new Token(Type.null, null, 1)\n\n/**\n * @param {Token} token\n * @returns {Uint8Array|undefined}\n */\nexport function quickEncodeToken (token) {\n  switch (token.type) {\n    case Type.false:\n      return fromArray([0xf4])\n    case Type.true:\n      return fromArray([0xf5])\n    case Type.null:\n      return fromArray([0xf6])\n    case Type.bytes:\n      if (!token.value.length) {\n        return fromArray([0x40])\n      }\n      return\n    case Type.string:\n      if (token.value === '') {\n        return fromArray([0x60])\n      }\n      return\n    case Type.array:\n      if (token.value === 0) {\n        return fromArray([0x80])\n      }\n      /* c8 ignore next 2 */\n      // shouldn't be possible if this were called when there was only one token\n      return\n    case Type.map:\n      if (token.value === 0) {\n        return fromArray([0xa0])\n      }\n      /* c8 ignore next 2 */\n      // shouldn't be possible if this were called when there was only one token\n      return\n    case Type.uint:\n      if (token.value < 24) {\n        return fromArray([Number(token.value)])\n      }\n      return\n    case Type.negint:\n      if (token.value >= -24) {\n        return fromArray([31 - Number(token.value)])\n      }\n  }\n}\n", "import { is } from './is.js'\nimport { Token, Type } from './token.js'\nimport { Bl, U8Bl } from './bl.js'\nimport { encodeErrPrefix } from './common.js'\nimport { quickEncodeToken } from './jump.js'\nimport { asU8A, compare, fromString } from './byte-utils.js'\n\nimport { encodeUint, encodeUintValue } from './0uint.js'\nimport { encodeNegint } from './1negint.js'\nimport { encodeBytes } from './2bytes.js'\nimport { encodeString } from './3string.js'\nimport { encodeArray } from './4array.js'\nimport { encodeMap } from './5map.js'\nimport { encodeTag } from './6tag.js'\nimport { encodeFloat, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'\n\n/**\n * @typedef {import('../interface').EncodeOptions} EncodeOptions\n * @typedef {import('../interface').OptionalTypeEncoder} OptionalTypeEncoder\n * @typedef {import('../interface').Reference} Reference\n * @typedef {import('../interface').StrictTypeEncoder} StrictTypeEncoder\n * @typedef {import('../interface').TokenTypeEncoder} TokenTypeEncoder\n * @typedef {import('../interface').TokenOrNestedTokens} TokenOrNestedTokens\n * @typedef {import('../interface').ByteWriter} ByteWriter\n */\n\n/** @type {EncodeOptions} */\nconst defaultEncodeOptions = {\n  float64: false,\n  mapSorter,\n  quickEncodeToken\n}\n\n/** @type {EncodeOptions} */\nexport const rfc8949EncodeOptions = Object.freeze({\n  float64: true,\n  mapSorter: rfc8949MapSorter,\n  quickEncodeToken\n})\n\n/** @returns {TokenTypeEncoder[]} */\nexport function makeCborEncoders () {\n  const encoders = []\n  encoders[Type.uint.major] = encodeUint\n  encoders[Type.negint.major] = encodeNegint\n  encoders[Type.bytes.major] = encodeBytes\n  encoders[Type.string.major] = encodeString\n  encoders[Type.array.major] = encodeArray\n  encoders[Type.map.major] = encodeMap\n  encoders[Type.tag.major] = encodeTag\n  encoders[Type.float.major] = encodeFloat\n  return encoders\n}\n\nconst cborEncoders = makeCborEncoders()\n\nconst defaultWriter = new Bl()\n\n/** @implements {Reference} */\nclass Ref {\n  /**\n   * @param {object|any[]} obj\n   * @param {Reference|undefined} parent\n   */\n  constructor (obj, parent) {\n    this.obj = obj\n    this.parent = parent\n  }\n\n  /**\n   * @param {object|any[]} obj\n   * @returns {boolean}\n   */\n  includes (obj) {\n    /** @type {Reference|undefined} */\n    let p = this\n    do {\n      if (p.obj === obj) {\n        return true\n      }\n    } while (p = p.parent) // eslint-disable-line\n    return false\n  }\n\n  /**\n   * @param {Reference|undefined} stack\n   * @param {object|any[]} obj\n   * @returns {Reference}\n   */\n  static createCheck (stack, obj) {\n    if (stack && stack.includes(obj)) {\n      throw new Error(`${encodeErrPrefix} object contains circular references`)\n    }\n    return new Ref(obj, stack)\n  }\n}\n\nconst simpleTokens = {\n  null: new Token(Type.null, null),\n  undefined: new Token(Type.undefined, undefined),\n  true: new Token(Type.true, true),\n  false: new Token(Type.false, false),\n  emptyArray: new Token(Type.array, 0),\n  emptyMap: new Token(Type.map, 0)\n}\n\n/** @type {{[typeName: string]: StrictTypeEncoder}} */\nconst typeEncoders = {\n  /**\n   * @param {any} obj\n   * @param {string} _typ\n   * @param {EncodeOptions} _options\n   * @param {Reference} [_refStack]\n   * @returns {TokenOrNestedTokens}\n   */\n  number (obj, _typ, _options, _refStack) {\n    if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {\n      return new Token(Type.float, obj)\n    } else if (obj >= 0) {\n      return new Token(Type.uint, obj)\n    } else {\n      return new Token(Type.negint, obj)\n    }\n  },\n\n  /**\n   * @param {any} obj\n   * @param {string} _typ\n   * @param {EncodeOptions} _options\n   * @param {Reference} [_refStack]\n   * @returns {TokenOrNestedTokens}\n   */\n  bigint (obj, _typ, _options, _refStack) {\n    if (obj >= BigInt(0)) {\n      return new Token(Type.uint, obj)\n    } else {\n      return new Token(Type.negint, obj)\n    }\n  },\n\n  /**\n   * @param {any} obj\n   * @param {string} _typ\n   * @param {EncodeOptions} _options\n   * @param {Reference} [_refStack]\n   * @returns {TokenOrNestedTokens}\n   */\n  Uint8Array (obj, _typ, _options, _refStack) {\n    return new Token(Type.bytes, obj)\n  },\n\n  /**\n   * @param {any} obj\n   * @param {string} _typ\n   * @param {EncodeOptions} _options\n   * @param {Reference} [_refStack]\n   * @returns {TokenOrNestedTokens}\n   */\n  string (obj, _typ, _options, _refStack) {\n    return new Token(Type.string, obj)\n  },\n\n  /**\n   * @param {any} obj\n   * @param {string} _typ\n   * @param {EncodeOptions} _options\n   * @param {Reference} [_refStack]\n   * @returns {TokenOrNestedTokens}\n   */\n  boolean (obj, _typ, _options, _refStack) {\n    return obj ? simpleTokens.true : simpleTokens.false\n  },\n\n  /**\n   * @param {any} _obj\n   * @param {string} _typ\n   * @param {EncodeOptions} _options\n   * @param {Reference} [_refStack]\n   * @returns {TokenOrNestedTokens}\n   */\n  null (_obj, _typ, _options, _refStack) {\n    return simpleTokens.null\n  },\n\n  /**\n   * @param {any} _obj\n   * @param {string} _typ\n   * @param {EncodeOptions} _options\n   * @param {Reference} [_refStack]\n   * @returns {TokenOrNestedTokens}\n   */\n  undefined (_obj, _typ, _options, _refStack) {\n    return simpleTokens.undefined\n  },\n\n  /**\n   * @param {any} obj\n   * @param {string} _typ\n   * @param {EncodeOptions} _options\n   * @param {Reference} [_refStack]\n   * @returns {TokenOrNestedTokens}\n   */\n  ArrayBuffer (obj, _typ, _options, _refStack) {\n    return new Token(Type.bytes, new Uint8Array(obj))\n  },\n\n  /**\n   * @param {any} obj\n   * @param {string} _typ\n   * @param {EncodeOptions} _options\n   * @param {Reference} [_refStack]\n   * @returns {TokenOrNestedTokens}\n   */\n  DataView (obj, _typ, _options, _refStack) {\n    return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))\n  },\n\n  /**\n   * @param {any} obj\n   * @param {string} _typ\n   * @param {EncodeOptions} options\n   * @param {Reference} [refStack]\n   * @returns {TokenOrNestedTokens}\n   */\n  Array (obj, _typ, options, refStack) {\n    if (!obj.length) {\n      if (options.addBreakTokens === true) {\n        return [simpleTokens.emptyArray, new Token(Type.break)]\n      }\n      return simpleTokens.emptyArray\n    }\n    refStack = Ref.createCheck(refStack, obj)\n    const entries = []\n    let i = 0\n    for (const e of obj) {\n      entries[i++] = objectToTokens(e, options, refStack)\n    }\n    if (options.addBreakTokens) {\n      return [new Token(Type.array, obj.length), entries, new Token(Type.break)]\n    }\n    return [new Token(Type.array, obj.length), entries]\n  },\n\n  /**\n   * @param {any} obj\n   * @param {string} typ\n   * @param {EncodeOptions} options\n   * @param {Reference} [refStack]\n   * @returns {TokenOrNestedTokens}\n   */\n  Object (obj, typ, options, refStack) {\n    // could be an Object or a Map\n    const isMap = typ !== 'Object'\n    // it's slightly quicker to use Object.keys() than Object.entries()\n    const keys = isMap ? obj.keys() : Object.keys(obj)\n    const maxLength = isMap ? obj.size : keys.length\n\n    /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */\n    let entries\n\n    if (maxLength) {\n      // Pre-allocate the array with the expected size\n      entries = new Array(maxLength)\n      refStack = Ref.createCheck(refStack, obj)\n      const skipUndefined = !isMap && options.ignoreUndefinedProperties\n\n      let i = 0\n      for (const key of keys) {\n        const value = isMap ? obj.get(key) : obj[key]\n        if (skipUndefined && value === undefined) {\n          continue\n        }\n        entries[i++] = [\n          objectToTokens(key, options, refStack),\n          objectToTokens(value, options, refStack)\n        ]\n      }\n\n      // Truncate only if properties were skipped\n      if (i < maxLength) {\n        entries.length = i\n      }\n    }\n\n    if (!entries?.length) {\n      if (options.addBreakTokens === true) {\n        return [simpleTokens.emptyMap, new Token(Type.break)]\n      }\n      return simpleTokens.emptyMap\n    }\n\n    sortMapEntries(entries, options)\n    if (options.addBreakTokens) {\n      return [new Token(Type.map, entries.length), entries, new Token(Type.break)]\n    }\n    return [new Token(Type.map, entries.length), entries]\n  }\n}\n\ntypeEncoders.Map = typeEncoders.Object\ntypeEncoders.Buffer = typeEncoders.Uint8Array\nfor (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {\n  typeEncoders[`${typ}Array`] = typeEncoders.DataView\n}\n\n/**\n * @param {any} obj\n * @param {EncodeOptions} [options]\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\nfunction objectToTokens (obj, options = {}, refStack) {\n  const typ = is(obj)\n  const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]\n  if (typeof customTypeEncoder === 'function') {\n    const tokens = customTypeEncoder(obj, typ, options, refStack)\n    if (tokens != null) {\n      return tokens\n    }\n  }\n  const typeEncoder = typeEncoders[typ]\n  if (!typeEncoder) {\n    throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)\n  }\n  return typeEncoder(obj, typ, options, refStack)\n}\n\n/*\nCBOR key sorting is a mess.\n\nThe canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9\nincludes the wording:\n\n> The keys in every map must be sorted lowest value to highest.\n> Sorting is performed on the bytes of the representation of the key\n> data items without paying attention to the 3/5 bit splitting for\n> major types.\n> ...\n>  *  If two keys have different lengths, the shorter one sorts\n      earlier;\n>  *  If two keys have the same length, the one with the lower value\n      in (byte-wise) lexical order sorts earlier.\n\n1. It is not clear what \"bytes of the representation of the key\" means: is it\n   the CBOR representation, or the binary representation of the object itself?\n   Consider the int and uint difference here.\n2. It is not clear what \"without paying attention to\" means: do we include it\n   and compare on that? Or do we omit the special prefix byte, (mostly) treating\n   the key in its plain binary representation form.\n\nThe FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR\nwording and clarifies it according to their understanding.\nhttps://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding\n\n> The keys in every map must be sorted lowest value to highest. Sorting is\n> performed on the bytes of the representation of the key data items without\n> paying attention to the 3/5 bit splitting for major types. The sorting rules\n> are:\n>  * If the major types are different, the one with the lower value in numerical\n>    order sorts earlier.\n>  * If two keys have different lengths, the shorter one sorts earlier;\n>  * If two keys have the same length, the one with the lower value in\n>    (byte-wise) lexical order sorts earlier.\n\nSome other implementations, such as borc, do a full encode then do a\nlength-first, byte-wise-second comparison:\nhttps://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358\nhttps://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151\n\nThis has the benefit of being able to easily handle arbitrary keys, including\ncomplex types (maps and arrays).\n\nWe'll opt for the FIDO approach, since it affords some efficies since we don't\nneed a full encode of each key to determine order and can defer to the types\nto determine how to most efficiently order their values (i.e. int and uint\nordering can be done on the numbers, no need for byte-wise, for example).\n\nRecommendation: stick to single key types or you'll get into trouble, and prefer\nstring keys because it's much simpler that way.\n*/\n\n/**\n * @param {TokenOrNestedTokens[]} entries\n * @param {EncodeOptions} options\n */\nfunction sortMapEntries (entries, options) {\n  if (options.mapSorter) {\n    entries.sort(options.mapSorter)\n  }\n}\n\n/**\n * @param {(Token|Token[])[]} e1\n * @param {(Token|Token[])[]} e2\n * @returns {number}\n */\nfunction mapSorter (e1, e2) {\n  // the key position ([0]) could have a single token or an array\n  // almost always it'll be a single token but complex key might get involved\n  /* c8 ignore next 2 */\n  const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]\n  const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]\n\n  // different key types\n  if (keyToken1.type !== keyToken2.type) {\n    return keyToken1.type.compare(keyToken2.type)\n  }\n\n  const major = keyToken1.type.major\n  // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)\n  const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)\n  /* c8 ignore next 5 */\n  if (tcmp === 0) {\n    // duplicate key or complex type where the first token matched,\n    // i.e. a map or array and we're only comparing the opening token\n    console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')\n  }\n  return tcmp\n}\n\n/**\n * @typedef {Token & { _keyBytes?: Uint8Array }} TokenEx\n *\n * @param {(Token|Token[])[]} e1\n * @param {(Token|Token[])[]} e2\n * @returns {number}\n */\nfunction rfc8949MapSorter (e1, e2) {\n  if (e1[0] instanceof Token && e2[0] instanceof Token) {\n    const t1 = /** @type {TokenEx} */ (e1[0])\n    const t2 = /** @type {TokenEx} */ (e2[0])\n\n    if (!t1._keyBytes) {\n      t1._keyBytes = encodeRfc8949(t1.value)\n    }\n\n    if (!t2._keyBytes) {\n      t2._keyBytes = encodeRfc8949(t2.value)\n    }\n\n    return compare(t1._keyBytes, t2._keyBytes)\n  }\n\n  throw new Error('rfc8949MapSorter: complex key types are not supported yet')\n}\n\n/**\n * @param {any} data\n * @returns {Uint8Array}\n */\nfunction encodeRfc8949 (data) {\n  return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {TokenOrNestedTokens} tokens\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n */\nfunction tokensToEncoded (writer, tokens, encoders, options) {\n  if (Array.isArray(tokens)) {\n    for (const token of tokens) {\n      tokensToEncoded(writer, token, encoders, options)\n    }\n  } else {\n    encoders[tokens.type.major](writer, tokens, options)\n  }\n}\n\n// CBOR major type prefixes, cached from Type for hot path performance\nconst MAJOR_UINT = Type.uint.majorEncoded\nconst MAJOR_NEGINT = Type.negint.majorEncoded\nconst MAJOR_BYTES = Type.bytes.majorEncoded\nconst MAJOR_STRING = Type.string.majorEncoded\nconst MAJOR_ARRAY = Type.array.majorEncoded\n\n// Simple value bytes (CBOR major type 7 + minor value)\nconst SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE\nconst SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE\nconst SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL\nconst SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED\n\nconst neg1b = BigInt(-1)\nconst pos1b = BigInt(1)\n\n/**\n * Check if direct encoding can be used for the given options.\n * Direct encoding bypasses token creation for most values.\n * @param {EncodeOptions} options\n * @returns {boolean}\n */\nfunction canDirectEncode (options) {\n  // Cannot use direct encode with addBreakTokens (needs special break token handling).\n  // Direct encode checks typeEncoders per-value, falling back to tokens as needed.\n  // Maps fall back to token-based encoding for efficient key sorting.\n  return options.addBreakTokens !== true\n}\n\n/**\n * Direct encode a value to the writer, bypassing token creation for most types.\n * Falls back to token-based encoding for custom type encoders.\n * @param {ByteWriter} writer\n * @param {any} data\n * @param {EncodeOptions} options\n * @param {Reference|undefined} refStack\n */\nfunction directEncode (writer, data, options, refStack) {\n  const typ = is(data)\n\n  // Check for custom encoder for THIS specific type\n  const customEncoder = options.typeEncoders && options.typeEncoders[typ]\n  if (customEncoder) {\n    const tokens = customEncoder(data, typ, options, refStack)\n    if (tokens != null) {\n      // Custom encoder returned tokens, serialize immediately\n      tokensToEncoded(writer, tokens, cborEncoders, options)\n      return\n    }\n    // Custom encoder returned null, fall through to default handling\n  }\n\n  // Direct encode based on type\n  switch (typ) {\n    case 'null':\n      writer.push([SIMPLE_NULL])\n      return\n\n    case 'undefined':\n      writer.push([SIMPLE_UNDEFINED])\n      return\n\n    case 'boolean':\n      writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE])\n      return\n\n    case 'number':\n      if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {\n        // Float, use token encoder for complex float encoding\n        encodeFloat(writer, new Token(Type.float, data), options)\n      } else if (data >= 0) {\n        encodeUintValue(writer, MAJOR_UINT, data)\n      } else {\n        // Negative integer\n        encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)\n      }\n      return\n\n    case 'bigint':\n      if (data >= BigInt(0)) {\n        encodeUintValue(writer, MAJOR_UINT, data)\n      } else {\n        encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)\n      }\n      return\n\n    case 'string': {\n      const bytes = fromString(data)\n      encodeUintValue(writer, MAJOR_STRING, bytes.length)\n      writer.push(bytes)\n      return\n    }\n\n    case 'Uint8Array':\n      encodeUintValue(writer, MAJOR_BYTES, data.length)\n      writer.push(data)\n      return\n\n    case 'Array':\n      if (!data.length) {\n        writer.push([MAJOR_ARRAY]) // Empty array: 0x80\n        return\n      }\n      refStack = Ref.createCheck(refStack, data)\n      encodeUintValue(writer, MAJOR_ARRAY, data.length)\n      for (const elem of data) {\n        directEncode(writer, elem, options, refStack)\n      }\n      return\n\n    case 'Object':\n    case 'Map':\n      // Maps require key sorting, use token-based encoding for efficiency\n      // (pre-encoding all keys for sorting is expensive)\n      {\n        const tokens = typeEncoders.Object(data, typ, options, refStack)\n        tokensToEncoded(writer, tokens, cborEncoders, options)\n      }\n      return\n\n    default:\n    // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)\n    {\n      const typeEncoder = typeEncoders[typ]\n      if (!typeEncoder) {\n        throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)\n      }\n      const tokens = typeEncoder(data, typ, options, refStack)\n      tokensToEncoded(writer, tokens, cborEncoders, options)\n    }\n  }\n}\n\n/**\n * @param {any} data\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n * @param {Uint8Array} [destination]\n * @returns {Uint8Array}\n */\nfunction encodeCustom (data, encoders, options, destination) {\n  // arg ordering is different to encodeInto for backward compatibility\n  const hasDest = destination instanceof Uint8Array\n  let writeTo = hasDest ? new U8Bl(destination) : defaultWriter\n\n  const tokens = objectToTokens(data, options)\n  if (!Array.isArray(tokens) && options.quickEncodeToken) {\n    const quickBytes = options.quickEncodeToken(tokens)\n    if (quickBytes) {\n      if (hasDest) {\n        // Copy quick bytes into destination buffer\n        writeTo.push(quickBytes)\n        return writeTo.toBytes()\n      }\n      return quickBytes\n    }\n    const encoder = encoders[tokens.type.major]\n    if (encoder.encodedSize) {\n      const size = encoder.encodedSize(tokens, options)\n      if (!hasDest) {\n        writeTo = new Bl(size)\n      }\n      encoder(writeTo, tokens, options)\n      /* c8 ignore next 4 */\n      // this would be a problem with encodedSize() functions\n      if (writeTo.chunks.length !== 1) {\n        throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)\n      }\n      return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])\n    }\n  }\n  writeTo.reset()\n  tokensToEncoded(writeTo, tokens, encoders, options)\n  return writeTo.toBytes(true)\n}\n\n/**\n * @param {any} data\n * @param {EncodeOptions} [options]\n * @returns {Uint8Array}\n */\nfunction encode (data, options) {\n  options = Object.assign({}, defaultEncodeOptions, options)\n\n  // Use direct encode path when possible\n  if (canDirectEncode(options)) {\n    defaultWriter.reset()\n    directEncode(defaultWriter, data, options, undefined)\n    return defaultWriter.toBytes(true)\n  }\n\n  return encodeCustom(data, cborEncoders, options)\n}\n\n/**\n * @param {any} data\n * @param {Uint8Array} destination\n * @param {EncodeOptions} [options]\n * @returns {{ written: number }}\n */\nfunction encodeInto (data, destination, options) {\n  options = Object.assign({}, defaultEncodeOptions, options)\n\n  // Use direct encode path when possible\n  if (canDirectEncode(options)) {\n    const writer = new U8Bl(destination)\n    directEncode(writer, data, options, undefined)\n    return { written: writer.toBytes().length }\n  }\n\n  const result = encodeCustom(data, cborEncoders, options, destination)\n  return { written: result.length }\n}\n\nexport { objectToTokens, encode, encodeCustom, encodeInto, Ref }\n", "import { decodeErrPrefix } from './common.js'\nimport { Type } from './token.js'\nimport { jump, quick } from './jump.js'\nimport { asU8A } from './byte-utils.js'\n\n/**\n * @typedef {import('./token.js').Token} Token\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n * @typedef {import('../interface').DecodeTokenizer} DecodeTokenizer\n */\n\nconst defaultDecodeOptions = {\n  strict: false,\n  allowIndefinite: true,\n  allowUndefined: true,\n  allowBigInt: true\n}\n\n/**\n * @implements {DecodeTokenizer}\n */\nclass Tokeniser {\n  /**\n   * @param {Uint8Array} data\n   * @param {DecodeOptions} options\n   */\n  constructor (data, options = {}) {\n    this._pos = 0\n    this.data = data\n    this.options = options\n  }\n\n  pos () {\n    return this._pos\n  }\n\n  done () {\n    return this._pos >= this.data.length\n  }\n\n  next () {\n    const byt = this.data[this._pos]\n    let token = quick[byt]\n    if (token === undefined) {\n      const decoder = jump[byt]\n      /* c8 ignore next 4 */\n      // if we're here then there's something wrong with our jump or quick lists!\n      if (!decoder) {\n        throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)\n      }\n      const minor = byt & 31\n      token = decoder(this.data, this._pos, minor, this.options)\n    }\n    // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)\n    this._pos += token.encodedLength\n    return token\n  }\n}\n\nconst DONE = Symbol.for('DONE')\nconst BREAK = Symbol.for('BREAK')\n\n/**\n * @param {Token} token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokenToArray (token, tokeniser, options) {\n  const arr = []\n  for (let i = 0; i < token.value; i++) {\n    const value = tokensToObject(tokeniser, options)\n    if (value === BREAK) {\n      if (token.value === Infinity) {\n        // normal end to indefinite length array\n        break\n      }\n      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)\n    }\n    if (value === DONE) {\n      throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)\n    }\n    arr[i] = value\n  }\n  return arr\n}\n\n/**\n * @param {Token} token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokenToMap (token, tokeniser, options) {\n  const useMaps = options.useMaps === true\n  const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true\n  const obj = useMaps ? undefined : {}\n  const m = useMaps ? new Map() : undefined\n  for (let i = 0; i < token.value; i++) {\n    const key = tokensToObject(tokeniser, options)\n    if (key === BREAK) {\n      if (token.value === Infinity) {\n        // normal end to indefinite length map\n        break\n      }\n      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)\n    }\n    if (key === DONE) {\n      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)\n    }\n    if (!useMaps && typeof key !== 'string') {\n      throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)\n    }\n    if (rejectDuplicateMapKeys) {\n      // @ts-ignore\n      if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {\n        throw new Error(`${decodeErrPrefix} found repeat map key \"${key}\"`)\n      }\n    }\n    const value = tokensToObject(tokeniser, options)\n    if (value === DONE) {\n      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)\n    }\n    if (useMaps) {\n      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types\n      m.set(key, value)\n    } else {\n      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types\n      obj[key] = value\n    }\n  }\n  // @ts-ignore c'mon man\n  return useMaps ? m : obj\n}\n\n/**\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokensToObject (tokeniser, options) {\n  // should we support array as an argument?\n  // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?\n  if (tokeniser.done()) {\n    return DONE\n  }\n\n  const token = tokeniser.next()\n\n  if (Type.equals(token.type, Type.break)) {\n    return BREAK\n  }\n\n  if (token.type.terminal) {\n    return token.value\n  }\n\n  if (Type.equals(token.type, Type.array)) {\n    return tokenToArray(token, tokeniser, options)\n  }\n\n  if (Type.equals(token.type, Type.map)) {\n    return tokenToMap(token, tokeniser, options)\n  }\n\n  if (Type.equals(token.type, Type.tag)) {\n    if (options.tags && typeof options.tags[token.value] === 'function') {\n      const tagged = tokensToObject(tokeniser, options)\n      return options.tags[token.value](tagged)\n    }\n    throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)\n  }\n  /* c8 ignore next */\n  throw new Error('unsupported')\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {[any, Uint8Array]}\n */\nfunction decodeFirst (data, options) {\n  if (!(data instanceof Uint8Array)) {\n    throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)\n  }\n  options = Object.assign({}, defaultDecodeOptions, options)\n  // Convert Buffer to plain Uint8Array for faster slicing in decode path\n  const u8aData = asU8A(data)\n  const tokeniser = options.tokenizer || new Tokeniser(u8aData, options)\n  const decoded = tokensToObject(tokeniser, options)\n  if (decoded === DONE) {\n    throw new Error(`${decodeErrPrefix} did not find any content to decode`)\n  }\n  if (decoded === BREAK) {\n    throw new Error(`${decodeErrPrefix} got unexpected break`)\n  }\n  return [decoded, data.subarray(tokeniser.pos())]\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {any}\n */\nfunction decode (data, options) {\n  const [decoded, remainder] = decodeFirst(data, options)\n  if (remainder.length > 0) {\n    throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)\n  }\n  return decoded\n}\n\nexport { Tokeniser, tokensToObject, decode, decodeFirst }\n", "import { decode as cborDecode, encode as cborEncode } from 'cborg';\n\n/**\n * CBOR (Concise Binary Object Representation) encoding and decoding utilities.\n *\n * Provides a thin wrapper around the `cborg` library, exposing `encode` and `decode`\n * operations for use by COSE and EAT implementations.\n *\n * @see {@link https://www.rfc-editor.org/rfc/rfc8949 | RFC 8949 \u2014 CBOR}\n */\nexport class Cbor {\n  /**\n   * Encodes a JavaScript value to a CBOR byte string.\n   *\n   * @param value - The value to encode. Supports objects, arrays, strings, numbers,\n   *   booleans, null, undefined, Uint8Array (encoded as CBOR byte string), and Map.\n   * @returns The CBOR-encoded bytes.\n   */\n  public static encode(value: unknown): Uint8Array {\n    return cborEncode(value);\n  }\n\n  /**\n   * Decodes a CBOR byte string to a JavaScript value.\n   *\n   * CBOR maps are decoded as JavaScript `Map` instances to support integer keys,\n   * which is required by COSE (RFC 9052) and EAT (RFC 9711).\n   *\n   * @param data - The CBOR-encoded bytes to decode.\n   * @returns The decoded JavaScript value.\n   * @throws If the input is not valid CBOR.\n   */\n  public static decode<T = unknown>(data: Uint8Array): T {\n    return cborDecode(data, { useMaps: true }) as T;\n  }\n}\n", "import type { Jwk } from '../jose/jwk.js';\n\nimport { Convert } from '@enbox/common';\n\nimport { CryptoError, CryptoErrorCode } from '../crypto-error.js';\n\n/**\n * COSE Key Type values (RFC 9052, Section 7).\n *\n * @see {@link https://www.iana.org/assignments/cose/cose.xhtml#key-type | IANA COSE Key Types}\n */\nexport enum CoseKeyType {\n  /** Octet Key Pair (e.g., Ed25519, X25519) */\n  OKP = 1,\n  /** Elliptic Curve (e.g., P-256, P-384, P-521) */\n  EC2 = 2,\n  /** Symmetric key */\n  Symmetric = 4,\n}\n\n/**\n * COSE Elliptic Curve identifiers (RFC 9053, Section 7.1).\n *\n * @see {@link https://www.iana.org/assignments/cose/cose.xhtml#elliptic-curves | IANA COSE Elliptic Curves}\n */\nexport enum CoseEllipticCurve {\n  /** NIST P-256 (secp256r1) */\n  P256 = 1,\n  /** NIST P-384 (secp384r1) */\n  P384 = 2,\n  /** NIST P-521 (secp521r1) */\n  P521 = 3,\n  /** X25519 for ECDH */\n  X25519 = 4,\n  /** X448 for ECDH */\n  X448 = 5,\n  /** Ed25519 for EdDSA */\n  Ed25519 = 6,\n  /** Ed448 for EdDSA */\n  Ed448 = 7,\n  /** secp256k1 */\n  Secp256k1 = 8,\n}\n\n/**\n * COSE Algorithm identifiers (RFC 9053).\n *\n * Only includes algorithms relevant to Enbox confidential compute.\n *\n * @see {@link https://www.iana.org/assignments/cose/cose.xhtml#algorithms | IANA COSE Algorithms}\n */\nexport enum CoseAlgorithm {\n  /** EdDSA (Ed25519 or Ed448) */\n  EdDSA = -8,\n  /** ECDSA with SHA-256 (P-256) */\n  ES256 = -7,\n  /** ECDSA with SHA-384 (P-384) */\n  ES384 = -35,\n  /** ECDSA with SHA-512 (P-521) */\n  ES512 = -36,\n  /** ECDSA with SHA-256 (secp256k1) */\n  ES256K = -47,\n}\n\n/**\n * COSE Key common parameter labels (RFC 9052, Section 7.1).\n */\nenum CoseKeyLabel {\n  /** Key Type (kty) */\n  Kty = 1,\n  /** Key ID (kid) */\n  Kid = 2,\n  /** Algorithm */\n  Alg = 3,\n  /** Key Operations */\n  KeyOps = 4,\n  /** Base IV */\n  BaseIv = 5,\n}\n\n/**\n * COSE Key type-specific parameter labels.\n *\n * For OKP and EC2 keys, the curve and coordinate labels share the same\n * negative-integer label space (RFC 9053, Section 7.1-7.2).\n */\nenum CoseKeyParamLabel {\n  /** Curve identifier (OKP and EC2) */\n  Crv = -1,\n  /** X coordinate (OKP public key or EC2 x-coordinate) */\n  X = -2,\n  /** Y coordinate (EC2 only) */\n  Y = -3,\n  /** Private key (OKP d value or EC2 d value) */\n  D = -4,\n}\n\n/**\n * Maps JWK curve names to COSE elliptic curve identifiers.\n */\nconst jwkCrvToCose: Record<string, CoseEllipticCurve> = {\n  'P-256'     : CoseEllipticCurve.P256,\n  'P-384'     : CoseEllipticCurve.P384,\n  'P-521'     : CoseEllipticCurve.P521,\n  'X25519'    : CoseEllipticCurve.X25519,\n  'Ed25519'   : CoseEllipticCurve.Ed25519,\n  'Ed448'     : CoseEllipticCurve.Ed448,\n  'secp256k1' : CoseEllipticCurve.Secp256k1,\n};\n\n/**\n * Maps COSE elliptic curve identifiers to JWK curve names.\n */\nconst coseCrvToJwk: Record<number, string> = {\n  [CoseEllipticCurve.P256]      : 'P-256',\n  [CoseEllipticCurve.P384]      : 'P-384',\n  [CoseEllipticCurve.P521]      : 'P-521',\n  [CoseEllipticCurve.X25519]    : 'X25519',\n  [CoseEllipticCurve.Ed25519]   : 'Ed25519',\n  [CoseEllipticCurve.Ed448]     : 'Ed448',\n  [CoseEllipticCurve.Secp256k1] : 'secp256k1',\n};\n\n/**\n * Maps JWK algorithm names to COSE algorithm identifiers.\n */\nconst jwkAlgToCose: Record<string, CoseAlgorithm> = {\n  'EdDSA'  : CoseAlgorithm.EdDSA,\n  'ES256'  : CoseAlgorithm.ES256,\n  'ES384'  : CoseAlgorithm.ES384,\n  'ES512'  : CoseAlgorithm.ES512,\n  'ES256K' : CoseAlgorithm.ES256K,\n};\n\n/**\n * Maps COSE algorithm identifiers to JWK algorithm names.\n */\nconst coseAlgToJwk: Record<number, string> = {\n  [CoseAlgorithm.EdDSA]  : 'EdDSA',\n  [CoseAlgorithm.ES256]  : 'ES256',\n  [CoseAlgorithm.ES384]  : 'ES384',\n  [CoseAlgorithm.ES512]  : 'ES512',\n  [CoseAlgorithm.ES256K] : 'ES256K',\n};\n\n/**\n * Utilities for converting between JWK and COSE key representations.\n *\n * COSE keys use integer labels and CBOR encoding, while JWK uses string\n * property names and JSON. This class provides bidirectional conversion.\n *\n * @see {@link https://www.rfc-editor.org/rfc/rfc9052#section-7 | RFC 9052, Section 7}\n */\nexport class CoseKey {\n  /**\n   * Converts a JWK to a COSE key represented as a Map.\n   *\n   * @param jwk - The JWK to convert.\n   * @returns A Map with integer labels as keys, suitable for CBOR encoding.\n   * @throws {CryptoError} If the JWK key type or curve is not supported.\n   */\n  public static fromJwk(jwk: Jwk): Map<number, unknown> {\n    const coseKey = new Map<number, unknown>();\n\n    if (jwk.kty === 'OKP') {\n      coseKey.set(CoseKeyLabel.Kty, CoseKeyType.OKP);\n\n      const crv = jwk.crv;\n      if (crv === undefined || !(crv in jwkCrvToCose)) {\n        throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `CoseKey: unsupported OKP curve '${crv}'`);\n      }\n      coseKey.set(CoseKeyParamLabel.Crv, jwkCrvToCose[crv]);\n\n      if (jwk.x !== undefined) {\n        coseKey.set(CoseKeyParamLabel.X, Convert.base64Url(jwk.x).toUint8Array());\n      }\n      if (jwk.d !== undefined) {\n        coseKey.set(CoseKeyParamLabel.D, Convert.base64Url(jwk.d).toUint8Array());\n      }\n    } else if (jwk.kty === 'EC') {\n      coseKey.set(CoseKeyLabel.Kty, CoseKeyType.EC2);\n\n      const crv = jwk.crv;\n      if (crv === undefined || !(crv in jwkCrvToCose)) {\n        throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `CoseKey: unsupported EC curve '${crv}'`);\n      }\n      coseKey.set(CoseKeyParamLabel.Crv, jwkCrvToCose[crv]);\n\n      if (jwk.x !== undefined) {\n        coseKey.set(CoseKeyParamLabel.X, Convert.base64Url(jwk.x).toUint8Array());\n      }\n      if (jwk.y !== undefined) {\n        coseKey.set(CoseKeyParamLabel.Y, Convert.base64Url(jwk.y).toUint8Array());\n      }\n      if (jwk.d !== undefined) {\n        coseKey.set(CoseKeyParamLabel.D, Convert.base64Url(jwk.d).toUint8Array());\n      }\n    } else {\n      throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `CoseKey: unsupported key type '${jwk.kty}'`);\n    }\n\n    if (jwk.kid !== undefined) {\n      coseKey.set(CoseKeyLabel.Kid, Convert.string(jwk.kid).toUint8Array());\n    }\n\n    if (jwk.alg !== undefined && jwk.alg in jwkAlgToCose) {\n      coseKey.set(CoseKeyLabel.Alg, jwkAlgToCose[jwk.alg]);\n    }\n\n    return coseKey;\n  }\n\n  /**\n   * Converts a COSE key Map to a JWK.\n   *\n   * @param coseKey - A Map with integer labels as keys (from CBOR decoding).\n   * @returns The equivalent JWK.\n   * @throws {CryptoError} If the COSE key type or curve is not supported.\n   */\n  public static toJwk(coseKey: Map<number, unknown>): Jwk {\n    const kty = coseKey.get(CoseKeyLabel.Kty) as number;\n\n    if (kty === CoseKeyType.OKP) {\n      const crv = coseKey.get(CoseKeyParamLabel.Crv) as number;\n      if (!(crv in coseCrvToJwk)) {\n        throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `CoseKey: unsupported COSE OKP curve ${crv}`);\n      }\n\n      const jwk: Jwk = {\n        kty : 'OKP',\n        crv : coseCrvToJwk[crv],\n      };\n\n      const x = coseKey.get(CoseKeyParamLabel.X) as Uint8Array | undefined;\n      if (x !== undefined) {\n        jwk.x = Convert.uint8Array(x).toBase64Url();\n      }\n\n      const d = coseKey.get(CoseKeyParamLabel.D) as Uint8Array | undefined;\n      if (d !== undefined) {\n        jwk.d = Convert.uint8Array(d).toBase64Url();\n      }\n\n      CoseKey.applyCommonFields(coseKey, jwk);\n      return jwk;\n\n    } else if (kty === CoseKeyType.EC2) {\n      const crv = coseKey.get(CoseKeyParamLabel.Crv) as number;\n      if (!(crv in coseCrvToJwk)) {\n        throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `CoseKey: unsupported COSE EC2 curve ${crv}`);\n      }\n\n      const jwk: Jwk = {\n        kty : 'EC',\n        crv : coseCrvToJwk[crv],\n      };\n\n      const x = coseKey.get(CoseKeyParamLabel.X) as Uint8Array | undefined;\n      if (x !== undefined) {\n        jwk.x = Convert.uint8Array(x).toBase64Url();\n      }\n\n      const y = coseKey.get(CoseKeyParamLabel.Y) as Uint8Array | undefined;\n      if (y !== undefined) {\n        jwk.y = Convert.uint8Array(y).toBase64Url();\n      }\n\n      const d = coseKey.get(CoseKeyParamLabel.D) as Uint8Array | undefined;\n      if (d !== undefined) {\n        jwk.d = Convert.uint8Array(d).toBase64Url();\n      }\n\n      CoseKey.applyCommonFields(coseKey, jwk);\n      return jwk;\n\n    } else {\n      throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `CoseKey: unsupported COSE key type ${kty}`);\n    }\n  }\n\n  /**\n   * Infers the COSE algorithm identifier from a JWK.\n   *\n   * If the JWK has an `alg` field, it is used directly. Otherwise, the algorithm\n   * is inferred from the key type and curve.\n   *\n   * @param jwk - The JWK to infer the algorithm from.\n   * @returns The COSE algorithm identifier.\n   * @throws {CryptoError} If the algorithm cannot be determined.\n   */\n  public static algorithmFromJwk(jwk: Jwk): CoseAlgorithm {\n    if (jwk.alg !== undefined && jwk.alg in jwkAlgToCose) {\n      return jwkAlgToCose[jwk.alg];\n    }\n\n    // Infer from key type and curve.\n    if (jwk.kty === 'OKP') {\n      if (jwk.crv === 'Ed25519' || jwk.crv === 'Ed448') {\n        return CoseAlgorithm.EdDSA;\n      }\n    } else if (jwk.kty === 'EC') {\n      switch (jwk.crv) {\n        case 'P-256': return CoseAlgorithm.ES256;\n        case 'P-384': return CoseAlgorithm.ES384;\n        case 'P-521': return CoseAlgorithm.ES512;\n        case 'secp256k1': return CoseAlgorithm.ES256K;\n      }\n    }\n\n    throw new CryptoError(\n      CryptoErrorCode.AlgorithmNotSupported,\n      `CoseKey: cannot determine COSE algorithm for key type '${jwk.kty}' curve '${jwk.crv}'`\n    );\n  }\n\n  /**\n   * Maps a COSE algorithm identifier to a JWK algorithm name.\n   *\n   * @param alg - The COSE algorithm identifier.\n   * @returns The JWK algorithm name.\n   * @throws {CryptoError} If the algorithm is not supported.\n   */\n  public static algorithmToJwk(alg: CoseAlgorithm): string {\n    if (alg in coseAlgToJwk) {\n      return coseAlgToJwk[alg];\n    }\n    throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `CoseKey: unsupported COSE algorithm ${alg}`);\n  }\n\n  /**\n   * Applies common COSE key fields (kid, alg) to a JWK.\n   */\n  private static applyCommonFields(coseKey: Map<number, unknown>, jwk: Jwk): void {\n    const kid = coseKey.get(CoseKeyLabel.Kid) as Uint8Array | undefined;\n    if (kid !== undefined) {\n      jwk.kid = Convert.uint8Array(kid).toString();\n    }\n\n    const alg = coseKey.get(CoseKeyLabel.Alg) as number | undefined;\n    if (alg !== undefined && alg in coseAlgToJwk) {\n      jwk.alg = coseAlgToJwk[alg];\n    }\n  }\n}\n", "import type { Jwk } from '../jose/jwk.js';\n\nimport { Cbor } from './cbor.js';\nimport { Ed25519 } from '../primitives/ed25519.js';\nimport { Secp256r1 } from '../primitives/secp256r1.js';\nimport { CoseAlgorithm, CoseKey } from './cose-key.js';\nimport { CryptoError, CryptoErrorCode } from '../crypto-error.js';\n\n/**\n * COSE_Sign1 protected header parameters.\n *\n * The protected header is integrity-protected by inclusion in the Sig_structure.\n * At minimum, it MUST contain the algorithm identifier.\n *\n * @see {@link https://www.rfc-editor.org/rfc/rfc9052#section-4 | RFC 9052, Section 4}\n */\nexport interface CoseSign1ProtectedHeader {\n  /** Algorithm identifier (label 1). Required. */\n  alg: CoseAlgorithm;\n\n  /** Content type (label 3). */\n  contentType?: string | number;\n\n  /** Key ID (label 4). */\n  kid?: Uint8Array;\n\n  /** Additional header parameters. */\n  [key: string]: unknown;\n}\n\n/**\n * COSE_Sign1 unprotected header parameters.\n *\n * These parameters are NOT integrity-protected.\n *\n * @see {@link https://www.rfc-editor.org/rfc/rfc9052#section-4 | RFC 9052, Section 4}\n */\nexport interface CoseSign1UnprotectedHeader {\n  /** Key ID (label 4). */\n  kid?: Uint8Array;\n\n  /** Additional header parameters. */\n  [key: string]: unknown;\n}\n\n/**\n * Parameters for creating a COSE_Sign1 structure.\n */\nexport interface CoseSign1CreateParams {\n  /** The signing key in JWK format. Must contain the private key (`d`). */\n  key: Jwk;\n\n  /** The payload to sign. */\n  payload: Uint8Array;\n\n  /**\n   * Protected header parameters. If omitted, the algorithm is inferred from the key\n   * and a minimal protected header `{ alg }` is used.\n   */\n  protectedHeader?: CoseSign1ProtectedHeader;\n\n  /** Unprotected header parameters. */\n  unprotectedHeader?: CoseSign1UnprotectedHeader;\n\n  /**\n   * External additional authenticated data (external_aad).\n   * Included in the Sig_structure but not in the COSE_Sign1 message itself.\n   * Defaults to empty bytes.\n   */\n  externalAad?: Uint8Array;\n\n  /**\n   * If true, the payload is detached (not included in the COSE_Sign1 serialization).\n   * The payload field in the CBOR array will be `null`.\n   */\n  detachedPayload?: boolean;\n}\n\n/**\n * Parameters for verifying a COSE_Sign1 structure.\n */\nexport interface CoseSign1VerifyParams {\n  /** The COSE_Sign1 CBOR-encoded message to verify. */\n  coseSign1: Uint8Array;\n\n  /** The public key in JWK format for verification. */\n  key: Jwk;\n\n  /**\n   * External additional authenticated data (external_aad).\n   * Must match the value used during signing.\n   * Defaults to empty bytes.\n   */\n  externalAad?: Uint8Array;\n\n  /**\n   * Detached payload. Required if the COSE_Sign1 was created with `detachedPayload: true`.\n   */\n  payload?: Uint8Array;\n}\n\n/**\n * Decoded COSE_Sign1 structure.\n */\nexport interface CoseSign1Decoded {\n  /** The protected header parameters (decoded from CBOR). */\n  protectedHeader: CoseSign1ProtectedHeader;\n\n  /** The raw protected header bytes (needed for signature verification). */\n  protectedHeaderBytes: Uint8Array;\n\n  /** The unprotected header parameters. */\n  unprotectedHeader: Map<number, unknown>;\n\n  /** The payload (null if detached). */\n  payload: Uint8Array | null;\n\n  /** The signature. */\n  signature: Uint8Array;\n}\n\n/**\n * COSE header label constants (RFC 9052, Section 3.1).\n */\nenum CoseHeaderLabel {\n  /** Algorithm identifier */\n  Alg = 1,\n  /** Critical headers */\n  Crit = 2,\n  /** Content type */\n  ContentType = 3,\n  /** Key ID */\n  Kid = 4,\n}\n\n/**\n * CBOR tag for COSE_Sign1 (RFC 9052, Section 4.2).\n */\n// const COSE_SIGN1_TAG = 18;\n\n/**\n * COSE_Sign1 implementation per RFC 9052.\n *\n * Provides creation, verification, and decoding of COSE_Sign1 (single-signer)\n * signed messages. This is the CBOR-based counterpart to JOSE/JWS and is used\n * in TEE attestation (EAT tokens), CWT, and other COSE-based protocols.\n *\n * Supported algorithms:\n * - EdDSA (Ed25519) \u2014 CoseAlgorithm.EdDSA (-8)\n * - ES256 (P-256 / secp256r1 with SHA-256) \u2014 CoseAlgorithm.ES256 (-7)\n *\n * @see {@link https://www.rfc-editor.org/rfc/rfc9052#section-4.3 | RFC 9052, Section 4.3}\n */\nexport class CoseSign1 {\n  /**\n   * Creates a COSE_Sign1 message.\n   *\n   * Constructs the `Sig_structure1` to-be-signed bytes per RFC 9052 Section 4.4,\n   * signs them with the provided key, and returns the CBOR-encoded COSE_Sign1 array:\n   *\n   * ```\n   * COSE_Sign1 = [\n   *   protected : bstr,       ; CBOR-encoded protected header\n   *   unprotected : map,      ; unprotected header parameters\n   *   payload : bstr / nil,   ; payload (nil if detached)\n   *   signature : bstr        ; signature\n   * ]\n   * ```\n   *\n   * @param params - The parameters for creating the COSE_Sign1 message.\n   * @returns The CBOR-encoded COSE_Sign1 message.\n   * @throws {CryptoError} If the algorithm is not supported or signing fails.\n   *\n   * @see {@link https://www.rfc-editor.org/rfc/rfc9052#section-4.3 | RFC 9052, Section 4.3}\n   * @see {@link https://www.rfc-editor.org/rfc/rfc9052#section-4.4 | RFC 9052, Section 4.4}\n   */\n  public static async create(params: CoseSign1CreateParams): Promise<Uint8Array> {\n    const {\n      key,\n      payload,\n      externalAad = new Uint8Array(0),\n      detachedPayload = false,\n    } = params;\n\n    // Build the protected header.\n    const alg = params.protectedHeader?.alg ?? CoseKey.algorithmFromJwk(key);\n    const protectedHeaderMap = CoseSign1.buildProtectedHeaderMap(\n      params.protectedHeader ?? { alg }\n    );\n    const protectedHeaderBytes = Cbor.encode(protectedHeaderMap);\n\n    // Build the unprotected header.\n    const unprotectedHeaderMap = params.unprotectedHeader === undefined\n      ? new Map<number, unknown>()\n      : CoseSign1.buildUnprotectedHeaderMap(params.unprotectedHeader);\n\n    // Construct the Sig_structure1 (to-be-signed bytes).\n    const sigStructure = CoseSign1.buildSigStructure1(\n      protectedHeaderBytes, externalAad, payload\n    );\n    const toBeSigned = Cbor.encode(sigStructure);\n\n    // Sign the Sig_structure1 bytes.\n    const signature = await CoseSign1.signBytes(alg, key, toBeSigned);\n\n    // Assemble the COSE_Sign1 array.\n    const coseSign1Array = [\n      protectedHeaderBytes,\n      unprotectedHeaderMap,\n      detachedPayload ? null : payload,\n      signature,\n    ];\n\n    return Cbor.encode(coseSign1Array);\n  }\n\n  /**\n   * Verifies a COSE_Sign1 message.\n   *\n   * Decodes the CBOR-encoded message, reconstructs the `Sig_structure1`, and verifies\n   * the signature using the provided public key.\n   *\n   * @param params - The parameters for verifying the COSE_Sign1 message.\n   * @returns `true` if the signature is valid, `false` otherwise.\n   * @throws {CryptoError} If the message is malformed or the algorithm is not supported.\n   *\n   * @see {@link https://www.rfc-editor.org/rfc/rfc9052#section-4.4 | RFC 9052, Section 4.4}\n   */\n  public static async verify(params: CoseSign1VerifyParams): Promise<boolean> {\n    const {\n      coseSign1,\n      key,\n      externalAad = new Uint8Array(0),\n    } = params;\n\n    // Decode the COSE_Sign1 message.\n    const decoded = CoseSign1.decode(coseSign1);\n\n    // Resolve the payload (from message or detached parameter).\n    const payload = decoded.payload ?? params.payload ?? null;\n    if (payload === null) {\n      throw new CryptoError(\n        CryptoErrorCode.InvalidCoseSign1,\n        'CoseSign1: payload is detached but no payload was provided for verification'\n      );\n    }\n\n    // Reconstruct the Sig_structure1.\n    const sigStructure = CoseSign1.buildSigStructure1(\n      decoded.protectedHeaderBytes, externalAad, payload\n    );\n    const toBeSigned = Cbor.encode(sigStructure);\n\n    // Extract the algorithm from the protected header.\n    const alg = decoded.protectedHeader.alg;\n\n    // Verify the signature.\n    return CoseSign1.verifyBytes(alg, key, toBeSigned, decoded.signature);\n  }\n\n  /**\n   * Decodes a CBOR-encoded COSE_Sign1 message into its constituent parts.\n   *\n   * The COSE_Sign1 structure is a CBOR array of four elements:\n   * ```\n   * [protected, unprotected, payload, signature]\n   * ```\n   *\n   * The message may optionally be wrapped in CBOR tag 18.\n   *\n   * @param coseSign1 - The CBOR-encoded COSE_Sign1 message.\n   * @returns The decoded COSE_Sign1 components.\n   * @throws {CryptoError} If the message does not conform to COSE_Sign1 structure.\n   */\n  public static decode(coseSign1: Uint8Array): CoseSign1Decoded {\n    let decoded: unknown;\n    try {\n      decoded = Cbor.decode(coseSign1);\n    } catch {\n      throw new CryptoError(\n        CryptoErrorCode.InvalidCoseSign1,\n        'CoseSign1: failed to decode CBOR'\n      );\n    }\n\n    // Handle CBOR Tagged value (tag 18 for COSE_Sign1).\n    // The `cborg` library decodes tagged values as `Tagged` objects with `tag` and `value` properties.\n    if (decoded !== null && typeof decoded === 'object' && 'tag' in (decoded as Record<string, unknown>)) {\n      const tagged = decoded as { tag: number; value: unknown };\n      if (tagged.tag === 18) {\n        decoded = tagged.value;\n      }\n    }\n\n    // Validate the COSE_Sign1 array structure.\n    if (!Array.isArray(decoded) || decoded.length !== 4) {\n      throw new CryptoError(\n        CryptoErrorCode.InvalidCoseSign1,\n        'CoseSign1: expected a CBOR array of 4 elements [protected, unprotected, payload, signature]'\n      );\n    }\n\n    const [protectedHeaderBytes, unprotectedHeaderMap, payload, signature] = decoded as [\n      Uint8Array, Map<number, unknown>, Uint8Array | null, Uint8Array\n    ];\n\n    // Validate element types.\n    if (!(protectedHeaderBytes instanceof Uint8Array)) {\n      throw new CryptoError(\n        CryptoErrorCode.InvalidCoseSign1,\n        'CoseSign1: protected header must be a byte string'\n      );\n    }\n\n    if (!(signature instanceof Uint8Array)) {\n      throw new CryptoError(\n        CryptoErrorCode.InvalidCoseSign1,\n        'CoseSign1: signature must be a byte string'\n      );\n    }\n\n    // Decode the protected header.\n    let protectedHeaderMap: Map<number, unknown>;\n    if (protectedHeaderBytes.length === 0) {\n      protectedHeaderMap = new Map();\n    } else {\n      try {\n        protectedHeaderMap = Cbor.decode<Map<number, unknown>>(protectedHeaderBytes);\n      } catch {\n        throw new CryptoError(\n          CryptoErrorCode.InvalidCoseSign1,\n          'CoseSign1: failed to decode protected header CBOR'\n        );\n      }\n    }\n\n    // Extract the algorithm from the protected header.\n    const alg = protectedHeaderMap.get(CoseHeaderLabel.Alg);\n    if (alg === undefined || typeof alg !== 'number') {\n      throw new CryptoError(\n        CryptoErrorCode.InvalidCoseSign1,\n        'CoseSign1: protected header must contain an algorithm identifier (label 1)'\n      );\n    }\n\n    // Build the typed protected header.\n    const protectedHeader: CoseSign1ProtectedHeader = { alg: alg as CoseAlgorithm };\n\n    const contentType = protectedHeaderMap.get(CoseHeaderLabel.ContentType);\n    if (contentType !== undefined) {\n      protectedHeader.contentType = contentType as string | number;\n    }\n\n    const kid = protectedHeaderMap.get(CoseHeaderLabel.Kid);\n    if (kid !== undefined) {\n      protectedHeader.kid = kid as Uint8Array;\n    }\n\n    return {\n      protectedHeader,\n      protectedHeaderBytes,\n      unprotectedHeader : unprotectedHeaderMap instanceof Map ? unprotectedHeaderMap : new Map(),\n      payload           : payload instanceof Uint8Array ? payload : null,\n      signature,\n    };\n  }\n\n  /**\n   * Builds the Sig_structure1 array for COSE_Sign1 signing and verification.\n   *\n   * ```\n   * Sig_structure1 = [\n   *   context : \"Signature1\",\n   *   body_protected : bstr,\n   *   external_aad : bstr,\n   *   payload : bstr\n   * ]\n   * ```\n   *\n   * @see {@link https://www.rfc-editor.org/rfc/rfc9052#section-4.4 | RFC 9052, Section 4.4}\n   */\n  private static buildSigStructure1(\n    protectedHeaderBytes: Uint8Array,\n    externalAad: Uint8Array,\n    payload: Uint8Array,\n  ): unknown[] {\n    return [\n      'Signature1', // context string\n      protectedHeaderBytes, // body_protected\n      externalAad, // external_aad\n      payload, // payload\n    ];\n  }\n\n  /**\n   * Converts a {@link CoseSign1ProtectedHeader} to a CBOR Map with integer labels.\n   */\n  private static buildProtectedHeaderMap(header: CoseSign1ProtectedHeader): Map<number, unknown> {\n    const map = new Map<number, unknown>();\n\n    map.set(CoseHeaderLabel.Alg, header.alg);\n\n    if (header.contentType !== undefined) {\n      map.set(CoseHeaderLabel.ContentType, header.contentType);\n    }\n\n    if (header.kid !== undefined) {\n      map.set(CoseHeaderLabel.Kid, header.kid);\n    }\n\n    return map;\n  }\n\n  /**\n   * Converts a {@link CoseSign1UnprotectedHeader} to a CBOR Map with integer labels.\n   */\n  private static buildUnprotectedHeaderMap(header: CoseSign1UnprotectedHeader): Map<number, unknown> {\n    const map = new Map<number, unknown>();\n\n    if (header.kid !== undefined) {\n      map.set(CoseHeaderLabel.Kid, header.kid);\n    }\n\n    return map;\n  }\n\n  /**\n   * Signs the to-be-signed bytes with the appropriate algorithm.\n   */\n  private static async signBytes(\n    alg: CoseAlgorithm,\n    key: Jwk,\n    data: Uint8Array,\n  ): Promise<Uint8Array> {\n    switch (alg) {\n      case CoseAlgorithm.EdDSA:\n        return Ed25519.sign({ key, data });\n\n      case CoseAlgorithm.ES256:\n        return Secp256r1.sign({ key, data });\n\n      default:\n        throw new CryptoError(\n          CryptoErrorCode.AlgorithmNotSupported,\n          `CoseSign1: signing algorithm ${alg} is not supported`\n        );\n    }\n  }\n\n  /**\n   * Verifies a signature over the to-be-signed bytes with the appropriate algorithm.\n   */\n  private static async verifyBytes(\n    alg: CoseAlgorithm,\n    key: Jwk,\n    data: Uint8Array,\n    signature: Uint8Array,\n  ): Promise<boolean> {\n    switch (alg) {\n      case CoseAlgorithm.EdDSA:\n        return Ed25519.verify({ key, signature, data });\n\n      case CoseAlgorithm.ES256:\n        return Secp256r1.verify({ key, signature, data });\n\n      default:\n        throw new CryptoError(\n          CryptoErrorCode.AlgorithmNotSupported,\n          `CoseSign1: verification algorithm ${alg} is not supported`\n        );\n    }\n  }\n}\n", "import type { CoseSign1ProtectedHeader } from './cose-sign1.js';\nimport type { Jwk } from '../jose/jwk.js';\n\nimport { Cbor } from './cbor.js';\nimport { CoseSign1 } from './cose-sign1.js';\nimport { CryptoError, CryptoErrorCode } from '../crypto-error.js';\n\n/**\n * EAT (Entity Attestation Token) claim key constants.\n *\n * EAT reuses CWT registered claim keys and adds attestation-specific claims.\n *\n * @see {@link https://www.rfc-editor.org/rfc/rfc9711 | RFC 9711 \u2014 Entity Attestation Token (EAT)}\n * @see {@link https://www.rfc-editor.org/rfc/rfc8392 | RFC 8392 \u2014 CWT (CBOR Web Token)}\n */\nexport enum EatClaimKey {\n  /** Issuer (iss) \u2014 RFC 8392 */\n  Iss = 1,\n  /** Subject (sub) \u2014 RFC 8392 */\n  Sub = 2,\n  /** Audience (aud) \u2014 RFC 8392 */\n  Aud = 3,\n  /** Expiration Time (exp) \u2014 RFC 8392 */\n  Exp = 4,\n  /** Not Before (nbf) \u2014 RFC 8392 */\n  Nbf = 5,\n  /** Issued At (iat) \u2014 RFC 8392 */\n  Iat = 6,\n  /** CWT ID (cti) \u2014 RFC 8392 */\n  Cti = 7,\n  /** Nonce (eat_nonce) \u2014 RFC 9711, Section 4.1 */\n  Nonce = 10,\n  /** UEID (Universal Entity ID) \u2014 RFC 9711, Section 4.2.1 */\n  Ueid = 256,\n  /** SUEIDs (Semi-permanent UEIDs) \u2014 RFC 9711, Section 4.2.2 */\n  Sueids = 257,\n  /** OEM ID (Hardware OEM Identification) \u2014 RFC 9711, Section 4.2.3 */\n  Oemid = 258,\n  /** Hardware Model \u2014 RFC 9711, Section 4.2.4 */\n  Hwmodel = 259,\n  /** Hardware Version \u2014 RFC 9711, Section 4.2.5 */\n  Hwversion = 260,\n  /** Secure Boot \u2014 RFC 9711, Section 4.2.7 */\n  Secboot = 262,\n  /** Debug Status \u2014 RFC 9711, Section 4.2.8 */\n  Dbgstat = 263,\n  /** Location \u2014 RFC 9711, Section 4.2.9 */\n  Location = 264,\n  /** Profile \u2014 RFC 9711, Section 4.2.10 */\n  Profile = 265,\n  /** Submods (Submodules) \u2014 RFC 9711, Section 4.2.18 */\n  Submods = 266,\n  /** Measurement Results \u2014 RFC 9711, Section 4.2.15 */\n  Measres = 272,\n  /** Intended Use \u2014 RFC 9711, Section 4.2.14 */\n  Intuse = 268,\n}\n\n/**\n * Debug status values for the `dbgstat` claim.\n *\n * @see {@link https://www.rfc-editor.org/rfc/rfc9711#section-4.2.8 | RFC 9711, Section 4.2.8}\n */\nexport enum EatDebugStatus {\n  /** Debug is enabled */\n  Enabled = 0,\n  /** Debug is disabled */\n  Disabled = 1,\n  /** Debug is disabled since manufacture */\n  DisabledSinceBoot = 2,\n  /** Debug is disabled permanently */\n  DisabledPermanently = 3,\n  /** Debug is disabled fully and permanently */\n  DisabledFullyAndPermanently = 4,\n}\n\n/**\n * Security level for the `seclevel` claim.\n *\n * @see {@link https://www.rfc-editor.org/rfc/rfc9711#section-4.2.6 | RFC 9711, Section 4.2.6}\n */\nexport enum EatSecurityLevel {\n  /** Unrestricted \u2014 no security guarantees */\n  Unrestricted = 1,\n  /** Restricted \u2014 some restrictions on environment */\n  Restricted = 2,\n  /** Secure Restricted \u2014 hardware-enforced restrictions */\n  SecureRestricted = 3,\n  /** Hardware \u2014 hardware-isolated execution environment */\n  Hardware = 4,\n}\n\n/**\n * Parsed EAT claims, providing typed access to standard and attestation-specific claims.\n *\n * All fields are optional because EAT does not mandate any specific claims; the\n * required set depends on the attestation profile.\n *\n * @see {@link https://www.rfc-editor.org/rfc/rfc9711 | RFC 9711}\n */\nexport interface EatClaims {\n  /** Issuer \u2014 identifies the entity that issued the token. */\n  iss?: string;\n\n  /** Subject \u2014 identifies the entity that is the subject of the token. */\n  sub?: string;\n\n  /** Audience \u2014 identifies the intended recipient(s). */\n  aud?: string;\n\n  /** Expiration time (seconds since epoch). */\n  exp?: number;\n\n  /** Not Before (seconds since epoch). */\n  nbf?: number;\n\n  /** Issued At (seconds since epoch). */\n  iat?: number;\n\n  /** CWT ID \u2014 unique token identifier (byte string). */\n  cti?: Uint8Array;\n\n  /** Nonce \u2014 challenge value binding the token to a request. */\n  nonce?: Uint8Array | Uint8Array[];\n\n  /** Universal Entity ID. */\n  ueid?: Uint8Array;\n\n  /** Hardware model identifier. */\n  hwmodel?: Uint8Array;\n\n  /** Hardware version. */\n  hwversion?: unknown;\n\n  /** Debug status. */\n  dbgstat?: EatDebugStatus;\n\n  /** Measurement results \u2014 software component measurements. */\n  measres?: unknown;\n\n  /** Submodules \u2014 nested EAT tokens or claims from sub-components. */\n  submods?: Map<string, unknown>;\n\n  /**\n   * All raw claims as a Map for access to non-standard or profile-specific claims.\n   * Integer keys correspond to {@link EatClaimKey} values.\n   */\n  rawClaims: Map<number | string, unknown>;\n}\n\n/**\n * Parameters for decoding an EAT token.\n */\nexport interface EatDecodeParams {\n  /** The CBOR-encoded EAT token (COSE_Sign1 envelope). */\n  token: Uint8Array;\n}\n\n/**\n * Parameters for verifying and decoding an EAT token.\n */\nexport interface EatVerifyParams {\n  /** The CBOR-encoded EAT token (COSE_Sign1 envelope). */\n  token: Uint8Array;\n\n  /** The public key for signature verification, in JWK format. */\n  key: Jwk;\n\n  /** External additional authenticated data. Defaults to empty bytes. */\n  externalAad?: Uint8Array;\n}\n\n/**\n * Result of decoding an EAT token.\n */\nexport interface EatDecodeResult {\n  /** The parsed protected header from the COSE_Sign1 envelope. */\n  protectedHeader: CoseSign1ProtectedHeader;\n\n  /** The parsed EAT claims from the payload. */\n  claims: EatClaims;\n}\n\n/**\n * Entity Attestation Token (EAT) implementation per RFC 9711.\n *\n * EATs are CBOR-based attestation tokens carried in COSE_Sign1 envelopes.\n * They are used by TEE platforms (ARM CCA, Intel TDX, AMD SEV-SNP, Nitro Enclaves)\n * to provide hardware-rooted attestation evidence.\n *\n * This implementation focuses on decoding and verification of EAT tokens \u2014 the\n * primary use case for a DWN node that needs to verify TEE attestation from\n * compute modules.\n *\n * @see {@link https://www.rfc-editor.org/rfc/rfc9711 | RFC 9711 \u2014 Entity Attestation Token (EAT)}\n */\nexport class Eat {\n  /**\n   * Decodes an EAT token without verifying its signature.\n   *\n   * Use this method only when signature verification is performed separately\n   * (e.g., by a TEE attestation service) or for debugging/inspection.\n   *\n   * @param params - The parameters for decoding.\n   * @returns The decoded protected header and claims.\n   * @throws {CryptoError} If the token is not valid COSE_Sign1 or the payload is not valid CBOR.\n   */\n  public static decode({ token }: EatDecodeParams): EatDecodeResult {\n    // Decode the COSE_Sign1 envelope.\n    const coseSign1 = CoseSign1.decode(token);\n\n    if (coseSign1.payload === null) {\n      throw new CryptoError(\n        CryptoErrorCode.InvalidEat,\n        'Eat: token has detached payload; use verifyAndDecode with the payload provided separately'\n      );\n    }\n\n    // Decode the CBOR payload into claims.\n    const claims = Eat.parseClaims(coseSign1.payload);\n\n    return {\n      protectedHeader: coseSign1.protectedHeader,\n      claims,\n    };\n  }\n\n  /**\n   * Verifies the signature of an EAT token and decodes its claims.\n   *\n   * This is the primary method for processing EAT tokens from TEE attestation.\n   * It verifies the COSE_Sign1 signature using the provided public key, then\n   * parses the EAT claims from the payload.\n   *\n   * @param params - The parameters for verification and decoding.\n   * @returns The decoded protected header and claims if verification succeeds.\n   * @throws {CryptoError} If verification fails or the token is malformed.\n   */\n  public static async verifyAndDecode(params: EatVerifyParams): Promise<EatDecodeResult> {\n    const { token, key, externalAad } = params;\n\n    // Verify the COSE_Sign1 signature.\n    const isValid = await CoseSign1.verify({\n      coseSign1: token,\n      key,\n      externalAad,\n    });\n\n    if (!isValid) {\n      throw new CryptoError(\n        CryptoErrorCode.InvalidEat,\n        'Eat: signature verification failed'\n      );\n    }\n\n    // Decode and return claims (signature is already verified).\n    return Eat.decode({ token });\n  }\n\n  /**\n   * Parses CBOR-encoded EAT claims into a typed {@link EatClaims} object.\n   *\n   * Handles both integer-keyed (CBOR standard) and string-keyed claims.\n   *\n   * @param payload - The CBOR-encoded claims byte string.\n   * @returns The parsed EAT claims.\n   * @throws {CryptoError} If the payload is not valid CBOR or not a map.\n   */\n  private static parseClaims(payload: Uint8Array): EatClaims {\n    let rawClaims: Map<number | string, unknown>;\n\n    try {\n      const decoded = Cbor.decode<unknown>(payload);\n      if (decoded instanceof Map) {\n        rawClaims = decoded as Map<number | string, unknown>;\n      } else if (typeof decoded === 'object' && decoded !== null) {\n        // Some encoders produce plain objects instead of Maps for maps with string keys.\n        rawClaims = new Map(Object.entries(decoded));\n      } else {\n        throw new Error('not a map');\n      }\n    } catch (error) {\n      if (error instanceof CryptoError) {\n        throw error;\n      }\n      throw new CryptoError(\n        CryptoErrorCode.InvalidEat,\n        'Eat: payload is not a valid CBOR map'\n      );\n    }\n\n    const claims: EatClaims = { rawClaims };\n\n    // Extract standard CWT claims.\n    const iss = rawClaims.get(EatClaimKey.Iss);\n    if (iss !== undefined) {\n      claims.iss = iss as string;\n    }\n\n    const sub = rawClaims.get(EatClaimKey.Sub);\n    if (sub !== undefined) {\n      claims.sub = sub as string;\n    }\n\n    const aud = rawClaims.get(EatClaimKey.Aud);\n    if (aud !== undefined) {\n      claims.aud = aud as string;\n    }\n\n    const exp = rawClaims.get(EatClaimKey.Exp);\n    if (exp !== undefined) {\n      claims.exp = exp as number;\n    }\n\n    const nbf = rawClaims.get(EatClaimKey.Nbf);\n    if (nbf !== undefined) {\n      claims.nbf = nbf as number;\n    }\n\n    const iat = rawClaims.get(EatClaimKey.Iat);\n    if (iat !== undefined) {\n      claims.iat = iat as number;\n    }\n\n    const cti = rawClaims.get(EatClaimKey.Cti);\n    if (cti !== undefined) {\n      claims.cti = cti as Uint8Array;\n    }\n\n    // Extract EAT-specific claims.\n    const nonce = rawClaims.get(EatClaimKey.Nonce);\n    if (nonce !== undefined) {\n      claims.nonce = nonce as Uint8Array | Uint8Array[];\n    }\n\n    const ueid = rawClaims.get(EatClaimKey.Ueid);\n    if (ueid !== undefined) {\n      claims.ueid = ueid as Uint8Array;\n    }\n\n    const hwmodel = rawClaims.get(EatClaimKey.Hwmodel);\n    if (hwmodel !== undefined) {\n      claims.hwmodel = hwmodel as Uint8Array;\n    }\n\n    const hwversion = rawClaims.get(EatClaimKey.Hwversion);\n    if (hwversion !== undefined) {\n      claims.hwversion = hwversion;\n    }\n\n    const dbgstat = rawClaims.get(EatClaimKey.Dbgstat);\n    if (dbgstat !== undefined) {\n      claims.dbgstat = dbgstat as EatDebugStatus;\n    }\n\n    const measres = rawClaims.get(EatClaimKey.Measres);\n    if (measres !== undefined) {\n      claims.measres = measres;\n    }\n\n    const submods = rawClaims.get(EatClaimKey.Submods);\n    if (submods !== undefined) {\n      claims.submods = submods as Map<string, unknown>;\n    }\n\n    return claims;\n  }\n}\n", "import { Convert } from '@enbox/common';\n\nimport type { Jwk } from '../jose/jwk.js';\n\nimport { getWebcryptoSubtle } from './webcrypto.js';\nimport { computeJwkThumbprint, isOctPrivateJwk } from '../jose/jwk.js';\n\n/**\n * Const defining the AES-GCM initialization vector (IV) length in bits.\n *\n * @remarks\n * NIST Special Publication 800-38D, Section 5.2.1.1 states that the IV length:\n * > For IVs, it is recommended that implementations restrict support to the length of 96 bits, to\n * > promote interoperability, efficiency, and simplicity of design.\n *\n * This implementation does not support IV lengths that are different from the value defined by\n * this constant.\n *\n * @see {@link https://doi.org/10.6028/NIST.SP.800-38D | NIST SP 800-38D}\n */\nconst AES_GCM_IV_LENGTH = 96;\n\n/**\n * Constant defining the AES key length values in bits.\n *\n * @remarks\n * NIST publication FIPS 197 states:\n * > The AES algorithm is capable of using cryptographic keys of 128, 192, and 256 bits to encrypt\n * > and decrypt data in blocks of 128 bits.\n *\n * This implementation does not support key lengths that are different from the three values\n * defined by this constant.\n *\n * @see {@link https://doi.org/10.6028/NIST.FIPS.197-upd1 | NIST FIPS 197}\n */\nconst AES_KEY_LENGTHS = [128, 192, 256] as const;\n\n/**\n * Constant defining the AES-GCM tag length values in bits.\n *\n * @remarks\n * NIST Special Publication 800-38D, Section 5.2.1.2 states that the tag length:\n * > may be any one of the following five values: 128, 120, 112, 104, or 96\n *\n * Although the NIST specification allows for tag lengths of 32 or 64 bits in certain applications,\n * the use of shorter tag lengths can be problematic for GCM due to targeted forgery attacks. As a\n * precaution, this implementation does not support tag lengths that are different from the five\n * values defined by this constant. See Appendix C of the NIST SP 800-38D specification for\n * additional guidance and details.\n *\n * @see {@link https://doi.org/10.6028/NIST.SP.800-38D | NIST SP 800-38D}\n */\nexport const AES_GCM_TAG_LENGTHS = [96, 104, 112, 120, 128] as const;\n\n/**\n * The `AesGcm` class provides a comprehensive set of utilities for cryptographic operations\n * using the Advanced Encryption Standard (AES) in Galois/Counter Mode (GCM). This class includes\n * methods for key generation, encryption, decryption, and conversions between raw byte arrays\n * and JSON Web Key (JWK) formats. It is designed to support AES-GCM, a symmetric key algorithm\n * that is widely used for its efficiency, security, and provision of authenticated encryption.\n *\n * AES-GCM is particularly favored for scenarios that require both confidentiality and integrity\n * of data. It integrates the counter mode of encryption with the Galois mode of authentication,\n * offering high performance and parallel processing capabilities.\n *\n * Key Features:\n * - Key Generation: Generate AES symmetric keys in JWK format.\n * - Key Conversion: Transform keys between raw byte arrays and JWK formats.\n * - Encryption: Encrypt data using AES-GCM with the provided symmetric key.\n * - Decryption: Decrypt data encrypted with AES-GCM using the corresponding symmetric key.\n *\n * The methods in this class are asynchronous, returning Promises to accommodate various\n * JavaScript environments.\n *\n * @example\n * ```ts\n * // Key Generation\n * const length = 256; // Length of the key in bits (e.g., 128, 192, 256)\n * const privateKey = await AesGcm.generateKey({ length });\n *\n * // Encryption\n * const data = new TextEncoder().encode('Messsage');\n * const iv = new Uint8Array(12); // 12-byte initialization vector\n * const encryptedData = await AesGcm.encrypt({\n *   data,\n *   iv,\n *   key: privateKey\n * });\n *\n * // Decryption\n * const decryptedData = await AesGcm.decrypt({\n *   data: encryptedData,\n *   iv,\n *   key: privateKey\n * });\n *\n * // Key Conversion\n * const privateKeyBytes = await AesGcm.privateKeyToBytes({ privateKey });\n * ```\n */\nexport class AesGcm {\n  /**\n * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method accepts a symmetric key represented as a byte array (Uint8Array) and\n * converts it into a JWK object for use with AES-GCM (Advanced Encryption Standard -\n * Galois/Counter Mode). The conversion process involves encoding the key into\n * base64url format and setting the appropriate JWK parameters.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'oct' for Octet Sequence (representing a symmetric key).\n * - `k`: The symmetric key, base64url-encoded.\n * - `kid`: Key ID, generated based on the JWK thumbprint.\n *\n * @example\n * ```ts\n * const privateKeyBytes = new Uint8Array([...]); // Replace with actual symmetric key bytes\n * const privateKey = await AesGcm.bytesToPrivateKey({ privateKeyBytes });\n * ```\n *\n * @param params - The parameters for the symmetric key conversion.\n * @param params.privateKeyBytes - The raw symmetric key as a Uint8Array.\n *\n * @returns A Promise that resolves to the symmetric key in JWK format.\n */\n  public static async bytesToPrivateKey({ privateKeyBytes }: {\n    privateKeyBytes: Uint8Array;\n  }): Promise<Jwk> {\n    // Construct the private key in JWK format.\n    const privateKey: Jwk = {\n      k   : Convert.uint8Array(privateKeyBytes).toBase64Url(),\n      kty : 'oct'\n    };\n\n    // Compute the JWK thumbprint and set as the key ID.\n    privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n    return privateKey;\n  }\n\n  /**\n   * Decrypts the provided data using AES-GCM.\n   *\n   * @remarks\n   * This method performs AES-GCM decryption on the given encrypted data using the specified key.\n   * It requires an initialization vector (IV), the encrypted data along with the decryption key,\n   * and optionally, additional authenticated data (AAD). The method returns the decrypted data as a\n   * Uint8Array. The optional `tagLength` parameter specifies the size in bits of the authentication\n   * tag used when encrypting the data. If not specified, the default tag length of 128 bits is\n   * used.\n   *\n   * @example\n   * ```ts\n   * const encryptedData = new Uint8Array([...]); // Encrypted data\n   * const iv = new Uint8Array([...]); // Initialization vector used during encryption\n   * const additionalData = new Uint8Array([...]); // Optional additional authenticated data\n   * const key = { ... }; // A Jwk object representing the AES key\n   * const decryptedData = await AesGcm.decrypt({\n   *   data: encryptedData,\n   *   iv,\n   *   additionalData,\n   *   key,\n   *   tagLength: 128 // Optional tag length in bits\n   * });\n   * ```\n   *\n   * @param params - The parameters for the decryption operation.\n   * @param params.key - The key to use for decryption, represented in JWK format.\n   * @param params.data - The encrypted data to decrypt, represented as a Uint8Array.\n   * @param params.iv - The initialization vector, represented as a Uint8Array.\n   * @param params.additionalData - Optional additional authenticated data. Optional.\n   * @param params.tagLength - The length of the authentication tag in bits. Optional.\n   *\n   * @returns A Promise that resolves to the decrypted data as a Uint8Array.\n   */\n  public static async decrypt({ key, data, iv, additionalData, tagLength }: {\n    key: Jwk;\n    data: Uint8Array;\n    iv: Uint8Array;\n    additionalData?: Uint8Array;\n    tagLength?: typeof AES_GCM_TAG_LENGTHS[number];\n  }): Promise<Uint8Array> {\n    // Validate the initialization vector length.\n    if (iv.byteLength !== AES_GCM_IV_LENGTH / 8) {\n      throw new TypeError(`The initialization vector must be ${AES_GCM_IV_LENGTH} bits in length`);\n    }\n\n    // Validate the tag length.\n    if (tagLength && !(AES_GCM_TAG_LENGTHS as readonly number[]).includes(tagLength)) {\n      throw new RangeError(`The tag length is invalid: Must be ${AES_GCM_TAG_LENGTHS.join(', ')} bits`);\n    }\n\n    // Get the Web Crypto API interface.\n    const webCrypto = getWebcryptoSubtle();\n\n    // Import the JWK into the Web Crypto API to use for the decrypt operation.\n    const webCryptoKey = await webCrypto.importKey('jwk', key, { name: 'AES-GCM' }, true, ['decrypt']);\n\n    // Note: Some browser implementations of the Web Crypto API throw an error if additionalData or\n    // tagLength are undefined, so only include them in the algorithm object if they are defined.\n    const algorithm = {\n      name: 'AES-GCM',\n      iv,\n      ...(tagLength && { tagLength }),\n      ...(additionalData && { additionalData })\n    };\n\n    // Decrypt the data.\n    const plaintextBuffer = await webCrypto.decrypt(algorithm, webCryptoKey, data);\n\n    // Convert from ArrayBuffer to Uint8Array.\n    const plaintext = new Uint8Array(plaintextBuffer);\n\n    return plaintext;\n  }\n\n  /**\n   * Encrypts the provided data using AES-GCM.\n   *\n   * @remarks\n   * This method performs AES-GCM encryption on the given data using the specified key.\n   * It requires an initialization vector (IV), the encrypted data along with the decryption key,\n   * and optionally, additional authenticated data (AAD). The method returns the encrypted data as a\n   * Uint8Array. The optional `tagLength` parameter specifies the size in bits of the authentication\n   * tag generated in the encryption operation and used for authentication in the corresponding\n   * decryption. If not specified, the default tag length of 128 bits is used.\n   *\n   * @example\n   * ```ts\n   * const data = new TextEncoder().encode('Messsage');\n   * const iv = new Uint8Array([...]); // Initialization vector\n   * const additionalData = new Uint8Array([...]); // Optional additional authenticated data\n   * const key = { ... }; // A Jwk object representing an AES key\n   * const encryptedData = await AesGcm.encrypt({\n   *   data,\n   *   iv,\n   *   additionalData,\n   *   key,\n   *   tagLength: 128 // Optional tag length in bits\n   * });\n   * ```\n   *\n   * @param params - The parameters for the encryption operation.\n   * @param params.key - The key to use for encryption, represented in JWK format.\n   * @param params.data - The data to encrypt, represented as a Uint8Array.\n   * @param params.iv - The initialization vector, represented as a Uint8Array.\n   * @param params.additionalData - Optional additional authenticated data. Optional.\n   * @param params.tagLength - The length of the authentication tag in bits. Optional.\n   *\n   * @returns A Promise that resolves to the encrypted data as a Uint8Array.\n   */\n  public static async encrypt({ data, iv, key, additionalData, tagLength }: {\n    key: Jwk;\n    data: Uint8Array;\n    iv: Uint8Array;\n    additionalData?: Uint8Array;\n    tagLength?: typeof AES_GCM_TAG_LENGTHS[number];\n  }): Promise<Uint8Array> {\n    // Validate the initialization vector length.\n    if (iv.byteLength !== AES_GCM_IV_LENGTH / 8) {\n      throw new TypeError(`The initialization vector must be ${AES_GCM_IV_LENGTH} bits in length`);\n    }\n\n    // Validate the tag length.\n    if (tagLength && !(AES_GCM_TAG_LENGTHS as readonly number[]).includes(tagLength)) {\n      throw new RangeError(`The tag length is invalid: Must be ${AES_GCM_TAG_LENGTHS.join(', ')} bits`);\n    }\n\n    // Get the Web Crypto API interface.\n    const webCrypto = getWebcryptoSubtle();\n\n    // Import the JWK into the Web Crypto API to use for the encrypt operation.\n    const webCryptoKey = await webCrypto.importKey('jwk', key, { name: 'AES-GCM' }, true, ['encrypt']);\n\n    // Note: Some browser implementations of the Web Crypto API throw an error if additionalData or\n    // tagLength are undefined, so only include them in the algorithm object if they are defined.\n    const algorithm = {\n      name: 'AES-GCM',\n      iv,\n      ...(tagLength && { tagLength }),\n      ...(additionalData && { additionalData })\n    };\n\n    // Encrypt the data.\n    const ciphertextBuffer = await webCrypto.encrypt(algorithm, webCryptoKey, data);\n\n    // Convert from ArrayBuffer to Uint8Array.\n    const ciphertext = new Uint8Array(ciphertextBuffer);\n\n    return ciphertext;\n  }\n\n  /**\n   * Generates a symmetric key for AES in Galois/Counter Mode (GCM) in JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method creates a new symmetric key of a specified length suitable for use with\n   * AES-GCM encryption. It leverages cryptographically secure random number generation\n   * to ensure the uniqueness and security of the key. The generated key adheres to the JWK\n   * format, facilitating compatibility with common cryptographic standards and ease of use\n   * in various cryptographic applications.\n   *\n   * The generated key includes these components:\n   * - `kty`: Key Type, set to 'oct' for Octet Sequence, indicating a symmetric key.\n   * - `k`: The symmetric key component, base64url-encoded.\n   * - `kid`: Key ID, generated based on the JWK thumbprint, providing a unique identifier.\n   *\n   * @example\n   * ```ts\n   * const length = 256; // Length of the key in bits (e.g., 128, 192, 256)\n   * const privateKey = await AesGcm.generateKey({ length });\n   * ```\n   *\n   * @param params - The parameters for the key generation.\n   * @param params.length - The length of the key in bits. Common lengths are 128, 192, and 256 bits.\n   *\n   * @returns A Promise that resolves to the generated symmetric key in JWK format.\n   */\n  public static async generateKey({ length }: {\n    length: typeof AES_KEY_LENGTHS[number];\n  }): Promise<Jwk> {\n    // Validate the key length.\n    if (!(AES_KEY_LENGTHS as readonly number[]).includes(length)) {\n      throw new RangeError(`The key length is invalid: Must be ${AES_KEY_LENGTHS.join(', ')} bits`);\n    }\n\n    // Get the Web Crypto API interface.\n    const webCrypto = getWebcryptoSubtle();\n\n    // Generate a random private key.\n    // See https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#usage_notes for\n    // an explanation for why Web Crypto generateKey() is used instead of getRandomValues().\n    const webCryptoKey = await webCrypto.generateKey( { name: 'AES-GCM', length }, true, ['encrypt']);\n\n    // Export the private key in JWK format.\n    const { ext, key_ops, ...privateKey } = await webCrypto.exportKey('jwk', webCryptoKey);\n\n    // Compute the JWK thumbprint and set as the key ID.\n    privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n    return privateKey;\n  }\n\n  /**\n   * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n   *\n   * @remarks\n   * This method takes a symmetric key in JWK format and extracts its raw byte representation.\n   * It focuses on the 'k' parameter of the JWK, which represents the symmetric key component\n   * in base64url encoding. The method decodes this value into a byte array, providing\n   * the symmetric key in its raw binary form.\n   *\n   * @example\n   * ```ts\n   * const privateKey = { ... }; // A symmetric key in JWK format\n   * const privateKeyBytes = await AesGcm.privateKeyToBytes({ privateKey });\n   * ```\n   *\n   * @param params - The parameters for the symmetric key conversion.\n   * @param params.privateKey - The symmetric key in JWK format.\n   *\n   * @returns A Promise that resolves to the symmetric key as a Uint8Array.\n   */\n  public static async privateKeyToBytes({ privateKey }: {\n    privateKey: Jwk;\n  }): Promise<Uint8Array> {\n    // Verify the provided JWK represents a valid oct private key.\n    if (!isOctPrivateJwk(privateKey)) {\n      throw new Error(`AesGcm: The provided key is not a valid oct private key.`);\n    }\n\n    // Decode the provided private key to bytes.\n    const privateKeyBytes = Convert.base64Url(privateKey.k).toUint8Array();\n\n    return privateKeyBytes;\n  }\n}\n", "import type { AES_GCM_TAG_LENGTHS } from '../primitives/aes-gcm.js';\nimport type { Cipher } from '../types/cipher.js';\nimport type { Jwk } from '../jose/jwk.js';\nimport type { KeyConverter } from '../types/key-converter.js';\nimport type { KeyGenerator } from '../types/key-generator.js';\nimport type { BytesToPrivateKeyParams, DecryptParams, EncryptParams, GenerateKeyParams, PrivateKeyToBytesParams } from '../types/params-direct.js';\n\nimport { AesGcm } from '../primitives/aes-gcm.js';\nimport { CryptoAlgorithm } from './crypto-algorithm.js';\n\n/**\n * The `AesGcmGenerateKeyParams` interface defines the algorithm-specific parameters that should be\n * passed into the `generateKey()` method when using the AES-GCM algorithm.\n */\nexport interface AesGcmGenerateKeyParams extends GenerateKeyParams {\n  /** Specifies the algorithm variant for key generation in AES-GCM mode.\n   * The value determines the length of the key to be generated and must be one of the following:\n   * - `\"A128GCM\"`: Generates a 128-bit key.\n   * - `\"A192GCM\"`: Generates a 192-bit key.\n   * - `\"A256GCM\"`: Generates a 256-bit key.\n   */\n  algorithm: 'A128GCM' | 'A192GCM' | 'A256GCM';\n}\n\n/**\n * The `AesGcmParams` interface defines the algorithm-specific parameters that should be passed\n * into the `encrypt()` and `decrypt()` methods when using the AES-GCM algorithm.\n */\nexport interface AesGcmParams {\n  /**\n   * The `additionalData` property is used for authentication alongside encrypted data but isn't\n   * encrypted itself. It must match in both encryption and decryption; a mismatch will cause\n   * decryption to fail. This feature allows for the authentication of data without encrypting it.\n   *\n   * The `additionalData` property is optional and omitting it does not compromise encryption\n   * security.\n   */\n  additionalData?: Uint8Array;\n\n  /**\n   * The initialization vector (IV) must be unique for every encryption operation carried out with a\n   * given key. The IV need not be secret, but it must be unpredictable: that is, the IV must not be\n   * reused with the same key. The IV must be 12 bytes (96 bits) in length in accordance with the\n   * AES-GCM specification recommendedation to promote interoperability and efficiency.\n   *\n   * Note: It is OK to transmit the IV in the clear with the encrypted message.\n   */\n  iv: Uint8Array;\n\n  /**\n   * This property determines the size in bits of the authentication tag generated in the encryption\n   * operation and used for authentication in the corresponding decryption. In accordance with the\n   * AES-GCM specification, the tag length must be 96, 104, 112, 120 or 128.\n   *\n   * The `tagLength` property is optional and defaults to 128 bits if omitted.\n   */\n  tagLength?: typeof AES_GCM_TAG_LENGTHS[number];\n}\n\n/**\n * The `AesGcmAlgorithm` class provides a concrete implementation for cryptographic operations using\n * the AES algorithm in Galois/Counter Mode (GCM). This class implements both\n * {@link Cipher | `Cipher`} and { @link KeyGenerator | `KeyGenerator`} interfaces, providing\n * key generation, encryption, and decryption features.\n *\n * This class is typically accessed through implementations that extend the\n * {@link DsaApi | `DsaApi`} interface.\n */\nexport class AesGcmAlgorithm extends CryptoAlgorithm\n  implements Cipher<AesGcmParams, AesGcmParams>,\n             KeyConverter,\n             KeyGenerator<AesGcmGenerateKeyParams, Jwk> {\n\n  /**\n   * Converts a private key from a byte array to JWK format, setting the `alg` property based on\n   * the key length.\n   *\n   * @param params - The parameters for the private key conversion.\n   * @param params.privateKeyBytes - The raw private key as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the private key in JWK format.\n   */\n  public async bytesToPrivateKey({ privateKeyBytes }: BytesToPrivateKeyParams): Promise<Jwk> {\n    // Convert the byte array to a JWK.\n    const privateKey = await AesGcm.bytesToPrivateKey({ privateKeyBytes });\n\n    // Set the `alg` property based on the key length.\n    privateKey.alg = { 16: 'A128GCM', 24: 'A192GCM', 32: 'A256GCM' }[privateKeyBytes.length];\n\n    return privateKey;\n  }\n\n  /**\n   * Decrypts the provided data using AES-GCM.\n   *\n   * @remarks\n   * This method performs AES-GCM decryption on the given encrypted data using the specified key.\n   * It requires an initialization vector (IV), the encrypted data along with the decryption key,\n   * and optionally, additional authenticated data (AAD). The method returns the decrypted data as a\n   * Uint8Array. The optional `tagLength` parameter specifies the size in bits of the authentication\n   * tag used when encrypting the data. If not specified, the default tag length of 128 bits is\n   * used.\n   *\n   * @example\n   * ```ts\n   * const aesGcm = new AesGcmAlgorithm();\n   * const encryptedData = new Uint8Array([...]); // Encrypted data\n   * const iv = new Uint8Array([...]); // Initialization vector used during encryption\n   * const additionalData = new Uint8Array([...]); // Optional additional authenticated data\n   * const key = { ... }; // A Jwk object representing the AES key\n   * const decryptedData = await aesGcm.decrypt({\n   *   data: encryptedData,\n   *   iv,\n   *   additionalData,\n   *   key,\n   *   tagLength: 128 // Optional tag length in bits\n   * });\n   * ```\n   *\n   * @param params - The parameters for the decryption operation.\n   *\n   * @returns A Promise that resolves to the decrypted data as a Uint8Array.\n   */\n  public async decrypt(params:\n    DecryptParams & AesGcmParams\n  ): Promise<Uint8Array> {\n    const plaintext = AesGcm.decrypt(params);\n\n    return plaintext;\n  }\n\n  /**\n   * Encrypts the provided data using AES-GCM.\n   *\n   * @remarks\n   * This method performs AES-GCM encryption on the given data using the specified key.\n   * It requires an initialization vector (IV), the encrypted data along with the decryption key,\n   * and optionally, additional authenticated data (AAD). The method returns the encrypted data as a\n   * Uint8Array. The optional `tagLength` parameter specifies the size in bits of the authentication\n   * tag generated in the encryption operation and used for authentication in the corresponding\n   * decryption. If not specified, the default tag length of 128 bits is used.\n   *\n   * @example\n   * ```ts\n   * const aesGcm = new AesGcmAlgorithm();\n   * const data = new TextEncoder().encode('Messsage');\n   * const iv = new Uint8Array([...]); // Initialization vector\n   * const additionalData = new Uint8Array([...]); // Optional additional authenticated data\n   * const key = { ... }; // A Jwk object representing an AES key\n   * const encryptedData = await aesGcm.encrypt({\n   *   data,\n   *   iv,\n   *   additionalData,\n   *   key,\n   *   tagLength: 128 // Optional tag length in bits\n   * });\n   * ```\n   *\n   * @param params - The parameters for the encryption operation.\n   *\n   * @returns A Promise that resolves to the encrypted data as a Uint8Array.\n   */\n  public async encrypt(params:\n    EncryptParams & AesGcmParams\n  ): Promise<Uint8Array> {\n    const ciphertext = AesGcm.encrypt(params);\n\n    return ciphertext;\n  }\n\n  /**\n   * Generates a symmetric key for AES in Galois/Counter Mode (GCM) in JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method generates a symmetric AES key for use in GCM mode, based on the specified\n   * `algorithm` parameter which determines the key length. It uses cryptographically secure random\n   * number generation to ensure the uniqueness and security of the key. The key is returned in JWK\n   * format.\n   *\n   * The generated key includes the following components:\n   * - `kty`: Key Type, set to 'oct' for Octet Sequence.\n   * - `k`: The symmetric key component, base64url-encoded.\n   * - `kid`: Key ID, generated based on the JWK thumbprint.\n   *\n   * @example\n   * ```ts\n   * const aesGcm = new AesGcmAlgorithm();\n   * const privateKey = await aesGcm.generateKey({ algorithm: 'A256GCM' });\n   * ```\n   *\n   * @param params - The parameters for the key generation.\n   *\n   * @returns A Promise that resolves to the generated symmetric key in JWK format.\n   */\n  public async generateKey({ algorithm }:\n    AesGcmGenerateKeyParams\n  ): Promise<Jwk> {\n    // Map algorithm name to key length.\n    const length = { A128GCM: 128, A192GCM: 192, A256GCM: 256 }[algorithm] as 128 | 192 | 256;\n\n    // Generate a random private key.\n    const privateKey = await AesGcm.generateKey({ length });\n\n    // Set the `alg` property based on the specified algorithm.\n    privateKey.alg = algorithm;\n\n    return privateKey;\n  }\n\n  /**\n   * Converts a private key from JWK format to a byte array.\n   *\n   * @param params - The parameters for the private key conversion.\n   * @param params.privateKey - The private key in JWK format.\n   *\n   * @returns A Promise that resolves to the private key as a Uint8Array.\n   */\n  public async privateKeyToBytes({ privateKey }: PrivateKeyToBytesParams): Promise<Uint8Array> {\n    // Convert the JWK to a byte array.\n    const privateKeyBytes = await AesGcm.privateKeyToBytes({ privateKey });\n\n    return privateKeyBytes;\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 type { Jwk } from '../jose/jwk.js';\nimport type { UnwrapKeyParams, WrapKeyParams } from '../types/params-direct.js';\n\nimport { aeskw } from '@noble/ciphers/aes.js';\nimport { Convert } from '@enbox/common';\n\nimport { computeJwkThumbprint, isOctPrivateJwk } from '../jose/jwk.js';\nimport { CryptoError, CryptoErrorCode } from '../crypto-error.js';\nimport { getWebcrypto, getWebcryptoSubtle } from './webcrypto.js';\n\n/**\n * Constant defining the AES key length values in bits.\n *\n * @remarks\n * NIST publication FIPS 197 states:\n * > The AES algorithm is capable of using cryptographic keys of 128, 192, and 256 bits to encrypt\n * > and decrypt data in blocks of 128 bits.\n *\n * This implementation does not support key lengths that are different from the three values\n * defined by this constant.\n *\n * @see {@link https://doi.org/10.6028/NIST.FIPS.197-upd1 | NIST FIPS 197}\n */\nconst AES_KEY_LENGTHS = [128, 192, 256] as const;\n\n/**\n * Cached result of the one-time probe for Web Crypto 'AES-KW' support.\n *\n * Most runtimes support AES-KW, but Electron compiles Node against BoringSSL,\n * whose WebCrypto build drops AES key wrapping (\"Unrecognized algorithm\n * name\"). When unsupported, {@link AesKw} transparently falls back to\n * `@noble/ciphers`' RFC 3394 implementation. Every wrap/unwrap input and\n * output of this class is a plain 'oct' JWK (raw bytes in `k`), and RFC 3394\n * output is implementation-independent, so the fallback is byte-compatible\n * with native WebCrypto in both directions.\n */\nlet webCryptoAesKwSupport: Promise<boolean> | undefined;\n\nfunction hasWebCryptoAesKw(): Promise<boolean> {\n  webCryptoAesKwSupport ??= (async (): Promise<boolean> => {\n    try {\n      const webCrypto = getWebcryptoSubtle() as unknown as SubtleCrypto;\n      await webCrypto.importKey('raw', new Uint8Array(16), { name: 'AES-KW' }, false, ['wrapKey']);\n      return true;\n    } catch {\n      return false;\n    }\n  })();\n  return webCryptoAesKwSupport;\n}\n\n/**\n * Resets the cached AES-KW capability probe so the next operation re-detects.\n *\n * @internal For tests only.\n */\nexport function _resetWebCryptoAesKwDetection(): void {\n  webCryptoAesKwSupport = undefined;\n}\n\nexport class AesKw {\n  /**\n   * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method takes a symmetric key represented as a byte array (Uint8Array) and\n   * converts it into a JWK object for use with AES (Advanced Encryption Standard)\n   * for key wrapping. The conversion process involves encoding the key into\n   * base64url format and setting the appropriate JWK parameters.\n   *\n   * The resulting JWK object includes the following properties:\n   * - `kty`: Key Type, set to 'oct' for Octet Sequence (representing a symmetric key).\n   * - `k`: The symmetric key, base64url-encoded.\n   * - `kid`: Key ID, generated based on the JWK thumbprint.\n   *\n   * @example\n   * ```ts\n   * const privateKeyBytes = new Uint8Array([...]); // Replace with actual symmetric key bytes\n   * const privateKey = await AesKw.bytesToPrivateKey({ privateKeyBytes });\n   * ```\n   *\n   * @param params - The parameters for the symmetric key conversion.\n   * @param params.privateKeyBytes - The raw symmetric key as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the symmetric key in JWK format.\n   */\n  public static async bytesToPrivateKey({ privateKeyBytes }: {\n    privateKeyBytes: Uint8Array;\n  }): Promise<Jwk> {\n    // Construct the private key in JWK format.\n    const privateKey: Jwk = {\n      k   : Convert.uint8Array(privateKeyBytes).toBase64Url(),\n      kty : 'oct'\n    };\n\n    // Compute the JWK thumbprint and set as the key ID.\n    privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n    // Add algorithm identifier based on key length.\n    const lengthInBits = privateKeyBytes.length * 8;\n    privateKey.alg = { 128: 'A128KW', 192: 'A192KW', 256: 'A256KW' }[lengthInBits];\n\n    return privateKey;\n  }\n\n  /**\n   * Generates a symmetric key for AES for key wrapping in JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method creates a new symmetric key of a specified length suitable for use with\n   * AES key wrapping. It uses cryptographically secure random number generation to\n   * ensure the uniqueness and security of the key. The generated key adheres to the JWK\n   * format, making it compatible with common cryptographic standards and easy to use in\n   * various cryptographic processes.\n   *\n   * The generated key includes the following components:\n   * - `kty`: Key Type, set to 'oct' for Octet Sequence.\n   * - `k`: The symmetric key component, base64url-encoded.\n   * - `kid`: Key ID, generated based on the JWK thumbprint.\n   * - `alg`: Algorithm, set to 'A128KW', 'A192KW', or 'A256KW' for AES Key Wrap with the\n   *   specified key length.\n   *\n   * @example\n   * ```ts\n   * const length = 256; // Length of the key in bits (e.g., 128, 192, 256)\n   * const privateKey = await AesKw.generateKey({ length });\n   * ```\n   *\n   * @param params - The parameters for the key generation.\n   * @param params.length - The length of the key in bits. Common lengths are 128, 192, and 256 bits.\n   *\n   * @returns A Promise that resolves to the generated symmetric key in JWK format.\n   */\n  public static async generateKey({ length }: {\n    length: typeof AES_KEY_LENGTHS[number];\n  }): Promise<Jwk> {\n    // Validate the key length.\n    if (!(AES_KEY_LENGTHS as readonly number[]).includes(length)) {\n      throw new RangeError(`The key length is invalid: Must be ${AES_KEY_LENGTHS.join(', ')} bits`);\n    }\n\n    // BoringSSL hosts (e.g. Electron) lack Web Crypto AES-KW: generate the\n    // key material directly; bytesToPrivateKey builds the identical JWK shape.\n    if (!(await hasWebCryptoAesKw())) {\n      const privateKeyBytes = new Uint8Array(length / 8);\n      getWebcrypto().getRandomValues(privateKeyBytes);\n      return AesKw.bytesToPrivateKey({ privateKeyBytes });\n    }\n\n    // Get the Web Crypto API interface.\n    const webCrypto = getWebcryptoSubtle() as unknown as SubtleCrypto;\n\n    // Generate a random private key.\n    // See https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#usage_notes for\n    // an explanation for why Web Crypto generateKey() is used instead of getRandomValues().\n    const webCryptoKey = await webCrypto.generateKey( { name: 'AES-KW', length }, true, ['wrapKey', 'unwrapKey']);\n\n    // Export the private key in JWK format.\n    const { ext, key_ops, ...privateKey } = await webCrypto.exportKey('jwk', webCryptoKey) as Jwk;\n\n    // Compute the JWK thumbprint and set as the key ID.\n    privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n    return privateKey;\n  }\n\n  /**\n   * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n   *\n   * @remarks\n   * This method takes a symmetric key in JWK format and extracts its raw byte representation.\n   * It decodes the 'k' parameter of the JWK value, which represents the symmetric key in base64url\n   * encoding, into a byte array.\n   *\n   * @example\n   * ```ts\n   * const privateKey = { ... }; // A symmetric key in JWK format\n   * const privateKeyBytes = await AesKw.privateKeyToBytes({ privateKey });\n   * ```\n   *\n   * @param params - The parameters for the symmetric key conversion.\n   * @param params.privateKey - The symmetric key in JWK format.\n   *\n   * @returns A Promise that resolves to the symmetric key as a Uint8Array.\n   */\n  public static async privateKeyToBytes({ privateKey }: {\n    privateKey: Jwk;\n  }): Promise<Uint8Array> {\n    // Verify the provided JWK represents a valid oct private key.\n    if (!isOctPrivateJwk(privateKey)) {\n      throw new Error(`AesKw: The provided key is not a valid oct private key.`);\n    }\n\n    // Decode the provided private key to bytes.\n    const privateKeyBytes = Convert.base64Url(privateKey.k).toUint8Array();\n\n    return privateKeyBytes;\n  }\n\n  public static async unwrapKey({ wrappedKeyBytes, wrappedKeyAlgorithm, decryptionKey }:\n    UnwrapKeyParams\n  ): Promise<Jwk> {\n    if (!('alg' in decryptionKey && decryptionKey.alg)) {\n      throw new CryptoError(CryptoErrorCode.InvalidJwk, `The decryption key is missing the 'alg' property.`);\n    }\n\n    if (!['A128KW', 'A192KW', 'A256KW'].includes(decryptionKey.alg)) {\n      throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `The 'decryptionKey' algorithm is not supported: ${decryptionKey.alg}`);\n    }\n\n    // Map the private key's JOSE algorithm name to the Web Crypto API algorithm identifier.\n    const webCryptoAlgorithm = {\n      A128KW  : 'AES-KW', A192KW  : 'AES-KW', A256KW  : 'AES-KW',\n      A128CTR : 'AES-CTR', A192CTR : 'AES-CTR', A256CTR : 'AES-CTR',\n      A128GCM : 'AES-GCM', A192GCM : 'AES-GCM', A256GCM : 'AES-GCM',\n    }[wrappedKeyAlgorithm];\n\n    if (!webCryptoAlgorithm) {\n      throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `The 'wrappedKeyAlgorithm' is not supported: ${wrappedKeyAlgorithm}`);\n    }\n\n    // BoringSSL hosts (e.g. Electron) lack Web Crypto AES-KW: unwrap via the\n    // RFC 3394 fallback. The result mirrors the native path's exported JWK \u2014\n    // kty/k plus an alg named for the actual key size and algorithm family,\n    // and a kid thumbprint.\n    if (!(await hasWebCryptoAesKw())) {\n      const decryptionKeyBytes = await AesKw.privateKeyToBytes({ privateKey: decryptionKey });\n      const unwrappedKeyBytes = aeskw(decryptionKeyBytes).decrypt(wrappedKeyBytes);\n\n      const algorithmFamily = wrappedKeyAlgorithm.replace(/^A\\d{3}/, '');\n      const unwrappedKey: Jwk = {\n        k   : Convert.uint8Array(unwrappedKeyBytes).toBase64Url(),\n        kty : 'oct',\n        alg : `A${unwrappedKeyBytes.length * 8}${algorithmFamily}`,\n      };\n      unwrappedKey.kid = await computeJwkThumbprint({ jwk: unwrappedKey });\n\n      return unwrappedKey;\n    }\n\n    // Get the Web Crypto API interface.\n    const webCrypto = getWebcryptoSubtle() as unknown as SubtleCrypto;\n\n    // Import the decryption key for use with the Web Crypto API.\n    const decryptionCryptoKey = await webCrypto.importKey(\n      'jwk', // key format\n      decryptionKey as JsonWebKey, // key data\n      { name: 'AES-KW' }, // algorithm identifier\n      true, // key is extractable\n      ['unwrapKey'] // key usages\n    );\n\n    // Unwrap the key using the Web Crypto API.\n    const unwrappedCryptoKey = await webCrypto.unwrapKey(\n      'raw', // output format\n      wrappedKeyBytes.buffer as ArrayBuffer, // key to unwrap\n      decryptionCryptoKey, // unwrapping key\n      'AES-KW', // algorithm identifier\n      { name: webCryptoAlgorithm }, // unwrapped key algorithm identifier\n      true, // key is extractable\n      ['unwrapKey'] // key usages\n    );\n\n    // Export the unwrapped key in JWK format.\n    const { ext, key_ops, ...unwrappedJsonWebKey } = await webCrypto.exportKey('jwk', unwrappedCryptoKey);\n    const unwrappedKey = unwrappedJsonWebKey as Jwk;\n\n    // Compute the JWK thumbprint and set as the key ID.\n    unwrappedKey.kid = await computeJwkThumbprint({ jwk: unwrappedKey });\n\n    return unwrappedKey;\n  }\n\n  public static async wrapKey({ unwrappedKey, encryptionKey }:\n    WrapKeyParams\n  ): Promise<Uint8Array> {\n    if (!('alg' in encryptionKey && encryptionKey.alg)) {\n      throw new CryptoError(CryptoErrorCode.InvalidJwk, `The encryption key is missing the 'alg' property.`);\n    }\n\n    if (!['A128KW', 'A192KW', 'A256KW'].includes(encryptionKey.alg)) {\n      throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `The 'encryptionKey' algorithm is not supported: ${encryptionKey.alg}`);\n    }\n\n    if (!('alg' in unwrappedKey && unwrappedKey.alg)) {\n      throw new CryptoError(CryptoErrorCode.InvalidJwk, `The private key to wrap is missing the 'alg' property.`);\n    }\n\n    // Map the private key's JOSE algorithm name to the Web Crypto API algorithm identifier.\n    const webCryptoAlgorithm = {\n      A128KW  : 'AES-KW', A192KW  : 'AES-KW', A256KW  : 'AES-KW',\n      A128CTR : 'AES-CTR', A192CTR : 'AES-CTR', A256CTR : 'AES-CTR',\n      A128GCM : 'AES-GCM', A192GCM : 'AES-GCM', A256GCM : 'AES-GCM',\n    }[unwrappedKey.alg];\n\n    if (!webCryptoAlgorithm) {\n      throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `The 'unwrappedKey' algorithm is not supported: ${unwrappedKey.alg}`);\n    }\n\n    // BoringSSL hosts (e.g. Electron) lack Web Crypto AES-KW: wrap via the\n    // RFC 3394 fallback \u2014 the output is byte-identical to native WebCrypto.\n    if (!(await hasWebCryptoAesKw())) {\n      const encryptionKeyBytes = await AesKw.privateKeyToBytes({ privateKey: encryptionKey });\n      const unwrappedKeyBytes = await AesKw.privateKeyToBytes({ privateKey: unwrappedKey });\n\n      return aeskw(encryptionKeyBytes).encrypt(unwrappedKeyBytes);\n    }\n\n    // Get the Web Crypto API interface.\n    const webCrypto = getWebcryptoSubtle() as unknown as SubtleCrypto;\n\n    // Import the encryption key for use with the Web Crypto API.\n    const encryptionCryptoKey = await webCrypto.importKey(\n      'jwk', // key format\n      encryptionKey as JsonWebKey, // key data\n      { name: 'AES-KW' }, // algorithm identifier\n      true, // key is extractable\n      ['wrapKey'] // key usages\n    );\n\n    // Import the private key to wrap for use with the Web Crypto API.\n    const unwrappedCryptoKey = await webCrypto.importKey(\n      'jwk', // key format\n      unwrappedKey as JsonWebKey, // key data\n      { name: webCryptoAlgorithm }, // algorithm identifier\n      true, // key is extractable\n      ['unwrapKey'] // key usages\n    );\n\n    // Wrap the key using the Web Crypto API.\n    const wrappedKeyBuffer = await webCrypto.wrapKey(\n      'raw', // output format\n      unwrappedCryptoKey, // key to wrap\n      encryptionCryptoKey, // wrapping key\n      'AES-KW' // algorithm identifier\n    );\n\n    // Convert from ArrayBuffer to Uint8Array.\n    const wrappedKeyBytes = new Uint8Array(wrappedKeyBuffer);\n\n    return wrappedKeyBytes;\n  }\n}\n", "import type { Jwk } from '../jose/jwk.js';\nimport type { KeyConverter } from '../types/key-converter.js';\nimport type { KeyGenerator } from '../types/key-generator.js';\nimport type { KeyWrapper } from '../types/key-wrapper.js';\nimport type { RequireOnly } from '@enbox/common';\nimport type { BytesToPrivateKeyParams, GenerateKeyParams, PrivateKeyToBytesParams, UnwrapKeyParams, WrapKeyParams } from '../types/params-direct.js';\n\nimport { AesKw } from '../primitives/aes-kw.js';\nimport { CryptoAlgorithm } from './crypto-algorithm.js';\n\n/**\n * The `AesKwGenerateKeyParams` interface defines the algorithm-specific parameters that should be\n * passed into the `generateKey()` method when using the AES-KW algorithm.\n */\nexport interface AesKwGenerateKeyParams extends GenerateKeyParams {\n  /** Specifies the algorithm variant for key generation in AES-KW mode.\n   * The value determines the length of the key to be generated and must be one of the following:\n   * - `\"A128KW\"`: AES Key Wrap using a 128-bit key.\n   * - `\"A192KW\"`: AES Key Wrap using a 192-bit key.\n   * - `\"A256KW\"`: AES Key Wrap using a 256-bit key.\n   */\n  algorithm: 'A128KW' | 'A192KW' | 'A256KW';\n}\n\n/**\n * The `AesKwAlgorithm` class provides a concrete implementation for cryptographic operations using\n * the AES algorithm for key wrapping. This class implements both\n * {@link KeyGenerator | `KeyGenerator`} and {@link KeyWrapper | `KeyWrapper`} interfaces, providing\n * key generation, key wrapping, and key unwrapping features.\n *\n * This class is typically accessed through implementations that extend the\n * {@link DsaApi | `DsaApi`} interface.\n */\nexport class AesKwAlgorithm extends CryptoAlgorithm\n  implements KeyConverter,\n             KeyGenerator<AesKwGenerateKeyParams, Jwk>,\n             KeyWrapper<WrapKeyParams, UnwrapKeyParams> {\n\n  /**\n   * Converts a private key from a byte array to JWK format, setting the `alg` property based on\n   * the key length.\n   *\n   * @param params - The parameters for the private key conversion.\n   * @param params.privateKeyBytes - The raw private key as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the private key in JWK format.\n   */\n  public async bytesToPrivateKey({ privateKeyBytes }:\n    RequireOnly<BytesToPrivateKeyParams, 'privateKeyBytes'>\n  ): Promise<Jwk> {\n    // Convert the byte array to a JWK.\n    const privateKey = await AesKw.bytesToPrivateKey({ privateKeyBytes });\n\n    // Set the `alg` property based on the key length.\n    privateKey.alg = { 16: 'A128KW', 24: 'A192KW', 32: 'A256KW' }[privateKeyBytes.length];\n\n    return privateKey;\n  }\n\n  /**\n   * Generates a symmetric key for AES for key wrapping in JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method generates a symmetric AES key for use in key wrapping mode, based on the specified\n   * `algorithm` parameter which determines the key length. It uses cryptographically secure random\n   * number generation to ensure the uniqueness and security of the key. The key is returned in JWK\n   * format.\n   *\n   * The generated key includes the following components:\n   * - `kty`: Key Type, set to 'oct' for Octet Sequence.\n   * - `k`: The symmetric key component, base64url-encoded.\n   * - `kid`: Key ID, generated based on the JWK thumbprint.\n   * - `alg`: Algorithm, set to 'A128KW', 'A192KW', or 'A256KW' for AES Key Wrap with the\n   *   specified key length.\n   *\n   * @example\n   * ```ts\n   * const aesKw = new AesKwAlgorithm();\n   * const privateKey = await aesKw.generateKey({ algorithm: 'A256KW' });\n   * ```\n   *\n   * @param params - The parameters for the key generation.\n   *\n   * @returns A Promise that resolves to the generated symmetric key in JWK format.\n   */\n  public async generateKey({ algorithm }:\n    AesKwGenerateKeyParams\n  ): Promise<Jwk> {\n    // Map algorithm name to key length.\n    const length = { A128KW: 128, A192KW: 192, A256KW: 256 }[algorithm] as 128 | 192 | 256;\n\n    // Generate a random private key.\n    const privateKey = await AesKw.generateKey({ length });\n\n    // Set the `alg` property based on the specified algorithm.\n    privateKey.alg = algorithm;\n\n    return privateKey;\n  }\n\n  /**\n   * Converts a private key from JWK format to a byte array.\n   *\n   * @param params - The parameters for the private key conversion.\n   * @param params.privateKey - The private key in JWK format.\n   *\n   * @returns A Promise that resolves to the private key as a Uint8Array.\n   */\n  public async privateKeyToBytes({ privateKey }:\n    PrivateKeyToBytesParams\n  ): Promise<Uint8Array> {\n    // Convert the JWK to a byte array.\n    const privateKeyBytes = await AesKw.privateKeyToBytes({ privateKey });\n\n    return privateKeyBytes;\n  }\n\n  /**\n   * Decrypts a wrapped key using the AES Key Wrap algorithm.\n   *\n   * @remarks\n   * This method unwraps a previously wrapped cryptographic key using the AES Key Wrap algorithm.\n   * The wrapped key, provided as a byte array, is unwrapped using the decryption key specified in\n   * the parameters.\n   *\n   * This operation is useful for securely receiving keys transmitted over untrusted mediums. The\n   * method returns the unwrapped key as a JSON Web Key (JWK).\n   *\n   * @example\n   * ```ts\n   * const aesKw = new AesKwAlgorithm();\n   * const wrappedKeyBytes = new Uint8Array([...]); // Byte array of a wrapped AES-256 GCM key\n   * const decryptionKey = { ... }; // A Jwk object representing the AES unwrapping key\n   * const unwrappedKey = await aesKw.unwrapKey({\n   *   wrappedKeyBytes,\n   *   wrappedKeyAlgorithm: 'A256GCM',\n   *   decryptionKey\n   * });\n   * ```\n   *\n   * @param params - The parameters for the key unwrapping operation.\n   *\n   * @returns A Promise that resolves to the unwrapped key in JWK format.\n   */\n  public async unwrapKey(params:\n    UnwrapKeyParams\n  ): Promise<Jwk> {\n    const unwrappedKey = await AesKw.unwrapKey(params);\n\n    return unwrappedKey;\n  }\n\n  /**\n   * Encrypts a given key using the AES Key Wrap algorithm.\n   *\n   * @remarks\n   * This method wraps a given cryptographic key using the AES Key Wrap algorithm. The private key\n   * to be wrapped is provided in the form of a JSON Web Key (JWK).\n   *\n   * This operation is useful for securely transmitting keys over untrusted mediums. The method\n   * returns the wrapped key as a byte array.\n   *\n   * @example\n   * ```ts\n   * const aesKw = new AesKwAlgorithm();\n   * const unwrappedKey = { ... }; // A Jwk object representing the key to be wrapped\n   * const encryptionKey = { ... }; // A Jwk object representing the AES wrapping key\n   * const wrappedKeyBytes = await aesKw.wrapKey({ unwrappedKey, encryptionKey });\n   * ```\n   *\n   * @param params - The parameters for the key wrapping operation.\n   *\n   * @returns A Promise that resolves to the wrapped key as a Uint8Array.\n   */\n  public async wrapKey(params:\n    WrapKeyParams\n  ): Promise<Uint8Array> {\n    const wrappedKeyBytes = AesKw.wrapKey(params);\n\n    return wrappedKeyBytes;\n  }\n}\n", "import type { DeriveKeyBytesParams } from '../types/params-direct.js';\n\nimport { getWebcryptoSubtle } from './webcrypto.js';\n\nimport { Convert } from '@enbox/common';\n\n/**\n * The object that should be passed into `Hkdf.deriveKeyBytes()`, when using the HKDF algorithm.\n */\nexport type HkdfParams = {\n  /**\n   * A string representing the digest algorithm to use. This may be one of:\n   * - 'SHA-256'\n   * - 'SHA-384'\n   * - 'SHA-512'\n   */\n  hash: 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n  /**\n   * The salt value to use in the derivation process.\n   *\n   * Ideally, the salt is a random or pseudo-random value with the same length as the output of the\n   * digest function. Unlike the input key material passed into deriveKey(), salt does not need to\n   * be kept secret.\n   *\n   * Note: The {@link https://datatracker.ietf.org/doc/html/rfc5869 | HKDF specification} states\n   *       that adding salt \"adds significantly to the strength of HKDF\".\n   */\n  salt: string | Uint8Array;\n\n  /**\n   * Optional application-specific information to use in the HKDF.\n   *\n   * If given, this value is used to bind the derived key to application-specific contextual\n   * information. This makes it possible to derive different keys for different contexts while using\n   * the same input key material.\n   *\n   * If not provided, the `info` value is set to an empty array.\n   *\n   * Note: It is important that the `info` value be independent and unrelated to the input key\n   * material.\n   */\n  info?: string | Uint8Array,\n};\n\n/**\n * The `Hkdf` class provides an interface for HMAC-based Extract-and-Expand Key Derivation Function (HKDF)\n * as defined in RFC 5869.\n *\n * Note: The `baseKeyBytes` that will be the input key material for HKDF should be a high-entropy secret\n * value, such as a cryptographic key. It should be kept confidential and not be derived from a\n * low-entropy value, such as a password.\n *\n * @example\n * ```ts\n * const info = new Uint8Array([...]);\n * const derivedKeyBytes = await Hkdf.deriveKeyBytes({\n *   baseKeyBytes: new Uint8Array([...]), // Input keying material\n *   hash: 'SHA-256', // The hash function to use ('SHA-256', 'SHA-384', 'SHA-512')\n *   salt: new Uint8Array([...]), // The salt value\n *   info: new Uint8Array([...]), // Optional application-specific information\n *   length: 256 // The length of the derived key in bits\n * });\n * ```\n */\nexport class Hkdf {\n  /**\n   * Derives a key using the HMAC-based Extract-and-Expand Key Derivation Function (HKDF).\n   *\n   * This method generates a derived key using a hash function from input keying material given as\n   * `baseKeyBytes`. The length of the derived key can be specified. Optionally, it can also use a salt\n   * and info for the derivation process.\n   *\n   * HKDF is useful in various cryptographic applications and protocols, especially when\n   * there's a need to derive multiple keys from a single source of key material.\n   *\n   * Note: The `baseKeyBytes` that will be the input key material for HKDF should be a high-entropy\n   * secret value, such as a cryptographic key. It should be kept confidential and not be derived\n   * from a low-entropy value, such as a password.\n   *\n   * @example\n   * ```ts\n   * const info = new Uint8Array([...]);\n   * const derivedKeyBytes = await Hkdf.deriveKeyBytes({\n   *   baseKeyBytes: new Uint8Array([...]), // Input keying material\n   *   hash: 'SHA-256', // The hash function to use ('SHA-256', 'SHA-384', 'SHA-512')\n   *   salt: new Uint8Array([...]), // The salt value\n   *   info: new Uint8Array([...]), // Optional application-specific information\n   *   length: 256 // The length of the derived key in bits\n   * });\n   * ```\n   *\n   * @param params - The parameters for key derivation.\n   * @returns A Promise that resolves to the derived key as a byte array.\n   */\n  public static async deriveKeyBytes({ baseKeyBytes, length, hash, salt, info = new Uint8Array() }:\n    DeriveKeyBytesParams & HkdfParams\n  ): Promise<Uint8Array> {\n    // Get the Web Crypto API interface.\n    const webCrypto = getWebcryptoSubtle() as unknown as SubtleCrypto;\n\n    // Import the baseKeyBytes into the Web Crypto API to use for the key derivation operation.\n    const webCryptoKey = await webCrypto.importKey('raw', baseKeyBytes as BufferSource, { name: 'HKDF' }, false, ['deriveBits']);\n\n    // Convert the salt and info to Uint8Array if they are provided as strings.\n    const saltBytes = typeof salt === 'string' ? Convert.string(salt).toUint8Array() : salt;\n    const infoBytes = typeof info === 'string' ? Convert.string(info).toUint8Array() : info;\n\n    // Derive the bytes using the Web Crypto API.\n    const derivedKeyBuffer = await webCrypto.deriveBits(\n      { name: 'HKDF', hash, salt: saltBytes as BufferSource, info: infoBytes as BufferSource },\n      webCryptoKey,\n      length\n    );\n\n    // Convert from ArrayBuffer to Uint8Array.\n    const derivedKeyBytes = new Uint8Array(derivedKeyBuffer);\n\n    return derivedKeyBytes;\n  }\n}\n", "import type { DeriveKeyBytesParams } from '../types/params-direct.js';\nimport type { HkdfParams } from '../primitives/hkdf.js';\nimport type { KeyBytesDeriver } from '../types/key-deriver.js';\n\nimport { CryptoAlgorithm } from './crypto-algorithm.js';\nimport { Hkdf } from '../primitives/hkdf.js';\n\n/**\n * The `HkdfDeriveKeyBytesParams` interface defines the algorithm-specific parameters that should be\n * passed into the `deriveKeyBytes()` method when using the HKDF algorithm.\n */\nexport interface HkdfDeriveKeyBytesParams extends DeriveKeyBytesParams {\n  /** Specifies the algorithm variant for HKDF key derivation.\n   * The value determines the hash function that will be used and must be one of the following:\n   * - `\"HKDF-256\"`: HKDF with SHA-256.\n   * - `\"HKDF-384\"`: HKDF with SHA-384.\n   * - `\"HKDF-512\"`: HKDF with SHA-512.\n   */\n  algorithm: 'HKDF-256' | 'HKDF-384' | 'HKDF-512';\n}\n\n/**\n * The `HkdfAlgorithm` class provides a concrete implementation for HKDF key derivation. It wraps\n * the {@link Hkdf} primitive and maps JOSE algorithm names to hash functions.\n */\nexport class HkdfAlgorithm extends CryptoAlgorithm\n  implements KeyBytesDeriver<HkdfDeriveKeyBytesParams, Uint8Array> {\n\n  /**\n   * Derives a cryptographic byte array using HKDF.\n   *\n   * @param params - The parameters for the key derivation operation.\n   * @param params.algorithm - The HKDF algorithm variant (e.g., `'HKDF-256'`).\n   * @param params.baseKeyBytes - The input key material.\n   * @param params.length - The desired length of the output in bits.\n   *\n   * @returns A Promise that resolves to the derived key bytes.\n   */\n  public async deriveKeyBytes({ algorithm, ...params }:\n    HkdfDeriveKeyBytesParams & Omit<HkdfParams, 'hash'>\n  ): Promise<Uint8Array> {\n    // Map algorithm name to hash function.\n    const hash = {\n      'HKDF-256' : 'SHA-256' as const,\n      'HKDF-384' : 'SHA-384' as const,\n      'HKDF-512' : 'SHA-512' as const\n    }[algorithm];\n\n    // Derive a cryptographic byte array using HKDF.\n    const derivedKeyBytes = await Hkdf.deriveKeyBytes({ ...params, hash });\n\n    return derivedKeyBytes;\n  }\n}\n", "import type { DeriveKeyBytesParams } from '../types/params-direct.js';\n\nimport { getWebcryptoSubtle } from './webcrypto.js';\n\n/**\n * The object that should be passed into `Pbkdf2.deriveKeyBytes()`, when using the PBKDF2 algorithm.\n */\nexport interface Pbkdf2Params {\n  /**\n   * A string representing the digest algorithm to use. This may be one of:\n   * - 'SHA-256'\n   * - 'SHA-384'\n   * - 'SHA-512'\n   */\n  hash: 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n  /**\n   * The salt value to use in the derivation process, as a Uint8Array. This should be a random or\n   * pseudo-random value of at least 16 bytes. Unlike the `password`, `salt` does not need to be\n   * kept secret.\n   */\n  salt: Uint8Array;\n\n  /**\n   * A `Number` representing the number of iterations the hash function will be executed in\n   * `deriveKey()`. This impacts the computational cost of the `deriveKey()` operation, making it\n   * more resistant to dictionary attacks. The higher the number, the more secure, but also slower,\n   * the operation. Choose a value that balances security needs and performance for your\n   * application.\n   */\n  iterations: number;\n}\n\n/**\n * The object that should be passed into `Pbkdf2.deriveKey()`, when using the PBKDF2 algorithm.\n */\nexport type Pbkdf2DeriveKeyParams = {\n  /**\n   * A string representing the digest algorithm to use. This may be one of:\n   * - 'SHA-256'\n   * - 'SHA-384'\n   * - 'SHA-512'\n   */\n  hash: 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n  /**\n   * The password from which to derive the key, represented as a Uint8Array.\n   */\n  password: Uint8Array;\n\n  /**\n   * The salt value to use in the derivation process, as a Uint8Array. This should be a random or\n   * pseudo-random value of at least 16 bytes. Unlike the `password`, `salt` does not need to be\n   * kept secret.\n   */\n  salt: Uint8Array;\n\n  /**\n   * A `Number` representing the number of iterations the hash function will be executed in\n   * `deriveKey()`. This impacts the computational cost of the `deriveKey()` operation, making it\n   * more resistant to dictionary attacks. The higher the number, the more secure, but also slower,\n   * the operation. Choose a value that balances security needs and performance for your\n   * application.\n   */\n  iterations: number;\n\n  /**\n   * The desired length of the derived key in bits. To be compatible with all browsers, the number\n   * should be a multiple of 8.\n   */\n  length: number;\n};\n\n/**\n * The `Pbkdf2` class provides a secure way to derive cryptographic keys from a password\n * using the PBKDF2 (Password-Based Key Derivation Function 2) algorithm.\n *\n * The PBKDF2 algorithm is widely used for generating keys from passwords, as it applies\n * a pseudorandom function to the input password along with a salt value and iterates the\n * process multiple times to increase the key's resistance to brute-force attacks.\n *\n * This class offers a single static method `deriveKey` to perform key derivation.\n *\n * @example\n * ```ts\n * // Key Derivation\n * const derivedKey = await Pbkdf2.deriveKey({\n *   hash: 'SHA-256', // The hash function to use ('SHA-256', 'SHA-384', 'SHA-512')\n *   password: new TextEncoder().encode('password'), // The password as a Uint8Array\n *   salt: new Uint8Array([...]), // The salt value\n *   iterations: 1000, // The number of iterations\n *   length: 256 // The length of the derived key in bits\n * });\n * ```\n *\n * @remarks\n * This class relies on the availability of the Web Crypto API.\n */\nexport class Pbkdf2 {\n  /**\n   * Derives a cryptographic key from a password using the PBKDF2 algorithm.\n   *\n   * @remarks\n   * This method applies the PBKDF2 algorithm to the provided password along with\n   * a salt value and iterates the process a specified number of times. It uses\n   * a cryptographic hash function to enhance security and produce a key of the\n   * desired length. The method is capable of utilizing either the Web Crypto API\n   * or the Node.js Crypto module, depending on the environment's support.\n   *\n   * @example\n   * ```ts\n   * const derivedKey = await Pbkdf2.deriveKey({\n   *   hash: 'SHA-256',\n   *   password: new TextEncoder().encode('password'),\n   *   salt: new Uint8Array([...]),\n   *   iterations: 1000,\n   *   length: 256\n   * });\n   * ```\n   *\n   * @param params - The parameters for key derivation.\n   * @param params.hash - The hash function to use, such as 'SHA-256', 'SHA-384', or 'SHA-512'.\n   * @param params.password - The password from which to derive the key, represented as a Uint8Array.\n   * @param params.salt - The salt value to use in the derivation process, as a Uint8Array.\n   * @param params.iterations - The number of iterations to apply in the PBKDF2 algorithm.\n   * @param params.length - The desired length of the derived key in bits.\n   *\n   * @returns A Promise that resolves to the derived key as a Uint8Array.\n   */\n  public static async deriveKey({ hash, password, salt, iterations, length }:\n    Pbkdf2DeriveKeyParams\n  ): Promise<Uint8Array> {\n    // Import the password as a raw key for use with the Web Crypto API.\n    const webCrypto = getWebcryptoSubtle();\n    const webCryptoKey = await webCrypto.importKey(\n      'raw',\n      password,\n      { name: 'PBKDF2' },\n      false,\n      ['deriveBits']\n    );\n\n    const derivedKeyBuffer = await webCrypto.deriveBits(\n      { name: 'PBKDF2', hash, salt, iterations },\n      webCryptoKey,\n      length\n    );\n\n    // Convert from ArrayBuffer to Uint8Array.\n    const derivedKey = new Uint8Array(derivedKeyBuffer);\n\n    return derivedKey;\n  }\n\n  /**\n   * Derives cryptographic key bytes from base key material using the PBKDF2 algorithm.\n   *\n   * @remarks\n   * This method is similar to {@link Pbkdf2.deriveKey | `deriveKey()`} but accepts\n   * raw key bytes (`baseKeyBytes`) instead of a password. It is intended for use cases\n   * where the input key material is already available as a byte array.\n   *\n   * Notes:\n   * - The `baseKeyBytes` that will be the input key material for PBKDF2 is expected to be a\n   *   low-entropy value, such as a password or passphrase. It should be kept confidential.\n   * - In 2023,\n   *   {@link https://web.archive.org/web/20230123232056/https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2\n   *   | OWASP recommended}\n   *   a minimum of 600,000 iterations for PBKDF2-HMAC-SHA256 and 210,000 for PBKDF2-HMAC-SHA512.\n   *\n   * @example\n   * ```ts\n   * const derivedKeyBytes = await Pbkdf2.deriveKeyBytes({\n   *   baseKeyBytes: new TextEncoder().encode('password'),\n   *   hash: 'SHA-256',\n   *   salt: new Uint8Array([...]),\n   *   iterations: 600_000,\n   *   length: 256\n   * });\n   * ```\n   *\n   * @param params - The parameters for key derivation.\n   * @returns A Promise that resolves to the derived key as a byte array.\n   */\n  public static async deriveKeyBytes({ baseKeyBytes, hash, salt, iterations, length }:\n    DeriveKeyBytesParams & Pbkdf2Params\n  ): Promise<Uint8Array> {\n    // Get the Web Crypto API interface.\n    const webCrypto = getWebcryptoSubtle() as unknown as SubtleCrypto;\n\n    // Import the password as a raw key for use with the Web Crypto API.\n    const webCryptoKey = await webCrypto.importKey(\n      'raw', // key format is raw bytes\n      baseKeyBytes as BufferSource, // key data to import\n      { name: 'PBKDF2' }, // algorithm identifier\n      false, // key is not extractable\n      ['deriveBits'] // key usages\n    );\n\n    // Derive the bytes using the Web Crypto API.\n    const derivedKeyBuffer = await webCrypto.deriveBits(\n      { name: 'PBKDF2', hash, salt: salt as BufferSource, iterations },\n      webCryptoKey,\n      length\n    );\n\n    // Convert from ArrayBuffer to Uint8Array.\n    const derivedKeyBytes = new Uint8Array(derivedKeyBuffer);\n\n    return derivedKeyBytes;\n  }\n}\n", "import type { DeriveKeyBytesParams } from '../types/params-direct.js';\nimport type { KeyBytesDeriver } from '../types/key-deriver.js';\nimport type { Pbkdf2Params } from '../primitives/pbkdf2.js';\n\nimport { CryptoAlgorithm } from './crypto-algorithm.js';\nimport { Pbkdf2 } from '../primitives/pbkdf2.js';\n\n/**\n * The `Pbkdf2DeriveKeyBytesParams` interface defines the algorithm-specific parameters that\n * should be passed into the `deriveKeyBytes()` method when using the PBKDF2 algorithm.\n */\nexport interface Pbkdf2DeriveKeyBytesParams extends DeriveKeyBytesParams {\n  /** Specifies the algorithm variant for PBKDF2 key derivation.\n   * The value determines the hash function that will be used and must be one of the following:\n   * - `\"PBES2-HS256+A128KW\"`: PBKDF2 with HMAC SHA-256 and A128KW key wrapping.\n   * - `\"PBES2-HS384+A192KW\"`: PBKDF2 with HMAC SHA-384 and A192KW key wrapping.\n   * - `\"PBES2-HS512+A256KW\"`: PBKDF2 with HMAC SHA-512 and A256KW key wrapping.\n   */\n  algorithm: 'PBES2-HS256+A128KW' | 'PBES2-HS384+A192KW' | 'PBES2-HS512+A256KW';\n}\n\n/**\n * The `Pbkdf2Algorithm` class provides a concrete implementation for PBKDF2 key derivation. It\n * wraps the {@link Pbkdf2} primitive and maps PBES2 JOSE algorithm names to hash functions.\n */\nexport class Pbkdf2Algorithm extends CryptoAlgorithm\n  implements KeyBytesDeriver<Pbkdf2DeriveKeyBytesParams, Uint8Array> {\n\n  /**\n   * Derives a cryptographic byte array using PBKDF2.\n   *\n   * @param params - The parameters for the key derivation operation.\n   * @param params.algorithm - The PBES2 algorithm variant (e.g., `'PBES2-HS512+A256KW'`).\n   * @param params.baseKeyBytes - The password or passphrase as bytes.\n   * @param params.length - The desired length of the output in bits.\n   *\n   * @returns A Promise that resolves to the derived key bytes.\n   */\n  public async deriveKeyBytes({ algorithm, ...params }:\n    Pbkdf2DeriveKeyBytesParams & Omit<Pbkdf2Params, 'hash'>\n  ): Promise<Uint8Array> {\n    // Extract the hash function component of the `algorithm` parameter.\n    const [, hashFunction] = algorithm.split(/[-+]/);\n\n    // Map from JOSE algorithm name to \"SHA\" hash function identifier.\n    const hash = {\n      'HS256' : 'SHA-256' as const,\n      'HS384' : 'SHA-384' as const,\n      'HS512' : 'SHA-512' as const\n    }[hashFunction]!;\n\n    // Derive a cryptographic byte array using PBKDF2.\n    const derivedKeyBytes = await Pbkdf2.deriveKeyBytes({ ...params, hash });\n\n    return derivedKeyBytes;\n  }\n}\n", "import type { JoseHeaderParams } from '../jws.js';\nimport type { Jwk } from '../jwk.js';\nimport type { KeyIdentifier } from '../../types/identifier.js';\n\n/**\n * JWE \"alg\" (Algorithm) Header Parameter values supported by this engine's key management.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc7518#section-4.1 | RFC 7518, Section 4.1}\n */\nexport type JweAlg =\n  // Direct use of a shared symmetric key as the CEK\n  | 'dir'\n  // Elliptic Curve Diffie-Hellman Ephemeral Static key agreement using Concat KDF\n  | 'ECDH-ES'\n  // PBES2 with HMAC SHA-256 and \"A128KW\" wrapping\n  | 'PBES2-HS256+A128KW'\n  // PBES2 with HMAC SHA-384 and \"A192KW\" wrapping\n  | 'PBES2-HS384+A192KW'\n  // PBES2 with HMAC SHA-512 and \"A256KW\" wrapping\n  | 'PBES2-HS512+A256KW';\n\n/**\n * JWE \"enc\" (Encryption Algorithm) Header Parameter values supported by this engine's content\n * encryption.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc7518#section-5.1 | RFC 7518, Section 5.1}\n */\nexport type JweEnc =\n  // AES GCM using 128-bit key\n  | 'A128GCM'\n  // AES GCM using 192-bit key\n  | 'A192GCM'\n  // AES GCM using 256-bit key\n  | 'A256GCM'\n  // XChaCha20-Poly1305 authenticated encryption algorithm\n  | 'XC20P';\n\n/**\n * Specifies options for decrypting a JWE, allowing the caller to define constraints on the JWE\n * decryption process, particularly regarding the algorithms used.\n *\n * These options ensure that only expected and permitted algorithms are utilized during the\n * decryption, enhancing security by preventing unexpected algorithm usage.\n */\nexport interface JweDecryptOptions {\n  /**\n   * The exhaustive list of \"alg\" (Algorithm) Header Parameter values the caller accepts for this\n   * decrypt operation. Decryption fails before any key management processing if the JWE's \"alg\"\n   * value is not in this list, preventing algorithm-confusion attacks between callers that share\n   * the same engine (e.g. vault PBES2 vs. connect ECDH-ES).\n   */\n  allowedAlgs: JweAlg[];\n\n  /**\n   * The exhaustive list of \"enc\" (Encryption Algorithm) Header Parameter values the caller accepts\n   * for this decrypt operation. Decryption fails before any key management processing if the JWE's\n   * \"enc\" value is not in this list.\n   */\n  allowedEncs: JweEnc[];\n\n  /**\n   * Minimum acceptable PBES2 iteration count (\"p2c\") for key derivation during decryption.\n   * Per RFC 7518 Section 4.8.1.2, a minimum of 1000 is RECOMMENDED. Set to a lower value\n   * only for test environments where speed is prioritized over security.\n   *\n   * @default 1000\n   */\n  minP2cCount?: number;\n}\n\n/**\n * Placeholder for specifying options during the JWE encryption process. Currently, this interface\n * does not define any specific options but can be extended in the future to include parameters\n * that control various aspects of the JWE encryption workflow.\n */\nexport interface JweEncryptOptions {}\n\n/**\n * A minimal cipher interface over {@link KeyIdentifier} (e.g. KMS URI) referenced keys.\n *\n * When a JWE uses \"dir\" (Direct Encryption Mode) with a Content Encryption Key that is referenced\n * by a Key Identifier rather than provided as a JWK, the engine delegates content encryption and\n * decryption to an injected implementation of this interface. The agent's `LocalKeyManager`\n * satisfies this interface structurally.\n */\nexport interface JweCipher {\n  /**\n   * Decrypts the provided data using the key identified by `keyUri`.\n   *\n   * @param params - The parameters for the decryption operation.\n   * @returns A Promise that resolves to the decrypted data as a byte array.\n   */\n  decrypt(params: { keyUri: KeyIdentifier; data: Uint8Array; iv?: Uint8Array; additionalData?: Uint8Array }): Promise<Uint8Array>;\n\n  /**\n   * Encrypts the provided data using the key identified by `keyUri`.\n   *\n   * @param params - The parameters for the encryption operation.\n   * @returns A Promise that resolves to the ciphertext (including the authentication tag) as a\n   *          byte array.\n   */\n  encrypt(params: { keyUri: KeyIdentifier; data: Uint8Array; iv?: Uint8Array; additionalData?: Uint8Array }): Promise<Uint8Array>;\n}\n\n/**\n * JSON Web Encryption (JWE) Header Parameters\n *\n * The Header Parameter names for use in JWEs are registered in the IANA \"JSON Web Signature and\n * Encryption Header Parameters\" registry.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc7516#section-4.1 | RFC 7516, Section 4.1}\n */\nexport interface JweHeaderParams extends JoseHeaderParams {\n  /**\n   * Algorithm Header Parameter\n   *\n   * Identifies the cryptographic algorithm used to encrypt or determine the value of the Content\n   * Encryption Key (CEK). The encrypted content is not usable if the \"alg\" value does not represent\n   * a supported algorithm, or if the recipient does not have a key that can be used with that\n   * algorithm.\n   *\n   * \"alg\" values should either be registered in the IANA \"JSON Web Signature and Encryption\n   * Algorithms\" registry or be a value that contains a Collision-Resistant Name. The \"alg\" value is\n   * a case-sensitive ASCII string.  This Header Parameter MUST be present and MUST be understood\n   * and processed by implementations.\n   *\n   * @see {@link https://datatracker.ietf.org/doc/html/rfc7516#section-4.1.1 | RFC 7516, Section 4.1.1}\n   */\n  alg:\n    // Algorithms supported by this engine's key management\n    | JweAlg\n    // an unregistered, case-sensitive, collision-resistant string\n    // `string & {}` preserves the literal hints above while still accepting any string.\n    | (string & {});\n\n  /**\n   * Agreement PartyUInfo Header Parameter\n   *\n   * The \"apu\" (agreement PartyUInfo) value is a base64url-encoded octet sequence containing\n   * information about the producer of the JWE.  This information is used by the recipient to\n   * determine the key agreement algorithm and key encryption algorithm to use to decrypt the JWE.\n   *\n   * Note: This parameter is intended only for use when the recipient is a key agreement algorithm\n   * that uses public key cryptography.\n   */\n  apu?: string;\n\n  /**\n   * Agreement PartyVInfo Header Parameter\n   *\n   * The \"apv\" (agreement PartyVInfo) value is a base64url-encoded octet sequence containing\n   * information about the recipient of the JWE.  This information is used by the recipient to\n   * determine the key agreement algorithm and key encryption algorithm to use to decrypt the JWE.\n   *\n   * Note: This parameter is intended only for use when the recipient is a key agreement algorithm\n   * that uses public key cryptography.\n   */\n  apv?: string;\n\n  /**\n   * Critical Header Parameter\n   *\n   * Indicates that extensions to JOSE RFCs are being used that MUST be understood and processed.\n   */\n  crit?: string[];\n\n  /**\n   * Encryption Algorithm Header Parameter\n   *\n   * Identifies the content encryption algorithm used to encrypt and integrity-protect (also\n   * known as \"authenticated encryption\") the plaintext and to integrity-protect the Additional\n   * Authenticated Data (AAD), if any.  This algorithm MUST be an AEAD algorithm with a specified\n   * key length.\n   *\n   * The encrypted content is not usable if the \"enc\" value does not represent a supported\n   * algorithm.  \"enc\" values should either be registered in the IANA \"JSON Web Signature and\n   * Encryption Algorithms\" registry or be a value that contains a Collision-Resistant Name. The\n   * \"enc\" value is a case-sensitive ASCII string containing a StringOrURI value. This Header\n   * Parameter MUST be present and MUST be understood and processed by implementations.\n   *\n   * @see {@link https://datatracker.ietf.org/doc/html/rfc7516#section-4.1.2 | RFC 7516, Section 4.1.2}\n   */\n  enc:\n    // Algorithms supported by this engine's content encryption\n    | JweEnc\n    // an unregistered, case-sensitive, collision-resistant string\n    // `string & {}` preserves the literal hints above while still accepting any string.\n    | (string & {});\n\n  /**\n   * Ephemeral Public Key Header Parameter\n   *\n   * The \"epk\" (ephemeral public key) value created by the originator for the use in key agreement\n   * algorithms.  It is the ephemeral public key that corresponds to the key used to encrypt the\n   * JWE.  This value is represented as a JSON Web Key (JWK).\n   *\n   * Note: This parameter is intended only for use when the recipient is a key agreement algorithm\n   * that uses public key cryptography.\n   */\n  epk?: Jwk;\n\n  /**\n   * Initialization Vector Header Parameter\n   *\n   * The \"iv\" (initialization vector) value is a base64url-encoded octet sequence used by the\n   * specified \"enc\" algorithm.  The length of this Initialization Vector value MUST be exactly\n   * equal to the value that would be produced by the \"enc\" algorithm.\n   *\n   * Note: With symmetric encryption algorithms such as AES GCM, this Header Parameter MUST\n   * be present and MUST be understood and processed by implementations.\n   */\n  iv?: string;\n\n  /**\n   * PBES2 Count Header Parameter\n   *\n   * The \"p2c\" (PBES2 count) value is an integer indicating the number of iterations of the PBKDF2\n   * algorithm performed during key derivation.\n   *\n   * Note: The iteration count adds computational expense, ideally compounded by the possible range\n   * of keys introduced by the salt.  A minimum iteration count of 1000 is RECOMMENDED.\n   */\n  p2c?: number;\n\n  /**\n   * PBES2 Salt Input Header Parameter\n   *\n   * The \"p2s\" (PBES2 salt) value is a base64url-encoded octet sequence used as the salt value\n   * input to the PBKDF2 algorithm during key derivation.\n   *\n   * The salt value used is (UTF8(Alg) || 0x00 || Salt Input), where Alg is the \"alg\" (algorithm)\n   * Header Parameter value.\n   *\n   * Note: The salt value is used to ensure that each key derived from the master key is\n   * independent of every other key. A suitable source of salt value is a sequence of\n   * cryptographically random bytes containing 8 or more octets.\n   */\n  p2s?: string;\n\n  /**\n   * Authentication Tag Header Parameter\n   *\n   * The \"tag\" value is a base64url-encoded octet sequence containing the value of the\n   * Authentication Tag output by the specified \"enc\" algorithm.  The length of this\n   * Authentication Tag value MUST be exactly equal to the value that would be produced by the\n   * \"enc\" algorithm.\n   *\n   * Note: With authenticated encryption algorithms such as AES GCM, this Header Parameter MUST\n   * be present and MUST be understood and processed by implementations.\n   */\n  tag?: string;\n\n  /**\n   * Additional Public or Private Header Parameter names.\n   */\n  [key: string]: unknown;\n}\n\n/**\n * Checks if the provided object is a valid JWE (JSON Web Encryption) header.\n *\n * This function evaluates whether the given object adheres to the structure expected for\n * a JWE header, specifically looking for the presence and proper format of the \"alg\" (algorithm)\n * and \"enc\" (encryption algorithm) properties, which are essential for defining the JWE's\n * cryptographic operations.\n *\n * @example\n * ```ts\n * const header = {\n *   alg: 'dir',\n *   enc: 'A256GCM'\n * };\n *\n * if (isValidJweHeader(header)) {\n *   console.log('The object is a valid JWE header.');\n * } else {\n *   console.log('The object is not a valid JWE header.');\n * }\n * ```\n *\n * @param obj - The object to be validated as a JWE header.\n * @returns Returns `true` if the object is a valid JWE header, otherwise `false`.\n */\nexport function isValidJweHeader(obj: unknown): obj is JweHeaderParams {\n  return typeof obj === 'object' && obj !== null\n    && 'alg' in obj && obj.alg !== undefined\n    && 'enc' in obj && obj.enc !== undefined;\n}\n", "/**\n * Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.\n\nRFC8439 requires multi-step cipher stream, where\nauthKey starts with counter: 0, actual msg with counter: 1.\n\nFor this, we need a way to re-use nonce / counter:\n\n    const counter = new Uint8Array(4);\n    chacha(..., counter, ...); // counter is now 1\n    chacha(..., counter, ...); // counter is now 2\n\nThis is complicated:\n\n- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB\n- Original papers don't allow mutating counters\n- Counter overflow is undefined [^1]\n- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it\n- Caveat: Cannot be re-used through all cases:\n- * chacha has (counter | nonce)\n- * xchacha has (nonce16 | counter | nonce16)\n- Idea B: separate nonce / counter and provide separate API for counter re-use\n- Caveat: there are different counter sizes depending on an algorithm.\n- salsa & chacha also differ in structures of key & sigma:\n  salsa20:      s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]\n  chacha:       s(4) | k(8) | cnt(1) | nonce(3)\n  chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)\n- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`\n- Caveat: we can't re-use counter array\n\nxchacha uses the subkey and remaining 8 byte nonce with ChaCha20 as normal\n(prefixed by 4 NUL bytes, since RFC8439 specifies a 12-byte nonce).\nCounter overflow is undefined; see {@link https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ | the CFRG thread}.\nCurrent noble policy is strict non-wrap for the shared 32-bit counter path:\nexported ARX ciphers reject initial `0xffffffff` and stop before any implicit\nwrap back to zero.\nSee {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 | the XChaCha appendix} for the extended-nonce construction.\n\n * @module\n */\nimport {\n  type PRG,\n  type TArg,\n  type TRet,\n  type XorStream,\n  abool,\n  abytes,\n  anumber,\n  checkOpts,\n  clean,\n  copyBytes,\n  getOutput,\n  isAligned32,\n  isLE,\n  randomBytes,\n  swap32IfBE,\n  u32,\n} from './utils.ts';\n\n// Replaces `TextEncoder` for ASCII literals, which is enough for sigma constants.\n// Non-ASCII input would not match UTF-8 `TextEncoder` output.\nconst encodeStr = (str: string) => Uint8Array.from(str.split(''), (c) => c.charCodeAt(0));\n// Raw `createCipher(...)` exports consume these native-endian `u32(...)` views directly.\n// Public `wrapCipher(...)` APIs reject non-little-endian platforms before reaching this path.\n// RFC 8439 \u00A72.3 / RFC 7539 \u00A72.3 only define the 256-bit-key constants; this 16-byte sigma is\n// kept for legacy allowShortKeys Salsa/ChaCha variants.\nconst sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 16-byte k'))))();\n// RFC 8439 \u00A72.3 / RFC 7539 \u00A72.3 define words 0-3 as\n// `0x61707865 0x3320646e 0x79622d32 0x6b206574`, i.e. `expand 32-byte k`.\nconst sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 32-byte k'))))();\n\n/**\n * Rotates a 32-bit word left.\n * @param a - Input word.\n * @param b - Rotation count in bits.\n * @returns Rotated 32-bit word.\n * @example\n * Moves the top byte of `0x12345678` into the low byte position.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(a: number, b: number): number {\n  return (a << b) | (a >>> (32 - b));\n}\n\n/**\n * ARX core function operating on 32-bit words. Ciphers must use u32 for efficiency.\n * @param sigma - Sigma constants for the selected cipher layout.\n * @param key - Expanded key words.\n * @param nonce - Nonce and counter words prepared for the round function.\n * @param output - Output block written in place.\n * @param counter - Block counter value.\n * @param rounds - Optional round count override.\n */\nexport type CipherCoreFn = (\n  sigma: TArg<Uint32Array>,\n  key: TArg<Uint32Array>,\n  nonce: TArg<Uint32Array>,\n  output: TArg<Uint32Array>,\n  counter: number,\n  rounds?: number\n) => void;\n\n/**\n * Nonce-extension function used by XChaCha and XSalsa.\n * @param sigma - Sigma constants for the selected cipher layout.\n * @param key - Expanded key words.\n * @param input - Input nonce words used for subkey derivation.\n * @param output - Output buffer written with the derived nonce words.\n */\nexport type ExtendNonceFn = (\n  sigma: TArg<Uint32Array>,\n  key: TArg<Uint32Array>,\n  input: TArg<Uint32Array>,\n  output: TArg<Uint32Array>\n) => void;\n\n/** ARX cipher options.\n * * `allowShortKeys` for 16-byte keys\n * * `counterLength` in bytes\n * * `counterRight`: right: `nonce|counter`; left: `counter|nonce`\n * */\nexport type CipherOpts = {\n  /** Whether 16-byte keys are accepted for legacy Salsa and ChaCha variants. */\n  allowShortKeys?: boolean;\n  /** Optional nonce-expansion hook used by extended-nonce variants. */\n  extendNonceFn?: ExtendNonceFn;\n  /** Counter length in bytes inside the nonce/counter layout. */\n  counterLength?: number;\n  /** Whether the layout is `nonce|counter` instead of `counter|nonce`. */\n  counterRight?: boolean;\n  /** Number of core rounds to execute. */\n  rounds?: number;\n};\n\n// Salsa and Chacha block length is always 512-bit\nconst BLOCK_LEN = 64;\n// RFC 8439 \u00A72.2 / RFC 7539 \u00A72.2: the ChaCha state has 16 32-bit words.\nconst BLOCK_LEN32 = 16;\n\n// Counter policy for the shared public `counter` argument:\n// - RFC/IETF ChaCha20 uses a 32-bit counter.\n// - OpenSSL/Node `chacha20` instead treat the full 16-byte IV as a 128-bit\n//   counter state and carry into the next word.\n// - Raw `chacha20orig`, `salsa20`, `xsalsa20`, and `xchacha20` use 64-bit counters in libsodium\n//   and libtomcrypt, while some libs (for example libtomcrypt's RFC/IETF path) reject the max\n//   boundary instead of carrying.\n// - AEAD wrappers diverge too: libsodium `xchacha20poly1305` uses the IETF payload counter from\n//   block 1, while `secretstream_xchacha20poly1305` is a different protocol with rekey/reset.\n// Noble intentionally throws instead of silently picking one wrap model for users. In the default\n// path, even a 32-bit boundary would take 2^32 blocks * 64 bytes = 256 GiB, which is practically\n// unreachable for normal JS callers; advanced users who pass `counter` explicitly can implement\n// whatever wider carry / wrap policy they need on top.\nconst MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)();\nconst U32_EMPTY = /* @__PURE__ */ Uint32Array.of();\nfunction runCipher(\n  core: TArg<CipherCoreFn>,\n  sigma: TArg<Uint32Array>,\n  key: TArg<Uint32Array>,\n  nonce: TArg<Uint32Array>,\n  data: TArg<Uint8Array>,\n  output: TArg<Uint8Array>,\n  counter: number,\n  rounds: number\n): void {\n  const len = data.length;\n  const block = new Uint8Array(BLOCK_LEN);\n  const b32 = u32(block);\n  // Make sure that buffers aligned to 4 bytes\n  const isAligned = isLE && isAligned32(data) && isAligned32(output);\n  const d32 = isAligned ? u32(data) : U32_EMPTY;\n  const o32 = isAligned ? u32(output) : U32_EMPTY;\n  // RFC 8439 \u00A72.4.1 / RFC 7539 \u00A72.4.1 allow XORing one keystream block at a time and\n  // truncating the final partial block instead of materializing the whole keystream.\n  if (!isLE) {\n    for (let pos = 0; pos < len; counter++) {\n      core(\n        sigma as TRet<Uint32Array>,\n        key as TRet<Uint32Array>,\n        nonce as TRet<Uint32Array>,\n        b32,\n        counter,\n        rounds\n      );\n      // RFC 8439 \u00A72.4 / RFC 7539 \u00A72.4 serialize keystream words in little-endian order.\n      swap32IfBE(b32);\n      if (counter >= MAX_COUNTER) throw new Error('arx: counter overflow');\n      const take = Math.min(BLOCK_LEN, len - pos);\n      for (let j = 0, posj; j < take; j++) {\n        posj = pos + j;\n        output[posj] = data[posj] ^ block[j];\n      }\n      pos += take;\n    }\n    return;\n  }\n  for (let pos = 0; pos < len; counter++) {\n    core(\n      sigma as TRet<Uint32Array>,\n      key as TRet<Uint32Array>,\n      nonce as TRet<Uint32Array>,\n      b32,\n      counter,\n      rounds\n    );\n    // See MAX_COUNTER policy note above: never silently wrap the shared public counter.\n    if (counter >= MAX_COUNTER) throw new Error('arx: counter overflow');\n    const take = Math.min(BLOCK_LEN, len - pos);\n    // aligned to 4 bytes\n    if (isAligned && take === BLOCK_LEN) {\n      const pos32 = pos / 4;\n      if (pos % 4 !== 0) throw new Error('arx: invalid block position');\n      for (let j = 0, posj: number; j < BLOCK_LEN32; j++) {\n        posj = pos32 + j;\n        o32[posj] = d32[posj] ^ b32[j];\n      }\n      pos += BLOCK_LEN;\n      continue;\n    }\n    for (let j = 0, posj; j < take; j++) {\n      posj = pos + j;\n      output[posj] = data[posj] ^ block[j];\n    }\n    pos += take;\n  }\n}\n\n/**\n * Creates an ARX stream cipher from a 32-bit core permutation.\n * Used internally to build the exported Salsa and ChaCha stream ciphers.\n * @param core - Core function that fills one keystream block.\n * @param opts - Cipher layout and nonce-extension options. See {@link CipherOpts}.\n * @returns Stream cipher function over byte arrays.\n * @throws If the core callback, key size, counter, or output sizing is invalid. {@link Error}\n */\nexport function createCipher(core: TArg<CipherCoreFn>, opts: TArg<CipherOpts>): TRet<XorStream> {\n  const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts(\n    { allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 },\n    opts\n  );\n  if (typeof core !== 'function') throw new Error('core must be a function');\n  anumber(counterLength);\n  anumber(rounds);\n  abool(counterRight);\n  abool(allowShortKeys);\n  return (\n    key: TArg<Uint8Array>,\n    nonce: TArg<Uint8Array>,\n    data: TArg<Uint8Array>,\n    output?: TArg<Uint8Array>,\n    counter = 0\n  ): TRet<Uint8Array> => {\n    abytes(key, undefined, 'key');\n    abytes(nonce, undefined, 'nonce');\n    abytes(data, undefined, 'data');\n    const len = data.length;\n    // Raw XorStream APIs return ciphertext/plaintext bytes directly, so caller-provided outputs\n    // must match the logical result length exactly instead of returning an oversized workspace.\n    output = getOutput(len, output, false);\n    anumber(counter);\n    // See MAX_COUNTER policy note above: reject advanced explicit-counter requests before any wrap.\n    if (counter < 0 || counter >= MAX_COUNTER) throw new Error('arx: counter overflow');\n    const toClean = [];\n\n    // Key & sigma\n    // key=16 -> sigma16, k=key|key\n    // key=32 -> sigma32, k=key\n    let l = key.length;\n    let k: Uint8Array;\n    let sigma: Uint32Array;\n    if (l === 32) {\n      // Copy caller keys too: big-endian normalization, extended-nonce subkey derivation, and\n      // final clean(...) all mutate or wipe the temporary buffer in place.\n      toClean.push((k = copyBytes(key)));\n      sigma = sigma32_32;\n    } else if (l === 16 && allowShortKeys) {\n      k = new Uint8Array(32);\n      k.set(key);\n      k.set(key, 16);\n      sigma = sigma16_32;\n      toClean.push(k);\n    } else {\n      abytes(key, 32, 'arx key');\n      throw new Error('invalid key size');\n      // throw new Error(`\"arx key\" expected Uint8Array of length 32, got length=${l}`);\n    }\n\n    // Nonce\n    // salsa20:      8   (8-byte counter)\n    // chacha20orig: 8   (8-byte counter)\n    // chacha20:     12  (4-byte counter)\n    // xsalsa20:     24  (16 -> hsalsa,  8 -> old nonce)\n    // xchacha20:    24  (16 -> hchacha, 8 -> old nonce)\n    // Copy before taking u32(...) views on misaligned inputs, and on big-endian so later\n    // swap32IfBE(...) never mutates caller nonce bytes in place.\n    if (!isLE || !isAligned32(nonce)) toClean.push((nonce = copyBytes(nonce)));\n\n    let k32 = u32(k);\n    // hsalsa & hchacha: handle extended nonce\n    if (extendNonceFn) {\n      if (nonce.length !== 24) throw new Error(`arx: extended nonce must be 24 bytes`);\n      const n16 = nonce.subarray(0, 16);\n      if (isLE) extendNonceFn(sigma as TRet<Uint32Array>, k32, u32(n16), k32);\n      else {\n        const sigmaRaw = swap32IfBE(Uint32Array.from(sigma));\n        extendNonceFn(sigmaRaw, k32, u32(n16), k32);\n        clean(sigmaRaw);\n        swap32IfBE(k32);\n      }\n      nonce = nonce.subarray(16);\n    } else if (!isLE) swap32IfBE(k32);\n\n    // Handle nonce counter\n    const nonceNcLen = 16 - counterLength;\n    if (nonceNcLen !== nonce.length)\n      throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);\n\n    // Normalize 64-bit-nonce layouts to the 12-byte core input: ChaCha/XChaCha prefix 4 zero\n    // counter bytes, while Salsa/XSalsa append them after the nonce words.\n    if (nonceNcLen !== 12) {\n      const nc = new Uint8Array(12);\n      nc.set(nonce, counterRight ? 0 : 12 - nonce.length);\n      nonce = nc;\n      toClean.push(nonce);\n    }\n    const n32 = swap32IfBE(u32(nonce));\n    // Ensure temporary key/nonce copies are wiped even if the remaining\n    // runtime guard in runCipher(...) throws on counter overflow.\n    try {\n      runCipher(core, sigma, k32, n32, data, output, counter, rounds);\n      return output as TRet<Uint8Array>;\n    } finally {\n      clean(...toClean);\n    }\n  };\n}\n\n/** Internal class which wraps chacha20 or chacha8 to create CSPRNG. */\nexport class _XorStreamPRG implements PRG {\n  readonly blockLen: number;\n  readonly keyLen: number;\n  readonly nonceLen: number;\n  private state: TRet<Uint8Array>;\n  private buf: TRet<Uint8Array>;\n  private key: TRet<Uint8Array>;\n  private nonce: TRet<Uint8Array>;\n  private pos: number;\n  private ctr: number;\n  private cipher: TArg<XorStream>;\n  constructor(\n    cipher: TArg<XorStream>,\n    blockLen: number,\n    keyLen: number,\n    nonceLen: number,\n    seed: TArg<Uint8Array>\n  ) {\n    this.cipher = cipher;\n    this.blockLen = blockLen;\n    this.keyLen = keyLen;\n    this.nonceLen = nonceLen;\n    this.state = new Uint8Array(this.keyLen + this.nonceLen) as TRet<Uint8Array>;\n    this.reseed(seed);\n    this.ctr = 0;\n    this.pos = this.blockLen;\n    this.buf = new Uint8Array(this.blockLen) as TRet<Uint8Array>;\n    // Keep a single key||nonce backing buffer so reseed/addEntropy/clean update the live cipher\n    // inputs in place through these subarray views.\n    this.key = this.state.subarray(0, this.keyLen) as TRet<Uint8Array>;\n    this.nonce = this.state.subarray(this.keyLen) as TRet<Uint8Array>;\n  }\n  private reseed(seed: TArg<Uint8Array>) {\n    abytes(seed);\n    if (!seed || seed.length === 0) throw new Error('entropy required');\n    // Mix variable-length entropy cyclically across the whole key||nonce state, then restart the\n    // keystream so buffered leftovers from the previous state are never reused.\n    for (let i = 0; i < seed.length; i++) this.state[i % this.state.length] ^= seed[i];\n    this.ctr = 0;\n    this.pos = this.blockLen;\n  }\n  addEntropy(seed: TArg<Uint8Array>): void {\n    // Reject empty entropy before re-keying, otherwise a throwing call would still advance state.\n    abytes(seed);\n    if (seed.length === 0) throw new Error('entropy required');\n    // Re-key from the current stream first, then mix external entropy into the fresh key||nonce\n    // state through reseed() so stale buffered bytes are discarded.\n    this.state.set(this.randomBytes(this.state.length));\n    this.reseed(seed);\n  }\n  randomBytes(len: number): TRet<Uint8Array> {\n    anumber(len);\n    if (len === 0) return new Uint8Array(0) as TRet<Uint8Array>;\n    const avail = this.pos < this.blockLen ? this.blockLen - this.pos : 0;\n    const blocks = Math.ceil(Math.max(0, len - avail) / this.blockLen);\n    // Preflight overflow so failed reads don't partially consume keystream\n    // and leave the PRG repeating blocks.\n    if (blocks > 0 && this.ctr > MAX_COUNTER - blocks) throw new Error('arx: counter overflow');\n    const out = new Uint8Array(len);\n    let outPos = 0;\n    // `out` starts zero-filled, and `buf.fill(0)` below does the same for leftovers: XOR-stream\n    // ciphers then emit raw keystream bytes directly into those buffers.\n    // Serve buffered leftovers first so split reads stay identical to one larger read.\n    if (this.pos < this.blockLen) {\n      const take = Math.min(len, this.blockLen - this.pos);\n      out.set(this.buf.subarray(this.pos, this.pos + take), 0);\n      this.pos += take;\n      outPos += take;\n      if (outPos === len) return out as TRet<Uint8Array>; // fast path\n    }\n    // Full blocks directly to out\n    const full = Math.floor((len - outPos) / this.blockLen);\n    if (full > 0) {\n      const blockBytes = full * this.blockLen;\n      const b = out.subarray(outPos, outPos + blockBytes);\n      this.cipher(this.key, this.nonce, b as TRet<Uint8Array>, b as TRet<Uint8Array>, this.ctr);\n      this.ctr += full;\n      outPos += blockBytes;\n    }\n    // Save leftovers\n    const left = len - outPos;\n    if (left > 0) {\n      this.buf.fill(0);\n      // NOTE: cipher will handle overflow\n      this.cipher(\n        this.key,\n        this.nonce,\n        this.buf as TRet<Uint8Array>,\n        this.buf as TRet<Uint8Array>,\n        this.ctr++\n      );\n      out.set(this.buf.subarray(0, left), outPos);\n      this.pos = left;\n    }\n    return out as TRet<Uint8Array>;\n  }\n  // Clone seeds the new instance from this stream, so the source PRG advances too.\n  clone(): _XorStreamPRG {\n    return new _XorStreamPRG(\n      this.cipher,\n      this.blockLen,\n      this.keyLen,\n      this.nonceLen,\n      this.randomBytes(this.state.length)\n    );\n  }\n  // Zeroes the current state and leftover buffer, but does not make the instance unusable:\n  // Later reads first drain zeros from the cleared buffer and then continue\n  // from zero key||nonce state.\n  clean(): void {\n    this.pos = 0;\n    this.ctr = 0;\n    this.buf.fill(0);\n    this.state.fill(0);\n  }\n}\n\n/**\n * PRG constructor backed by an ARX stream cipher.\n * @param seed - Optional seed bytes mixed into the initial state. When omitted, exactly 32\n * random bytes are mixed in by default: larger states keep a zero tail, while smaller states\n * wrap those bytes through `reseed()`'s XOR schedule.\n * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.\n */\nexport type XorPRG = (seed?: TArg<Uint8Array>) => TRet<_XorStreamPRG>;\n\n/**\n * Creates a PRG constructor from a stream cipher.\n * @param cipher - Stream cipher used to fill output blocks.\n * @param blockLen - Keystream block length in bytes.\n * @param keyLen - Internal key length in bytes.\n * @param nonceLen - Internal nonce length in bytes.\n * @returns PRG factory for seeded concrete `_XorStreamPRG` instances.\n * @example\n * Builds a PRG from XChaCha20 and reads bytes from a randomly seeded instance.\n * ```ts\n * import { xchacha20 } from '@noble/ciphers/chacha.js';\n * import { createPRG } from '@noble/ciphers/_arx.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(32);\n * const init = createPRG(xchacha20, 64, 32, 24);\n * const prg = init(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const createPRG = (\n  cipher: TArg<XorStream>,\n  blockLen: number,\n  keyLen: number,\n  nonceLen: number\n): TRet<XorPRG> => {\n  return ((seed: TArg<Uint8Array> = randomBytes(32)): TRet<_XorStreamPRG> =>\n    new _XorStreamPRG(\n      cipher,\n      blockLen,\n      keyLen,\n      nonceLen,\n      seed\n    ) as TRet<_XorStreamPRG>) as TRet<XorPRG>;\n};\n", "/**\n * Poly1305 ({@link https://cr.yp.to/mac/poly1305-20050329.pdf | PDF},\n * {@link https://en.wikipedia.org/wiki/Poly1305 | wiki})\n * is a fast and parallel secret-key message-authentication code suitable for\n * a wide variety of applications. It was standardized in\n * {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and is now used in TLS 1.3.\n *\n * Polynomial MACs are not perfect for every situation:\n * they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.\n * See {@link https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/ | the invisible salamanders attack writeup}.\n * To combat invisible salamanders, `hash(key)` can be included in ciphertext,\n * however, this would violate ciphertext indistinguishability:\n * an attacker would know which key was used - so `HKDF(key, i)`\n * could be used instead.\n *\n * Check out the {@link https://cr.yp.to/mac.html | original website}.\n * Based on public-domain {@link https://github.com/floodyberry/poly1305-donna | poly1305-donna}.\n * @module\n */\n// prettier-ignore\nimport {\n  abytes, aexists, aoutput, bytesToHex,\n  clean, concatBytes, copyBytes, hexToNumber, numberToBytesBE,\n  wrapMacConstructor, type CMac, type IHash2, type TArg, type TRet\n} from './utils.ts';\n\n// Little-endian 2-byte load used by the Poly1305 limb decomposition.\nfunction u8to16(a: TArg<Uint8Array>, i: number) {\n  return (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);\n}\n\nfunction bytesToNumberLE(bytes: TArg<Uint8Array>): bigint {\n  return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\n\n/** Small version of `poly1305` without loop unrolling. Unused, provided for auditability. */\nfunction poly1305_small(msg: TArg<Uint8Array>, key: TArg<Uint8Array>): TRet<Uint8Array> {\n  abytes(msg);\n  abytes(key, 32, 'key');\n  const POW_2_130_5 = BigInt(2) ** BigInt(130) - BigInt(5); // 2^130-5\n  const POW_2_128_1 = BigInt(2) ** BigInt(128) - BigInt(1); // 2^128-1\n  const CLAMP_R = BigInt('0x0ffffffc0ffffffc0ffffffc0fffffff');\n  const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R;\n  const s = bytesToNumberLE(key.subarray(16));\n  // Process by 16 byte chunks\n  let acc = BigInt(0);\n  for (let i = 0; i < msg.length; i += 16) {\n    const m = msg.subarray(i, i + 16);\n    // RFC 8439 \u00A72.5.1 / RFC 7539 \u00A72.5.1 append [0x01] to each chunk before multiplying by r.\n    const n = bytesToNumberLE(m) | (BigInt(1) << BigInt(8 * m.length));\n    acc = ((acc + n) * r) % POW_2_130_5;\n  }\n  const res = (acc + s) & POW_2_128_1;\n  // RFC 8439 \u00A72.5 / RFC 7539 \u00A72.5 serialize the low 128 bits in little-endian order.\n  return numberToBytesBE(res, 16).reverse() as TRet<Uint8Array>; // LE\n}\n\n// Can be used to replace `computeTag` in chacha.ts. Unused, provided for auditability.\n// @ts-expect-error\nfunction poly1305_computeTag_small(\n  authKey: TArg<Uint8Array>,\n  // AEAD trailer must already be the 16-byte length block:\n  // 8-byte little-endian AAD length || 8-byte little-endian ciphertext length.\n  lengths: TArg<Uint8Array>,\n  ciphertext: TArg<Uint8Array>,\n  AAD?: TArg<Uint8Array>\n): TRet<Uint8Array> {\n  // RFC 8439 \u00A72.8.1 / RFC 7539 \u00A72.8.1 MAC input is\n  // AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || lengths.\n  const res = [];\n  const updatePadded2 = (msg: TArg<Uint8Array>) => {\n    res.push(msg);\n    const leftover = msg.length % 16;\n    // RFC 8439 \u00A72.8.1 / RFC 7539 \u00A72.8.1: pad16(x) is empty for aligned\n    // inputs, else 16-(len%16) zero bytes.\n    if (leftover) res.push(new Uint8Array(16).slice(leftover));\n  };\n  if (AAD) updatePadded2(AAD);\n  updatePadded2(ciphertext);\n  res.push(lengths);\n  return poly1305_small(concatBytes(...res), authKey);\n}\n\n/**\n * Incremental Poly1305 MAC state.\n * Prefer `poly1305()` for one-shot use.\n * @param key - 32-byte Poly1305 one-time key.\n * @example\n * Feeds one chunk into an incremental Poly1305 state with a fresh one-time key.\n *\n * ```ts\n * import { Poly1305 } from '@noble/ciphers/_poly1305.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const mac = new Poly1305(key);\n * mac.update(new Uint8Array([1, 2, 3]));\n * mac.digest();\n * ```\n */\nexport class Poly1305 implements IHash2 {\n  readonly blockLen = 16;\n  readonly outputLen = 16;\n  private buffer = new Uint8Array(16);\n  private r = new Uint16Array(10); // Allocating 1 array with .subarray() here is slower than 3\n  private h = new Uint16Array(10);\n  private pad = new Uint16Array(8);\n  private pos = 0;\n  protected finished = false;\n  protected destroyed = false;\n\n  // Can be speed-up using BigUint64Array, at the cost of complexity\n  constructor(key: TArg<Uint8Array>) {\n    key = copyBytes(abytes(key, 32, 'key'));\n    const t0 = u8to16(key, 0);\n    const t1 = u8to16(key, 2);\n    const t2 = u8to16(key, 4);\n    const t3 = u8to16(key, 6);\n    const t4 = u8to16(key, 8);\n    const t5 = u8to16(key, 10);\n    const t6 = u8to16(key, 12);\n    const t7 = u8to16(key, 14);\n\n    // RFC 8439 \u00A72.5.1 / RFC 7539 \u00A72.5.1 clamp r before multiplication.\n    // These masks unpack that clamped value into 13-bit limbs, while pad\n    // keeps the raw s half for finalize().\n    // {@link https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47 | poly1305-donna reference}\n    this.r[0] = t0 & 0x1fff;\n    this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n    this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n    this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n    this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n    this.r[5] = (t4 >>> 1) & 0x1ffe;\n    this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n    this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n    this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n    this.r[9] = (t7 >>> 5) & 0x007f;\n    for (let i = 0; i < 8; i++) this.pad[i] = u8to16(key, 16 + 2 * i);\n  }\n\n  private process(data: TArg<Uint8Array>, offset: number, isLast = false) {\n    // RFC 8439 \u00A72.5 / \u00A72.5.1 and RFC 7539 \u00A72.5 / \u00A72.5.1 add an extra high\n    // bit to every full 16-byte block. The final partial block gets its\n    // explicit `1` byte during digestInto(), so `hibit` stays zero there.\n    const hibit = isLast ? 0 : 1 << 11;\n    const { h, r } = this;\n    const r0 = r[0];\n    const r1 = r[1];\n    const r2 = r[2];\n    const r3 = r[3];\n    const r4 = r[4];\n    const r5 = r[5];\n    const r6 = r[6];\n    const r7 = r[7];\n    const r8 = r[8];\n    const r9 = r[9];\n\n    const t0 = u8to16(data, offset + 0);\n    const t1 = u8to16(data, offset + 2);\n    const t2 = u8to16(data, offset + 4);\n    const t3 = u8to16(data, offset + 6);\n    const t4 = u8to16(data, offset + 8);\n    const t5 = u8to16(data, offset + 10);\n    const t6 = u8to16(data, offset + 12);\n    const t7 = u8to16(data, offset + 14);\n\n    let h0 = h[0] + (t0 & 0x1fff);\n    let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);\n    let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);\n    let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);\n    let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);\n    let h5 = h[5] + ((t4 >>> 1) & 0x1fff);\n    let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);\n    let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);\n    let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);\n    let h9 = h[9] + ((t7 >>> 5) | hibit);\n\n    let c = 0;\n\n    let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);\n    c = d0 >>> 13;\n    d0 &= 0x1fff;\n    d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);\n    c += d0 >>> 13;\n    d0 &= 0x1fff;\n\n    let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);\n    c = d1 >>> 13;\n    d1 &= 0x1fff;\n    d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);\n    c += d1 >>> 13;\n    d1 &= 0x1fff;\n\n    let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);\n    c = d2 >>> 13;\n    d2 &= 0x1fff;\n    d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);\n    c += d2 >>> 13;\n    d2 &= 0x1fff;\n\n    let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);\n    c = d3 >>> 13;\n    d3 &= 0x1fff;\n    d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);\n    c += d3 >>> 13;\n    d3 &= 0x1fff;\n\n    let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;\n    c = d4 >>> 13;\n    d4 &= 0x1fff;\n    d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);\n    c += d4 >>> 13;\n    d4 &= 0x1fff;\n\n    let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;\n    c = d5 >>> 13;\n    d5 &= 0x1fff;\n    d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);\n    c += d5 >>> 13;\n    d5 &= 0x1fff;\n\n    let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;\n    c = d6 >>> 13;\n    d6 &= 0x1fff;\n    d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);\n    c += d6 >>> 13;\n    d6 &= 0x1fff;\n\n    let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;\n    c = d7 >>> 13;\n    d7 &= 0x1fff;\n    d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);\n    c += d7 >>> 13;\n    d7 &= 0x1fff;\n\n    let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;\n    c = d8 >>> 13;\n    d8 &= 0x1fff;\n    d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);\n    c += d8 >>> 13;\n    d8 &= 0x1fff;\n\n    let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;\n    c = d9 >>> 13;\n    d9 &= 0x1fff;\n    d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;\n    c += d9 >>> 13;\n    d9 &= 0x1fff;\n\n    c = ((c << 2) + c) | 0;\n    c = (c + d0) | 0;\n    d0 = c & 0x1fff;\n    c = c >>> 13;\n    d1 += c;\n\n    h[0] = d0;\n    h[1] = d1;\n    h[2] = d2;\n    h[3] = d3;\n    h[4] = d4;\n    h[5] = d5;\n    h[6] = d6;\n    h[7] = d7;\n    h[8] = d8;\n    h[9] = d9;\n  }\n\n  private finalize() {\n    const { h, pad } = this;\n    const g = new Uint16Array(10);\n    let c = h[1] >>> 13;\n    h[1] &= 0x1fff;\n    for (let i = 2; i < 10; i++) {\n      h[i] += c;\n      c = h[i] >>> 13;\n      h[i] &= 0x1fff;\n    }\n    h[0] += c * 5;\n    c = h[0] >>> 13;\n    h[0] &= 0x1fff;\n    h[1] += c;\n    c = h[1] >>> 13;\n    h[1] &= 0x1fff;\n    h[2] += c;\n\n    // RFC 8439 \u00A72.5 / RFC 7539 \u00A72.5 reduce modulo 2^130-5 before repacking\n    // to 16-bit words and adding the raw s half.\n    g[0] = h[0] + 5;\n    c = g[0] >>> 13;\n    g[0] &= 0x1fff;\n    for (let i = 1; i < 10; i++) {\n      g[i] = h[i] + c;\n      c = g[i] >>> 13;\n      g[i] &= 0x1fff;\n    }\n    g[9] -= 1 << 13;\n\n    let mask = (c ^ 1) - 1;\n    for (let i = 0; i < 10; i++) g[i] &= mask;\n    mask = ~mask;\n    for (let i = 0; i < 10; i++) h[i] = (h[i] & mask) | g[i];\n    h[0] = (h[0] | (h[1] << 13)) & 0xffff;\n    h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;\n    h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;\n    h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;\n    h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;\n    h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;\n    h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;\n    h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;\n\n    let f = h[0] + pad[0];\n    h[0] = f & 0xffff;\n    for (let i = 1; i < 8; i++) {\n      f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;\n      h[i] = f & 0xffff;\n    }\n    clean(g);\n  }\n  update(data: TArg<Uint8Array>): this {\n    aexists(this);\n    abytes(data);\n    data = copyBytes(data);\n    const { buffer, blockLen } = this;\n    const len = data.length;\n\n    for (let pos = 0; pos < len; ) {\n      const take = Math.min(blockLen - this.pos, len - pos);\n      // Fast path: we have at least one block in input\n      if (take === blockLen) {\n        for (; blockLen <= len - pos; pos += blockLen) this.process(data, pos);\n        continue;\n      }\n      buffer.set(data.subarray(pos, pos + take), this.pos);\n      this.pos += take;\n      pos += take;\n      if (this.pos === blockLen) {\n        this.process(buffer, 0, false);\n        this.pos = 0;\n      }\n    }\n    return this;\n  }\n  destroy(): void {\n    // `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.\n    this.destroyed = true;\n    clean(this.h, this.r, this.buffer, this.pad);\n  }\n  digestInto(out: TArg<Uint8Array>): void {\n    aexists(this);\n    aoutput(out, this);\n    this.finished = true;\n    const { buffer, h } = this;\n    let { pos } = this;\n    if (pos) {\n      // RFC 8439 \u00A72.5 / RFC 7539 \u00A72.5: the final short block appends a\n      // single `0x01` byte and zero-fills the remaining bytes before the\n      // last multiplication step.\n      buffer[pos++] = 1;\n      for (; pos < 16; pos++) buffer[pos] = 0;\n      this.process(buffer, 0, true);\n    }\n    this.finalize();\n    let opos = 0;\n    for (let i = 0; i < 8; i++) {\n      out[opos++] = h[i] >>> 0;\n      out[opos++] = h[i] >>> 8;\n    }\n  }\n  digest(): TRet<Uint8Array> {\n    const { buffer, outputLen } = this;\n    this.digestInto(buffer);\n    // Copy out before destroy() zeroes the internal buffer.\n    const res = buffer.slice(0, outputLen);\n    this.destroy();\n    return res as TRet<Uint8Array>;\n  }\n}\n\n/** One-shot keyed hash helper with `.create()`. */\nexport type CHash = CMac<Poly1305>;\n\n/**\n * Poly1305 MAC from RFC 8439.\n * @param msg - Message bytes to authenticate.\n * @param key - 32-byte Poly1305 one-time key.\n * @returns 16-byte authentication tag.\n * @example\n * Authenticates one message with a one-shot Poly1305 call and a fresh key.\n *\n * ```ts\n * import { poly1305 } from '@noble/ciphers/_poly1305.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * poly1305(new Uint8Array(), key);\n * ```\n */\nexport const poly1305: TRet<CHash> = /* @__PURE__ */ wrapMacConstructor(\n  32,\n  (key: TArg<Uint8Array>) => new Poly1305(key)\n);\n", "/**\n * ChaCha stream cipher, released\n * in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.\n * It was standardized in\n * {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and\n * is now used in TLS 1.3.\n *\n * {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | XChaCha20}\n * extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with\n * randomly-generated nonces.\n *\n * Check out\n * {@link http://cr.yp.to/chacha/chacha-20080128.pdf | PDF},\n * {@link https://en.wikipedia.org/wiki/Salsa20 | wiki}, and\n * {@link https://cr.yp.to/chacha.html | website}.\n *\n * @module\n */\nimport { type XorPRG, createCipher, createPRG, rotl } from './_arx.ts';\nimport { poly1305 } from './_poly1305.ts';\nimport {\n  type ARXCipher,\n  type CipherWithOutput,\n  type TArg,\n  type TRet,\n  type XorStream,\n  abytes,\n  clean,\n  equalBytes,\n  getOutput,\n  swap8IfBE,\n  swap32IfBE,\n  u64Lengths,\n  wrapCipher,\n} from './utils.ts';\n\n/**\n * ChaCha core function. It is implemented twice:\n * 1. Simple loop (chachaCore_small, hchacha_small)\n * 2. Unrolled loop (chachaCore, hchacha) - 4x faster, but larger & harder to read\n * The specific implementation is selected in `createCipher` below.\n */\n\n/** RFC 8439 \u00A72.1 quarter round on words a, b, c, d. */\n// prettier-ignore\nfunction chachaQR(x: TArg<Uint32Array>, a: number, b: number, c: number, d: number) {\n  x[a] = (x[a] + x[b]) | 0; x[d] = rotl(x[d] ^ x[a], 16);\n  x[c] = (x[c] + x[d]) | 0; x[b] = rotl(x[b] ^ x[c], 12);\n  x[a] = (x[a] + x[b]) | 0; x[d] = rotl(x[d] ^ x[a], 8);\n  x[c] = (x[c] + x[d]) | 0; x[b] = rotl(x[b] ^ x[c], 7);\n}\n\n/** Repeated ChaCha double rounds; callers are expected to pass an even round count. */\nfunction chachaRound(x: TArg<Uint32Array>, rounds = 20) {\n  for (let r = 0; r < rounds; r += 2) {\n    // RFC 8439 \u00A72.3 / \u00A72.3.1 inner_block: four column rounds, then four diagonal rounds.\n    chachaQR(x, 0, 4, 8, 12);\n    chachaQR(x, 1, 5, 9, 13);\n    chachaQR(x, 2, 6, 10, 14);\n    chachaQR(x, 3, 7, 11, 15);\n    chachaQR(x, 0, 5, 10, 15);\n    chachaQR(x, 1, 6, 11, 12);\n    chachaQR(x, 2, 7, 8, 13);\n    chachaQR(x, 3, 4, 9, 14);\n  }\n}\n\n// Shared scratch for the auditability-only helper below; only the test-only\n// __TESTS.chachaCore_small hook reaches it, so production exports stay reentrant.\nconst ctmp = /* @__PURE__ */ new Uint32Array(16);\n\n/** Small version of chacha without loop unrolling. Unused, provided for auditability. */\n// prettier-ignore\nfunction chacha(\n  s: TArg<Uint32Array>, k: TArg<Uint32Array>, i: TArg<Uint32Array>, out: TArg<Uint32Array>,\n  isHChacha: boolean = true, rounds: number = 20\n): void {\n  // `i` is either `[counter, nonce0, nonce1, nonce2]` for the ChaCha block\n  // function or the full 128-bit nonce prefix for the HChaCha subkey path.\n  // Create initial array using common pattern\n  const y = Uint32Array.from([\n    s[0], s[1], s[2], s[3], // \"expa\"   \"nd 3\"  \"2-by\"  \"te k\"\n    k[0], k[1], k[2], k[3], // Key      Key     Key     Key\n    k[4], k[5], k[6], k[7], // Key      Key     Key     Key\n    i[0], i[1], i[2], i[3], // Counter  Counter Nonce   Nonce\n  ]);\n  const x = ctmp;\n  x.set(y);\n  chachaRound(x, rounds);\n\n  // HChaCha writes words 0..3 and 12..15 after the rounds; the ChaCha\n  // block path adds the original state word-by-word.\n  if (isHChacha) {\n    const xindexes = [0, 1, 2, 3, 12, 13, 14, 15];\n    for (let i = 0; i < 8; i++) out[i] = x[xindexes[i]];\n  } else {\n    for (let i = 0; i < 16; i++) out[i] = (y[i] + x[i]) | 0;\n  }\n}\n\n/** Identical to `chachaCore`. Reached only through the test-only `__TESTS` export. */\n// @ts-ignore\nconst chachaCore_small: typeof chachaCore = (s, k, n, out, cnt, rounds) =>\n  // Keep the reference wrapper on the same [counter, nonce0, nonce1, nonce2] layout as chacha().\n  chacha(s, k, Uint32Array.from([cnt, n[0], n[1], n[2]]), out, false, rounds);\n/** Identical to `hchacha`. Unused. */\n// @ts-ignore\nconst hchacha_small: typeof hchacha = chacha;\n\n/** RFC 8439 \u00A72.3 block core for `state = constants | key | counter | nonce`. */\n// prettier-ignore\nfunction chachaCore(\n  s: TArg<Uint32Array>, k: TArg<Uint32Array>, n: TArg<Uint32Array>, out: TArg<Uint32Array>, cnt: number, rounds = 20\n): void {\n  let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // \"expa\"   \"nd 3\"  \"2-by\"  \"te k\"\n      y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key      Key     Key     Key\n      y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key      Key     Key     Key\n      y12 = cnt,  y13 = n[0], y14 = n[1], y15 = n[2];  // Counter  Nonce   Nonce   Nonce\n  // Save state to temporary variables\n  let x00 = y00, x01 = y01, x02 = y02, x03 = y03,\n      x04 = y04, x05 = y05, x06 = y06, x07 = y07,\n      x08 = y08, x09 = y09, x10 = y10, x11 = y11,\n      x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n  for (let r = 0; r < rounds; r += 2) {\n    x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);\n    x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);\n    x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);\n    x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);\n\n    x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);\n    x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);\n    x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);\n    x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);\n\n    x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);\n    x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);\n    x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8);\n    x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);\n\n    x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);\n    x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);\n    x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)\n    x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);\n\n    x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);\n    x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);\n    x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);\n    x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);\n\n    x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);\n    x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);\n    x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);\n    x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);\n\n    x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);\n    x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);\n    x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);\n    x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);\n\n    x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)\n    x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);\n    x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);\n    x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);\n  }\n  // RFC 8439 \u00A72.3 / \u00A72.3.1: add the original state words back in state order.\n  let oi = 0;\n  out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0;\n  out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0;\n  out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0;\n  out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0;\n  out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0;\n  out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0;\n  out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0;\n  out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0;\n}\n/**\n * hchacha hashes key and nonce into key' and nonce' for xchacha20.\n * Algorithmically identical to `hchacha_small`, but this exported path\n * normalizes word order on big-endian hosts.\n * Need to find a way to merge it with `chachaCore` without 25% performance hit.\n * @param s - Sigma constants as 32-bit words.\n * @param k - Key words.\n * @param i - Nonce-prefix words.\n * @param out - Output buffer for the derived subkey.\n * @example\n * Derives the XChaCha subkey from sigma, key, and nonce-prefix words.\n *\n * ```ts\n * const sigma = new Uint32Array(4);\n * const key = new Uint32Array(8);\n * const nonce = new Uint32Array(4);\n * const out = new Uint32Array(8);\n * hchacha(sigma, key, nonce, out);\n * ```\n */\n// prettier-ignore\nexport function hchacha(\n  s: TArg<Uint32Array>, k: TArg<Uint32Array>, i: TArg<Uint32Array>, out: TArg<Uint32Array>\n): void {\n  let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(s[1]), x02 = swap8IfBE(s[2]), x03 = swap8IfBE(s[3]),\n      x04 = swap8IfBE(k[0]), x05 = swap8IfBE(k[1]), x06 = swap8IfBE(k[2]), x07 = swap8IfBE(k[3]),\n      x08 = swap8IfBE(k[4]), x09 = swap8IfBE(k[5]), x10 = swap8IfBE(k[6]), x11 = swap8IfBE(k[7]),\n      x12 = swap8IfBE(i[0]), x13 = swap8IfBE(i[1]), x14 = swap8IfBE(i[2]), x15 = swap8IfBE(i[3]);\n  for (let r = 0; r < 20; r += 2) {\n    x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);\n    x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);\n    x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);\n    x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);\n\n    x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);\n    x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);\n    x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);\n    x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);\n\n    x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);\n    x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);\n    x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8);\n    x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);\n\n    x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);\n    x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);\n    x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)\n    x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);\n\n    x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);\n    x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);\n    x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);\n    x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);\n\n    x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);\n    x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);\n    x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);\n    x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);\n\n    x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);\n    x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);\n    x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);\n    x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);\n\n    x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)\n    x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);\n    x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);\n    x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);\n  }\n  // HChaCha derives the subkey from state words 0..3 and 12..15 after 20 rounds.\n  let oi = 0;\n  out[oi++] = x00; out[oi++] = x01;\n  out[oi++] = x02; out[oi++] = x03;\n  out[oi++] = x12; out[oi++] = x13;\n  out[oi++] = x14; out[oi++] = x15;\n  swap32IfBE(out);\n}\n\n/**\n * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.\n * The nonce/counter layout still reserves 8 counter bytes internally, but the shared public\n * `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`\n * near `MAX_COUNTER` for the full counter-policy rationale.\n * @param key - 16-byte or 32-byte key.\n * @param nonce - 8-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Encrypts bytes with the original 8-byte-nonce ChaCha variant and a fresh key/nonce.\n *\n * ```ts\n * import { chacha20orig } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(8);\n * chacha20orig(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha20orig: TRet<XorStream> = /* @__PURE__ */ createCipher(chachaCore, {\n  counterRight: false,\n  counterLength: 8,\n  allowShortKeys: true,\n});\n/**\n * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.\n * With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Encrypts bytes with the RFC 8439 ChaCha20 stream cipher and a fresh key/nonce.\n *\n * ```ts\n * import { chacha20 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * chacha20(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha20: TRet<XorStream> = /* @__PURE__ */ createCipher(chachaCore, {\n  counterRight: false,\n  counterLength: 4,\n  allowShortKeys: false,\n});\n\n/**\n * XChaCha eXtended-nonce ChaCha. With 24-byte nonce, it's safe to make it random (CSPRNG).\n * See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.\n * The nonce/counter layout still reserves 8 counter bytes internally, but the shared public\n * `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`\n * near `MAX_COUNTER` for the full counter-policy rationale.\n * @param key - 32-byte key.\n * @param nonce - 24-byte extended nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Encrypts bytes with XChaCha20 using a fresh key and random 24-byte nonce.\n *\n * ```ts\n * import { xchacha20 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(24);\n * xchacha20(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const xchacha20: TRet<XorStream> = /* @__PURE__ */ createCipher(chachaCore, {\n  counterRight: false,\n  counterLength: 8,\n  extendNonceFn: hchacha,\n  allowShortKeys: false,\n});\n\n/**\n * Reduced 8-round chacha, described in original paper.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Uses the reduced 8-round variant for non-critical workloads with a fresh key/nonce.\n *\n * ```ts\n * import { chacha8 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * chacha8(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha8: TRet<XorStream> = /* @__PURE__ */ createCipher(chachaCore, {\n  counterRight: false,\n  counterLength: 4,\n  rounds: 8,\n});\n\n/**\n * Reduced 12-round chacha, described in original paper.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Uses the reduced 12-round variant for non-critical workloads with a fresh key/nonce.\n *\n * ```ts\n * import { chacha12 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * chacha12(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha12: TRet<XorStream> = /* @__PURE__ */ createCipher(chachaCore, {\n  counterRight: false,\n  counterLength: 4,\n  rounds: 12,\n});\n\n// Test-only hooks for keeping the simple/reference core aligned with the unrolled production core.\nexport const __TESTS: {\n  chachaCore_small: typeof chachaCore_small;\n  chachaCore: typeof chachaCore;\n} = /* @__PURE__ */ Object.freeze({ chachaCore_small, chachaCore });\n\n// RFC 8439 \u00A72.8.1 pad16(x): shared zero block for AAD/ciphertext padding.\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\n// RFC 8439 \u00A72.8 / \u00A72.8.1: aligned inputs add nothing, otherwise append 16-(len%16) zero bytes.\nconst updatePadded = (h: ReturnType<typeof poly1305.create>, msg: TArg<Uint8Array>) => {\n  h.update(msg);\n  const leftover = msg.length % 16;\n  if (leftover) h.update(ZEROS16.subarray(leftover));\n};\n\n// RFC 8439 \u00A72.6.1 poly1305_key_gen returns `block[0..31]`, so AEAD key\n// generation only needs 32 zero bytes.\nconst ZEROS32 = /* @__PURE__ */ new Uint8Array(32);\nfunction computeTag(\n  fn: TArg<XorStream>,\n  key: TArg<Uint8Array>,\n  nonce: TArg<Uint8Array>,\n  ciphertext: TArg<Uint8Array>,\n  AAD?: TArg<Uint8Array>\n): TRet<Uint8Array> {\n  if (AAD !== undefined) abytes(AAD, undefined, 'AAD');\n  // RFC 8439 \u00A72.6 / \u00A72.8: derive the Poly1305 one-time key from counter 0,\n  // then MAC AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || len(AAD) || len(ciphertext).\n  const authKey = fn(\n    key as TRet<Uint8Array>,\n    nonce as TRet<Uint8Array>,\n    ZEROS32 as TRet<Uint8Array>\n  );\n  const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);\n\n  // Methods below can be replaced with\n  // return poly1305_computeTag_small(authKey, lengths, ciphertext, AAD)\n  const h = poly1305.create(authKey);\n  if (AAD) updatePadded(h, AAD);\n  updatePadded(h, ciphertext);\n  h.update(lengths);\n  const res = h.digest();\n  clean(authKey, lengths);\n  return res;\n}\n\n/**\n * AEAD algorithm from RFC 8439.\n * Salsa20 and chacha (RFC 8439) use poly1305 differently.\n * We could have composed them, but it's hard because of authKey:\n * In salsa20, authKey changes position in salsa stream.\n * In chacha, authKey can't be computed inside computeTag, it modifies the counter.\n */\nexport const _poly1305_aead =\n  (xorStream: TArg<XorStream>) =>\n  (key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>): CipherWithOutput => {\n    // This borrows caller key/nonce/AAD buffers by reference; mutating them after construction\n    // changes future encrypt/decrypt results.\n    const tagLength = 16;\n    return {\n      encrypt(plaintext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array> {\n        const plength = plaintext.length;\n        output = getOutput(plength + tagLength, output, false);\n        output.set(plaintext);\n        const oPlain = output.subarray(0, -tagLength);\n        // RFC 8439 \u00A72.8: payload encryption starts at counter 1 because counter 0 produced the OTK.\n        xorStream(\n          key as TRet<Uint8Array>,\n          nonce as TRet<Uint8Array>,\n          oPlain as TRet<Uint8Array>,\n          oPlain as TRet<Uint8Array>,\n          1\n        );\n        const tag = computeTag(xorStream, key, nonce, oPlain, AAD);\n        output.set(tag, plength); // append tag\n        clean(tag);\n        return output as TRet<Uint8Array>;\n      },\n      decrypt(ciphertext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array> {\n        output = getOutput(ciphertext.length - tagLength, output, false);\n        const data = ciphertext.subarray(0, -tagLength);\n        const passedTag = ciphertext.subarray(-tagLength);\n        const tag = computeTag(xorStream, key, nonce, data, AAD);\n        // RFC 8439 \u00A72.8 / \u00A74: authenticate ciphertext before decrypting it, and compare tags with\n        // the constant-time equalBytes() helper rather than decrypting speculative plaintext first.\n        if (!equalBytes(passedTag, tag)) {\n          clean(tag);\n          throw new Error('invalid tag');\n        }\n        output.set(ciphertext.subarray(0, -tagLength));\n        // Actual decryption\n        xorStream(\n          key as TRet<Uint8Array>,\n          nonce as TRet<Uint8Array>,\n          output as TRet<Uint8Array>,\n          output as TRet<Uint8Array>,\n          1\n        ); // start stream with i=1\n        clean(tag);\n        return output as TRet<Uint8Array>;\n      },\n    };\n  };\n\n/**\n * ChaCha20-Poly1305 from RFC 8439.\n *\n * Unsafe to use random nonces under the same key, due to collision chance.\n * Prefer XChaCha instead.\n * @param key - 32-byte key.\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.\n *\n * ```ts\n * import { chacha20poly1305 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * const cipher = chacha20poly1305(key, nonce);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const chacha20poly1305: TRet<ARXCipher> = /* @__PURE__ */ wrapCipher(\n  { blockSize: 64, nonceLength: 12, tagLength: 16 },\n  /* @__PURE__ */ _poly1305_aead(chacha20)\n);\n/**\n * XChaCha20-Poly1305 extended-nonce chacha.\n *\n * Can be safely used with random nonces (CSPRNG).\n * See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.\n * @param key - 32-byte key.\n * @param nonce - 24-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 random 24-byte nonce.\n *\n * ```ts\n * import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(24);\n * const cipher = xchacha20poly1305(key, nonce);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const xchacha20poly1305: TRet<ARXCipher> = /* @__PURE__ */ wrapCipher(\n  { blockSize: 64, nonceLength: 24, tagLength: 16 },\n  /* @__PURE__ */ _poly1305_aead(xchacha20)\n);\n\n/**\n * Chacha20 CSPRNG (cryptographically secure pseudorandom number generator).\n * It's best to limit usage to non-production, non-critical cases: for example, test-only.\n * Compatible with libtomcrypt. It does not have a specification, so unclear how secure it is.\n * @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,\n * only 32 random bytes are mixed into the 40-byte state.\n * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.\n * @example\n * Seeds the test-only ChaCha20 DRBG from fresh entropy.\n *\n * ```ts\n * import { rngChacha20 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(32);\n * const prg = rngChacha20(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const rngChacha20: TRet<XorPRG> = /* @__PURE__ */ createPRG(chacha20orig, 64, 32, 8);\n/**\n * Chacha20/8 CSPRNG (cryptographically secure pseudorandom number generator).\n * It's best to limit usage to non-production, non-critical cases: for example, test-only.\n * Faster than `rngChacha20`.\n * @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,\n * only 32 random bytes are mixed into the 44-byte state.\n * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.\n * @example\n * Seeds the faster test-only ChaCha8 DRBG from fresh entropy.\n *\n * ```ts\n * import { rngChacha8 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(32);\n * const prg = rngChacha8(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const rngChacha8: TRet<XorPRG> = /* @__PURE__ */ createPRG(chacha8, 64, 32, 12);\n", "import { Convert } from '@enbox/common';\nimport { xchacha20poly1305 } from '@noble/ciphers/chacha.js';\n\nimport type { Jwk } from '../jose/jwk.js';\n\nimport { getWebcryptoSubtle } from './webcrypto.js';\nimport { computeJwkThumbprint, isOctPrivateJwk } from '../jose/jwk.js';\n\n/**\n * Constant defining the length of the authentication tag in bytes for XChaCha20-Poly1305.\n *\n * @remarks\n * The `POLY1305_TAG_LENGTH` is set to 16 bytes (128 bits), which is the standard size for the\n * Poly1305 authentication tag in XChaCha20-Poly1305 encryption. This tag length ensures\n * a strong level of security for message authentication, verifying the integrity and\n * authenticity of the data during decryption.\n */\nexport const POLY1305_TAG_LENGTH = 16;\n\n/**\n * The `XChaCha20Poly1305` class provides a suite of utilities for cryptographic operations\n * using the XChaCha20-Poly1305 algorithm, a combination of the XChaCha20 stream cipher and the\n * Poly1305 message authentication code (MAC). This class encompasses methods for key generation,\n * encryption, decryption, and conversions between raw byte arrays and JSON Web Key (JWK) formats.\n *\n * XChaCha20-Poly1305 is renowned for its high security and efficiency, especially in scenarios\n * involving large data volumes or where data integrity and confidentiality are paramount. The\n * extended nonce size of XChaCha20 reduces the risks of nonce reuse, while Poly1305 provides\n * a strong MAC ensuring data integrity.\n *\n * Key Features:\n * - Key Generation: Generate XChaCha20-Poly1305 symmetric keys in JWK format.\n * - Key Conversion: Transform keys between raw byte arrays and JWK formats.\n * - Encryption: Encrypt data using XChaCha20-Poly1305, returning both ciphertext and MAC tag.\n * - Decryption: Decrypt data and verify integrity using the XChaCha20-Poly1305 algorithm.\n *\n * The methods in this class are asynchronous, returning Promises to accommodate various\n * JavaScript environments.\n *\n * @example\n * ```ts\n * // Key Generation\n * const privateKey = await XChaCha20Poly1305.generateKey();\n *\n * // Encryption\n * const data = new TextEncoder().encode('Messsage');\n * const nonce = utils.randomBytes(24); // 24-byte nonce\n * const additionalData = new TextEncoder().encode('Associated data');\n * const { ciphertext, tag } = await XChaCha20Poly1305.encrypt({\n *   data,\n *   nonce,\n *   additionalData,\n *   key: privateKey\n * });\n *\n * // Decryption\n * const decryptedData = await XChaCha20Poly1305.decrypt({\n *   data: ciphertext,\n *   nonce,\n *   tag,\n *   additionalData,\n *   key: privateKey\n * });\n *\n * // Key Conversion\n * const privateKeyBytes = await XChaCha20Poly1305.privateKeyToBytes({ privateKey });\n * ```\n */\nexport class XChaCha20Poly1305 {\n  /**\n   * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method takes a symmetric key represented as a byte array (Uint8Array) and converts it into\n   * a JWK object for use with the XChaCha20-Poly1305 algorithm. The process involves encoding the\n   * key into base64url format and setting the appropriate JWK parameters.\n   *\n   * The resulting JWK object includes the following properties:\n   * - `kty`: Key Type, set to 'oct' for Octet Sequence (representing a symmetric key).\n   * - `k`: The symmetric key, base64url-encoded.\n   * - `kid`: Key ID, generated based on the JWK thumbprint.\n   *\n   * @example\n   * ```ts\n   * const privateKeyBytes = new Uint8Array([...]); // Replace with actual symmetric key bytes\n   * const privateKey = await XChaCha20Poly1305.bytesToPrivateKey({ privateKeyBytes });\n   * ```\n   *\n   * @param params - The parameters for the symmetric key conversion.\n   * @param params.privateKeyBytes - The raw symmetric key as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the symmetric key in JWK format.\n   */\n  public static async bytesToPrivateKey({ privateKeyBytes }: {\n    privateKeyBytes: Uint8Array;\n  }): Promise<Jwk> {\n    // Construct the private key in JWK format.\n    const privateKey: Jwk = {\n      k   : Convert.uint8Array(privateKeyBytes).toBase64Url(),\n      kty : 'oct'\n    };\n\n    // Compute the JWK thumbprint and set as the key ID.\n    privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n    return privateKey;\n  }\n\n  /**\n   * Decrypts the provided data using XChaCha20-Poly1305.\n   *\n   * @remarks\n   * This method performs XChaCha20-Poly1305 decryption on the given encrypted data using the\n   * specified key, nonce, and authentication tag. It supports optional additional authenticated\n   * data (AAD) for enhanced security. The nonce must be 24 bytes long, consistent with XChaCha20's\n   * specifications.\n   *\n   * @example\n   * ```ts\n   * const encryptedData = new Uint8Array([...]); // Encrypted data\n   * const nonce = new Uint8Array(24); // 24-byte nonce\n   * const additionalData = new Uint8Array([...]); // Optional AAD\n   * const key = { ... }; // A Jwk object representing the XChaCha20-Poly1305 key\n   * const decryptedData = await XChaCha20Poly1305.decrypt({\n   *   data: encryptedData,\n   *   nonce,\n   *   additionalData,\n   *   key\n   * });\n   * ```\n   *\n   * @param params - The parameters for the decryption operation.\n   * @param params.data - The encrypted data to decrypt including the authentication tag,\n   *                      represented as a Uint8Array.\n   * @param params.key - The key to use for decryption, represented in JWK format.\n   * @param params.nonce - The nonce used during the encryption process.\n   * @param params.additionalData - Optional additional authenticated data.\n   *\n   * @returns A Promise that resolves to the decrypted data as a Uint8Array.\n   */\n  public static async decrypt({ data, key, nonce, additionalData }: {\n    additionalData?: Uint8Array;\n    data: Uint8Array;\n    key: Jwk;\n    nonce: Uint8Array;\n  }): Promise<Uint8Array> {\n    // Convert the private key from JWK format to bytes.\n    const privateKeyBytes = await XChaCha20Poly1305.privateKeyToBytes({ privateKey: key });\n\n    return XChaCha20Poly1305.decryptRaw({ data, keyBytes: privateKeyBytes, nonce, additionalData });\n  }\n\n  /**\n   * Decrypts data using XChaCha20-Poly1305 with a raw byte array key.\n   *\n   * @remarks\n   * This is a lower-level method that accepts the key as a raw `Uint8Array` instead of a JWK.\n   * It is useful in scenarios where the key material is already in byte form (e.g., derived\n   * from ECDH + HKDF) and constructing a JWK would add unnecessary overhead.\n   *\n   * @param params - The parameters for the decryption operation.\n   * @param params.data - The encrypted data including the authentication tag.\n   * @param params.keyBytes - The 256-bit (32-byte) decryption key as a Uint8Array.\n   * @param params.nonce - The 24-byte nonce used during encryption.\n   * @param params.additionalData - Optional additional authenticated data.\n   *\n   * @returns A Promise that resolves to the decrypted plaintext as a Uint8Array.\n   */\n  public static async decryptRaw({ data, keyBytes, nonce, additionalData }: {\n    additionalData?: Uint8Array;\n    data: Uint8Array;\n    keyBytes: Uint8Array;\n    nonce: Uint8Array;\n  }): Promise<Uint8Array> {\n    const xc20p = xchacha20poly1305(keyBytes, nonce, additionalData);\n    const plaintext = xc20p.decrypt(data);\n\n    return plaintext;\n  }\n\n  /**\n   * Encrypts the provided data using XChaCha20-Poly1305.\n   *\n   * @remarks\n   * This method performs XChaCha20-Poly1305 encryption on the given data using the specified key\n   * and nonce. It supports optional additional authenticated data (AAD) for enhanced security. The\n   * nonce must be 24 bytes long, as per XChaCha20's specifications. The method returns the\n   * encrypted data along with an authentication tag as a Uint8Array, ensuring both confidentiality\n   * and integrity of the data.\n   *\n   * @example\n   * ```ts\n   * const data = new TextEncoder().encode('Messsage');\n   * const nonce = utils.randomBytes(24); // 24-byte nonce\n   * const additionalData = new TextEncoder().encode('Associated data'); // Optional AAD\n   * const key = { ... }; // A Jwk object representing an XChaCha20-Poly1305 key\n   * const encryptedData = await XChaCha20Poly1305.encrypt({\n   *   data,\n   *   nonce,\n   *   additionalData,\n   *   key\n   * });\n   * ```\n   *\n   * @param params - The parameters for the encryption operation.\n   * @param params.data - The data to encrypt, represented as a Uint8Array.\n   * @param params.key - The key to use for encryption, represented in JWK format.\n   * @param params.nonce - A 24-byte nonce for the encryption process.\n   * @param params.additionalData - Optional additional authenticated data.\n   *\n   * @returns A Promise that resolves to a byte array containing the encrypted data and the\n   *          authentication tag.\n   */\n  public static async encrypt({ data, key, nonce, additionalData }: {\n    additionalData?: Uint8Array;\n    data: Uint8Array;\n    key: Jwk;\n    nonce: Uint8Array;\n  }): Promise<Uint8Array> {\n    // Convert the private key from JWK format to bytes.\n    const privateKeyBytes = await XChaCha20Poly1305.privateKeyToBytes({ privateKey: key });\n\n    return XChaCha20Poly1305.encryptRaw({ data, keyBytes: privateKeyBytes, nonce, additionalData });\n  }\n\n  /**\n   * Encrypts data using XChaCha20-Poly1305 with a raw byte array key.\n   *\n   * @remarks\n   * This is a lower-level method that accepts the key as a raw `Uint8Array` instead of a JWK.\n   * It is useful in scenarios where the key material is already in byte form (e.g., derived\n   * from ECDH + HKDF) and constructing a JWK would add unnecessary overhead.\n   *\n   * The returned `Uint8Array` contains the ciphertext followed by the 16-byte Poly1305\n   * authentication tag.\n   *\n   * @param params - The parameters for the encryption operation.\n   * @param params.data - The plaintext data to encrypt.\n   * @param params.keyBytes - The 256-bit (32-byte) encryption key as a Uint8Array.\n   * @param params.nonce - A 24-byte nonce for the encryption process.\n   * @param params.additionalData - Optional additional authenticated data.\n   *\n   * @returns A Promise that resolves to the ciphertext + authentication tag as a Uint8Array.\n   */\n  public static async encryptRaw({ data, keyBytes, nonce, additionalData }: {\n    additionalData?: Uint8Array;\n    data: Uint8Array;\n    keyBytes: Uint8Array;\n    nonce: Uint8Array;\n  }): Promise<Uint8Array> {\n    const xc20p = xchacha20poly1305(keyBytes, nonce, additionalData);\n    const ciphertext = xc20p.encrypt(data);\n\n    return ciphertext;\n  }\n\n  /**\n   * Generates a symmetric key for XChaCha20-Poly1305 in JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method creates a new symmetric key suitable for use with the XChaCha20-Poly1305 algorithm.\n   * The key is generated using cryptographically secure random number generation to ensure its\n   * uniqueness and security. The XChaCha20-Poly1305 algorithm requires a 256-bit key (32 bytes),\n   * and this method adheres to that specification.\n   *\n   * Key components included in the JWK:\n   * - `kty`: Key Type, set to 'oct' for Octet Sequence.\n   * - `k`: The symmetric key component, base64url-encoded.\n   * - `kid`: Key ID, generated based on the JWK thumbprint.\n   *\n   * @example\n   * ```ts\n   * const privateKey = await XChaCha20Poly1305.generateKey();\n   * ```\n   *\n   * @returns A Promise that resolves to the generated symmetric key in JWK format.\n   */\n  public static async generateKey(): Promise<Jwk> {\n    // Get the Web Crypto API interface.\n    const webCrypto = getWebcryptoSubtle();\n\n    // Generate a random private key.\n    // See https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#usage_notes for\n    // an explanation for why Web Crypto generateKey() is used instead of getRandomValues().\n    const webCryptoKey = await webCrypto.generateKey( { name: 'AES-CTR', length: 256 }, true, ['encrypt']);\n\n    // Export the private key in JWK format.\n    const { alg, ext, key_ops, ...privateKey } = await webCrypto.exportKey('jwk', webCryptoKey);\n\n    // Compute the JWK thumbprint and set as the key ID.\n    privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n    return privateKey;\n  }\n\n  /**\n   * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n   *\n   * This method takes a symmetric key in JWK format and extracts its raw byte representation.\n   * It decodes the 'k' parameter of the JWK value, which represents the symmetric key in base64url\n   * encoding, into a byte array.\n   *\n   * @example\n   * ```ts\n   * const privateKey = { ... }; // A symmetric key in JWK format\n   * const privateKeyBytes = await XChaCha20Poly1305.privateKeyToBytes({ privateKey });\n   * ```\n   *\n   * @param params - The parameters for the symmetric key conversion.\n   * @param params.privateKey - The symmetric key in JWK format.\n   *\n   * @returns A Promise that resolves to the symmetric key as a Uint8Array.\n   */\n  public static async privateKeyToBytes({ privateKey }: {\n    privateKey: Jwk;\n  }): Promise<Uint8Array> {\n    // Verify the provided JWK represents a valid oct private key.\n    if (!isOctPrivateJwk(privateKey)) {\n      throw new Error(`XChaCha20Poly1305: The provided key is not a valid oct private key.`);\n    }\n\n    // Decode the provided private key to bytes.\n    const privateKeyBytes = Convert.base64Url(privateKey.k).toUint8Array();\n\n    return privateKeyBytes;\n  }\n}\n", "import type { TypedArray } from '@noble/hashes/utils.js';\n\nimport { concatBytes } from '@noble/hashes/utils.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { Convert, universalTypeOf } from '@enbox/common';\n\n/**\n * ConcatKDF FixedInfo Parameters.\n *\n * This implementation follows the recommended format for `FixedInfo` specified in section 5.8.2\n * of the NIST.800-56A publication.\n *\n * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Ar3.pdf | NIST.800-56A}\n * @see {@link https://datatracker.ietf.org/doc/html/rfc7518#section-4.6.2 | RFC 7518, Section 4.6.2}\n */\nexport type ConcatKdfFixedInfo = {\n  /**\n   * The algorithm the derived secret keying material will be used with.\n   */\n  algorithmId: string;\n\n  /**\n   * Information related to party U (initiator) involved in the key agreement\n   * transaction. It could be a public key, identifier, or any other data.\n   */\n  partyUInfo: string | TypedArray;\n\n  /**\n   * Information related to party V (receiver) involved in the key\n   * agreement transaction. Similar to partyUInfo, it could be a\n   * public key, identifier, etc.\n   */\n  partyVInfo: string | TypedArray;\n\n  /**\n   * Optional field. It is usually used to ensure the uniqueness of the\n   * derived keying material when the input keying material is used in\n   * multiple key-derivation key-agreement transactions. It is usually\n   * a public value such as the keyDataLen.\n   */\n  suppPubInfo?: number;\n\n  /**\n   * Optional field. It is used when it is desired to secretively\n   * bind additional information into the derived keying material.\n   * It is a secret value agreed upon by the entities who are party\n   * to the key agreement.\n   */\n  suppPrivInfo?: string | TypedArray;\n};\n\n/**\n * An implementation of the Concatenation Key Derivation Function (ConcatKDF)\n * as specified in NIST.800-56A, a single-step key-derivation function (SSKDF).\n * ConcatKDF produces a derived key from a secret key (like a shared secret\n * from ECDH), and other optional public information. This implementation\n * specifically uses SHA-256 as the pseudorandom function (PRF).\n *\n * Note: This implementation allows for only a single round / repetition using the function\n *       `K(1) = H(counter || Z || FixedInfo)`, where:\n *   - `K(1)` is the derived key material after one round\n *   - `H` is the SHA-256 hashing function\n *   - `counter` is a 32-bit, big-endian bit string counter set to 0x00000001\n *   - `Z` is the shared secret value obtained from a key agreement protocol\n *   - `FixedInfo` is a bit string used to ensure that the derived keying material is adequately\n *     \"bound\" to the key-agreement transaction.\n *\n * @example\n * ```ts\n * // Key Derivation\n * const derivedKeyingMaterial = await ConcatKdf.deriveKey({\n *   sharedSecret: utils.randomBytes(32),\n *   keyDataLen: 128,\n *   fixedInfo: {\n *     algorithmId: \"A128GCM\",\n *     partyUInfo: \"Alice\",\n *     partyVInfo: \"Bob\",\n *     suppPubInfo: 128,\n *   },\n * });\n * ```\n *\n * Additional Information:\n *\n * `Z`, or \"shared secret\":\n *   The shared secret value obtained from a key agreement protocol, such as\n *   Diffie-Hellman, ECDH (Elliptic Curve Diffie-Hellman). Importantly, this\n *   shared secret is not directly used as the encryption or authentication\n *   key, but as an input to a key derivation function (KDF), such as Concat\n *   KDF, to generate the actual key. This adds an extra layer of security, as\n *   even if the shared secret gets compromised, the actual  encryption or\n *   authentication key stays safe. This shared secret `Z` value is kept\n *   confidential between the two parties in the key agreement protocol.\n *\n * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Ar3.pdf | NIST.800-56A}\n * @see {@link https://datatracker.ietf.org/doc/html/rfc7518#section-4.6.2 | RFC 7518, Section 4.6.2}\n */\nexport class ConcatKdf {\n  /**\n   * Derives a key of a specified length from the input parameters.\n   *\n   * @example\n   * ```ts\n   * // Key Derivation\n   * const derivedKeyingMaterial = await ConcatKdf.deriveKey({\n   *   sharedSecret: utils.randomBytes(32),\n   *   keyDataLen: 128,\n   *   fixedInfo: {\n   *     algorithmId: \"A128GCM\",\n   *     partyUInfo: \"Alice\",\n   *     partyVInfo: \"Bob\",\n   *     suppPubInfo: 128,\n   *   },\n   * });\n   * ```\n   *\n   * @param params - Input parameters for key derivation.\n   * @param params.keyDataLen - The desired length of the derived key in bits.\n   * @param params.sharedSecret - The shared secret key to derive from.\n   * @param params.fixedInfo - Additional public information to use in key derivation.\n   * @returns The derived key as a Uint8Array.\n   *\n   * @throws {Error} If the `keyDataLen` would require multiple rounds.\n   */\n  public static async deriveKey({ keyDataLen, fixedInfo, sharedSecret }: {\n    keyDataLen: number;\n    fixedInfo: ConcatKdfFixedInfo;\n    sharedSecret: Uint8Array;\n  }): Promise<Uint8Array> {\n    // RFC 7518 Section 4.6.2 specifies using SHA-256 for ECDH key agreement:\n    // \"Key derivation is performed using the Concat KDF, as defined in\n    // Section 5.8.1 of [NIST.800-56A], where the Digest Method is SHA-256.\"\n    // Reference: https://tools.ietf.org/html/rfc7518#section-4.6.2\n    const hashLen = 256;\n\n    // This implementation only supports single round Concat KDF.\n    const roundCount = Math.ceil(keyDataLen / hashLen);\n    if (roundCount !== 1) {\n      throw new Error(`Concat KDF with ${roundCount} rounds not supported.`);\n    }\n\n    // Initialize a 32-bit, big-endian bit string counter as 0x00000001.\n    const counter = new Uint8Array(4);\n    new DataView(counter.buffer).setUint32(0, roundCount);\n\n    // Compute the FixedInfo bit-string.\n    const fixedInfoBytes = ConcatKdf.computeFixedInfo(fixedInfo);\n\n    // Compute K(i) = H(counter || Z || FixedInfo)\n    // return concatBytes(counter, sharedSecretZ, fixedInfo);\n    const derivedKeyingMaterial = sha256(concatBytes(counter, sharedSecret, fixedInfoBytes));\n\n    // Return the bit string of derived keying material of length keyDataLen bits.\n    return derivedKeyingMaterial.slice(0, keyDataLen / 8);\n  }\n\n  /**\n   * Computes the `FixedInfo` parameter for Concat KDF, which binds the derived key material to the\n   * context of the key agreement transaction.\n   *\n   * @remarks\n   * This implementation follows the recommended format for `FixedInfo` specified in section\n   * 5.8.1.2.1 of the NIST.800-56A publication.\n   *\n   * `FixedInfo` is a bit string equal to the following concatenation:\n   * `AlgorithmID || PartyUInfo || PartyVInfo {|| SuppPubInfo }{|| SuppPrivInfo }`.\n   *\n   * `SuppPubInfo` is the key length in bits, big endian encoded as a 32-bit number. For example,\n   * 128 would be [0, 0, 0, 128] and 256 would be [0, 0, 1, 0].\n   *\n   * @param params - Input data to construct FixedInfo.\n   * @returns FixedInfo as a Uint8Array.\n   */\n  private static computeFixedInfo(params:\n    ConcatKdfFixedInfo\n  ): Uint8Array {\n    // Required sub-fields.\n    const algorithmId = ConcatKdf.toDataLenData({ data: params.algorithmId });\n    const partyUInfo = ConcatKdf.toDataLenData({ data: params.partyUInfo });\n    const partyVInfo = ConcatKdf.toDataLenData({ data: params.partyVInfo });\n    // Optional sub-fields.\n    const suppPubInfo = ConcatKdf.toDataLenData({ data: params.suppPubInfo, variableLength: false });\n    const suppPrivInfo = ConcatKdf.toDataLenData({ data: params.suppPrivInfo });\n\n    // Concatenate AlgorithmID || PartyUInfo || PartyVInfo || SuppPubInfo || SuppPrivInfo.\n    const fixedInfo = concatBytes(algorithmId, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo);\n\n    return fixedInfo;\n  }\n\n  /**\n   * Encodes input data as a length-prefixed byte string, or\n   * as a fixed-length bit string if specified.\n   *\n   * If variableLength = true, return the data in the form Datalen || Data,\n   * where Data is a variable-length string of zero or more (eight-bit)\n   * bytes, and Datalen is a fixed-length, big-endian counter that\n   * indicates the length (in bytes) of Data.\n   *\n   * If variableLength = false, return the data formatted as a\n   * fixed-length bit string.\n   *\n   * @param params - Input data and options for the conversion.\n   * @param params.data - The input data to encode. Must be a type convertible to Uint8Array by the Convert class.\n   * @param params.variableLength - Whether to output the data as variable length. Default is true.\n   *\n   * @returns The input data encoded as a Uint8Array.\n   *\n   * @throws {TypeError} If fixed-length data is not a number.\n   */\n  private static toDataLenData({ data, variableLength = true }: {\n    data: unknown;\n    variableLength?: boolean;\n  }): Uint8Array {\n    let encodedData: Uint8Array;\n    const dataType = universalTypeOf(data);\n\n    // Return an emtpy octet sequence if data is not specified.\n    if (dataType === 'Undefined') {\n      return new Uint8Array(0);\n    }\n\n    if (variableLength) {\n      const dataU8A = (dataType === 'Uint8Array')\n        ? data as Uint8Array\n        : new Convert(data, dataType).toUint8Array();\n      const bufferLength = dataU8A.length;\n      encodedData = new Uint8Array(4 + bufferLength);\n      new DataView(encodedData.buffer).setUint32(0, bufferLength);\n      encodedData.set(dataU8A, 4);\n\n    } else {\n      if (typeof data !== 'number') {\n        throw TypeError('Fixed length input must be a number.');\n      }\n      encodedData = new Uint8Array(4);\n      new DataView(encodedData.buffer).setUint32(0, data);\n    }\n\n    return encodedData;\n  }\n}", "import type { Jwk } from '../jwk.js';\nimport type { KeyIdentifier } from '../../types/identifier.js';\nimport type { JweEnc, JweHeaderParams } from './header.js';\n\nimport { Convert } from '@enbox/common';\n\nimport { AesGcm } from '../../primitives/aes-gcm.js';\nimport { AesKw } from '../../primitives/aes-kw.js';\nimport { ConcatKdf } from '../../primitives/concat-kdf.js';\nimport { Hkdf } from '../../primitives/hkdf.js';\nimport { Pbkdf2 } from '../../primitives/pbkdf2.js';\nimport { X25519 } from '../../primitives/x25519.js';\nimport { XChaCha20Poly1305 } from '../../primitives/xchacha20-poly1305.js';\nimport { CryptoError, CryptoErrorCode } from '../../crypto-error.js';\n\n/**\n * The HKDF \"info\" value used by the optional PIN-strengthening KDF wrapper applied to an\n * ECDH-ES derived Content Encryption Key.\n */\nconst ECDH_ES_PIN_KDF_INFO = 'enbox/connect/v2/pin';\n\n/**\n * The PBES2 family of \"alg\" (Algorithm) Header Parameter values supported by this engine.\n */\ntype Pbes2Alg = 'PBES2-HS256+A128KW' | 'PBES2-HS384+A192KW' | 'PBES2-HS512+A256KW';\n\n/**\n * Maps each supported \"enc\" (Encryption Algorithm) Header Parameter value to the length in bits\n * of the Content Encryption Key it requires.\n */\nconst CEK_BIT_LENGTH_BY_ENC: Record<JweEnc, number> = {\n  'A128GCM' : 128,\n  'A192GCM' : 192,\n  'A256GCM' : 256,\n  'XC20P'   : 256,\n};\n\n/**\n * Key management input for encrypting with `\"alg\": \"ECDH-ES\"` (Direct Key Agreement).\n *\n * A fresh ephemeral X25519 key pair is generated for every encrypt operation and the public key\n * is placed in the JWE Protected Header as the \"epk\" parameter.\n */\nexport type JweEcdhEsEncryptKey = {\n  /** Discriminates ECDH-ES key management input from JWK / Key Identifier / passphrase inputs. */\n  mode: 'ecdh-es';\n\n  /** The recipient's static X25519 public key in JWK format. */\n  peerPublicKey: Jwk;\n\n  /**\n   * Optional PIN used to strengthen the derived Content Encryption Key. The PIN never transits:\n   * when provided, the CEK is passed through HKDF-SHA256 with salt UTF8(pin) and\n   * info UTF8('enbox/connect/v2/pin') after Concat KDF derivation. A recipient using the wrong\n   * PIN derives a different CEK and fails closed with an AEAD authentication tag failure.\n   */\n  pin?: string;\n};\n\n/**\n * Key management input for decrypting with `\"alg\": \"ECDH-ES\"` (Direct Key Agreement).\n */\nexport type JweEcdhEsDecryptKey = {\n  /** Discriminates ECDH-ES key management input from JWK / Key Identifier / passphrase inputs. */\n  mode: 'ecdh-es';\n\n  /** The recipient's static X25519 private key in JWK format. */\n  privateKey: Jwk;\n\n  /** {@inheritDoc JweEcdhEsEncryptKey.pin} */\n  pin?: string;\n};\n\n/**\n * The key management key material accepted by {@link JweKeyManagement.decrypt}.\n */\nexport type JweKeyManagementDecryptKey = KeyIdentifier | Jwk | Uint8Array | JweEcdhEsDecryptKey;\n\n/**\n * The key management key material accepted by {@link JweKeyManagement.encrypt}.\n */\nexport type JweKeyManagementEncryptKey = KeyIdentifier | Jwk | Uint8Array | JweEcdhEsEncryptKey;\n\n/**\n * Represents the result of the JWE key management encryption process, encapsulating the Content\n * Encryption Key (CEK) and optionally the encrypted CEK.\n */\nexport interface JweKeyManagementEncryptResult {\n  /**\n   * The Content Encryption Key (CEK) used for encrypting the JWE payload. It can be a Key\n   * Identifier such as a KMS URI or a JSON Web Key (JWK).\n   */\n  cek: KeyIdentifier | Jwk;\n\n  /**\n   * The encrypted version of the CEK, provided as a byte array. The encrypted version of the CEK\n   * is returned for all key management modes other than \"dir\" (Direct Encryption Mode) and\n   * \"ECDH-ES\" (Direct Key Agreement Mode).\n   */\n  encryptedKey?: Uint8Array;\n\n  /**\n   * Header parameters produced during key management (e.g. the ECDH-ES \"epk\" value) that MUST be\n   * merged into the JWE Protected Header before it is encoded so that they are covered by the\n   * Additional Authenticated Data.\n   */\n  headerParams?: Partial<JweHeaderParams>;\n}\n\n/**\n * Defines the parameters required to decrypt a JWE encrypted key, including the key management\n * details.\n */\nexport interface JweKeyManagementDecryptParams {\n  /**\n   * The decryption key which can be a Key Identifier such as a KMS key URI, a JSON Web Key (JWK),\n   * raw key material represented as a byte array, or an ECDH-ES key agreement input.\n   */\n  key: JweKeyManagementDecryptKey;\n\n  /**\n   * The encrypted key extracted from the JWE, represented as a byte array. This parameter is\n   * optional and is used when the key is wrapped.\n   */\n  encryptedKey?: Uint8Array;\n\n  /**\n   * The JWE header parameters that define the characteristics of the decryption process, specifying\n   * the algorithm and encryption method among other settings.\n   */\n  joseHeader: JweHeaderParams;\n}\n\n/**\n * Defines the parameters required for encrypting a JWE CEK, including the key management details.\n */\nexport interface JweKeyManagementEncryptParams {\n  /**\n   * The encryption key which can be a Key Identifier such as a KMS key URI, a JSON Web Key (JWK),\n   * raw key material represented as a byte array, or an ECDH-ES key agreement input.\n   */\n  key: JweKeyManagementEncryptKey;\n\n  /**\n   * The JWE header parameters that define the characteristics of the encryption process, specifying\n   * the algorithm and encryption method among other settings.\n   */\n  joseHeader: JweHeaderParams;\n}\n\n/**\n * Type guard function that checks whether the given key management key is an ECDH-ES key\n * agreement input (either the encrypt-side or decrypt-side shape).\n */\nfunction isJweEcdhEsKey(key: unknown): key is JweEcdhEsEncryptKey | JweEcdhEsDecryptKey {\n  return typeof key === 'object' && key !== null\n    && 'mode' in key && key.mode === 'ecdh-es';\n}\n\n/**\n * Generates a random Content Encryption Key (CEK) in JWK format for the given \"enc\" (Encryption\n * Algorithm) Header Parameter value.\n *\n * @param enc - The JWE \"enc\" value identifying the content encryption algorithm.\n * @returns A Promise that resolves to the generated CEK in JWK format.\n * @throws {@link CryptoError} with code `AlgorithmNotSupported` if the \"enc\" value is not\n *         supported.\n */\nexport async function generateCek(enc: string): Promise<Jwk> {\n  switch (enc) {\n    case 'A128GCM':\n    case 'A192GCM':\n    case 'A256GCM':\n      return await AesGcm.generateKey({ length: CEK_BIT_LENGTH_BY_ENC[enc] as 128 | 192 | 256 });\n\n    case 'XC20P':\n      return await XChaCha20Poly1305.generateKey();\n\n    default:\n      throw new CryptoError(\n        CryptoErrorCode.AlgorithmNotSupported,\n        `Unsupported \"enc\" (Encryption Algorithm) Header Parameter value: ${enc}`\n      );\n  }\n}\n\n/**\n * The `JweKeyManagement` class implements the key management aspects of JSON Web Encryption (JWE)\n * as specified in {@link https://datatracker.ietf.org/doc/html/rfc7516 | RFC 7516}.\n *\n * It supports algorithms for encrypting and decrypting keys, thereby enabling the secure\n * transmission of information where the payload is encrypted, and the encryption key is also\n * encrypted or agreed upon using key agreement techniques.\n *\n * The choice of algorithm is determined by the \"alg\" parameter in the JWE\n * header, and the class is designed to handle the intricacies associated with each algorithm,\n * ensuring the secure handling of the encryption keys.\n *\n * Supported algorithms include:\n * - `\"dir\"`: Direct Encryption Mode\n * - `\"ECDH-ES\"`: Direct Key Agreement Mode using Elliptic Curve Diffie-Hellman Ephemeral Static\n *   (X25519 only) with the Concat KDF, per RFC 7518, Section 4.6.\n * - `\"PBES2-HS256+A128KW\"`, `\"PBES2-HS384+A192KW\"`, `\"PBES2-HS512+A256KW\"`: Password-Based\n *   Encryption Mode with Key Wrapping (PBES2) using HMAC-SHA and AES Key Wrap algorithms for key\n *   wrapping and encryption.\n *\n * @example\n * ```ts\n * // To encrypt a key:\n * const keyEncryptionKey = Convert.string(passphrase).toUint8Array();\n * const { cek, encryptedKey: encryptedCek } = await JweKeyManagement.encrypt({\n *   key        : keyEncryptionKey,\n *   joseHeader : {\n *     alg : 'PBES2-HS512+A256KW',\n *     enc : 'A256GCM',\n *     p2c : 210_000,\n *     p2s : Convert.uint8Array(saltInput).toBase64Url()\n *   }\n * });\n *\n * // To decrypt a key:\n * const cek = await JweKeyManagement.decrypt({\n *   key          : keyEncryptionKey,\n *   encryptedKey : encryptedCek,\n *   joseHeader   : {\n *     alg : 'PBES2-HS512+A256KW',\n *     enc : 'A256GCM',\n *     p2c : 210_000,\n *     p2s : Convert.uint8Array(saltInput).toBase64Url()\n *   }\n * });\n * ```\n */\nexport class JweKeyManagement {\n  /**\n   * Decrypts the encrypted key (JWE Encrypted Key) using the specified key encryption algorithm\n   * defined in the JWE Header's \"alg\" parameter.\n   *\n   * This method supports multiple key management algorithms, including Direct Encryption (dir),\n   * Direct Key Agreement (ECDH-ES), and PBES2 schemes with key wrapping.\n   *\n   * The method takes a key, which can be a Key Identifier, JWK, raw byte array, or ECDH-ES key\n   * agreement input, and the encrypted key along with the JWE header. It returns the decrypted\n   * Content Encryption Key (CEK) which can then be used to decrypt the JWE ciphertext.\n   *\n   * @example\n   * ```ts\n   * // Decrypting the CEK with the PBES2-HS512+A256KW algorithm\n   * const cek = await JweKeyManagement.decrypt({\n   *   key          : Convert.string(passphrase).toUint8Array(),\n   *   encryptedKey : encryptedCek,\n   *   joseHeader   : {\n   *     alg : 'PBES2-HS512+A256KW',\n   *     enc : 'A256GCM',\n   *     p2c : 210_000,\n   *     p2s : Convert.uint8Array(saltInput).toBase64Url(),\n   *   }\n   * });\n   * ```\n   *\n   * @param params - The decryption parameters.\n   * @param options - Options controlling decryption constraints (e.g. the minimum acceptable\n   *                  PBES2 iteration count).\n   * @throws Throws an error if the key management algorithm is not supported or if required\n   *         parameters are missing or invalid.\n   */\n  public static async decrypt({ key, encryptedKey, joseHeader }: JweKeyManagementDecryptParams,\n    options?: { minP2cCount?: number }\n  ): Promise<KeyIdentifier | Jwk> {\n    const minP2cCount = options?.minP2cCount ?? 1000;\n    // Determine the Key Management Mode employed by the algorithm specified by the \"alg\"\n    // (algorithm) Header Parameter.\n    switch (joseHeader.alg) {\n      case 'dir': {\n        // In Direct Encryption mode, a JWE \"Encrypted Key\" is not provided. Instead, the\n        // provided key management `key` is directly used as the Content Encryption Key (CEK) to\n        // decrypt the JWE payload.\n\n        // Verify that the JWE Encrypted Key value is empty.\n        if (encryptedKey !== undefined) {\n          throw new CryptoError(CryptoErrorCode.InvalidJwe, 'JWE \"encrypted_key\" is not allowed when using \"dir\" (Direct Encryption Mode).');\n        }\n\n        // Verify the key management `key` is a Key Identifier or JWK.\n        if (key instanceof Uint8Array || isJweEcdhEsKey(key)) {\n          throw new CryptoError(CryptoErrorCode.InvalidJwe, 'Key management \"key\" must be a Key URI or JWK when using \"dir\" (Direct Encryption Mode).');\n        }\n\n        // return the key management `key` as the CEK.\n        return key;\n      }\n\n      case 'ECDH-ES': {\n        // In Direct Key Agreement mode (ECDH-ES), a JWE \"Encrypted Key\" is not provided. Instead,\n        // an ECDH shared secret is computed between the recipient's static private key and the\n        // ephemeral public key (\"epk\") from the JOSE Header, and the Content Encryption Key (CEK)\n        // is derived from the shared secret using the Concat KDF per RFC 7518, Section 4.6.\n\n        // Verify that the JWE Encrypted Key value is empty.\n        if (encryptedKey !== undefined) {\n          throw new CryptoError(CryptoErrorCode.InvalidJwe, 'JWE \"encrypted_key\" is not allowed when using \"ECDH-ES\" (Direct Key Agreement Mode).');\n        }\n\n        // Verify the key management `key` is an ECDH-ES decrypt input with a private key.\n        if (!(isJweEcdhEsKey(key) && 'privateKey' in key)) {\n          throw new CryptoError(CryptoErrorCode.InvalidJwe,\n            'Key management \"key\" must be an object with \"mode\": \"ecdh-es\" and \"privateKey\" when using \"ECDH-ES\" (Direct Key Agreement Mode).'\n          );\n        }\n\n        // Only the X25519 curve is supported for ECDH-ES key agreement.\n        if (key.privateKey.crv !== 'X25519') {\n          throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Unsupported ECDH-ES private key curve: ${key.privateKey.crv}`);\n        }\n\n        // Validate the ephemeral public key (\"epk\") from the JOSE Header.\n        const ephemeralPublicKey = JweKeyManagement.validateEpk(joseHeader.epk);\n\n        // Compute the ECDH shared secret between the recipient's static private key and the\n        // ephemeral public key.\n        const sharedSecret = await X25519.sharedSecret({\n          privateKeyA : key.privateKey,\n          publicKeyB  : ephemeralPublicKey\n        });\n\n        // Derive the CEK from the shared secret using the Concat KDF (and the optional PIN\n        // strengthening wrapper).\n        return await JweKeyManagement.deriveEcdhEsCek({ sharedSecret, joseHeader, pin: key.pin });\n      }\n\n      case 'PBES2-HS256+A128KW':\n      case 'PBES2-HS384+A192KW':\n      case 'PBES2-HS512+A256KW': {\n        // In Key Encryption mode (PBES2) with key wrapping (A128KW, A192KW, A256KW), the given\n        // passphrase, salt (p2s), and iteration count (p2c) are used with the PBKDF2 key derivation\n        // function to derive the Key Encryption Key (KEK).  The KEK is then used to decrypt the JWE\n        // Encrypted Key to obtain the Content Encryption Key (CEK).\n\n        if (typeof joseHeader.p2c !== 'number') {\n          throw new CryptoError(CryptoErrorCode.InvalidJwe, 'JOSE Header \"p2c\" (PBES2 Count) is missing or not a number.');\n        }\n\n        // Per RFC 7518, Section 4.8.1.2, a minimum iteration count of 1000 is RECOMMENDED.\n        // Enforce this floor to prevent an attacker from supplying a crafted JWE with a\n        // trivially low iteration count that would weaken key derivation.\n        if (joseHeader.p2c < minP2cCount) {\n          throw new CryptoError(\n            CryptoErrorCode.InvalidJwe,\n            `JOSE Header \"p2c\" (PBES2 Count) is ${joseHeader.p2c}, which is below the minimum of ${minP2cCount}.`\n          );\n        }\n\n        if (typeof joseHeader.p2s !== 'string') {\n          throw new CryptoError(CryptoErrorCode.InvalidJwe, 'JOSE Header \"p2s\" (PBES2 salt) is missing or not a string.');\n        }\n\n        // Throw an error if the key management `key` is not a byte array. For PBES2, the key is\n        // expected to be a low-entropy passphrase as a byte array.\n        if (!(key instanceof Uint8Array)) {\n          throw new CryptoError(CryptoErrorCode.InvalidJwe, 'Key management \"key\" must be a Uint8Array when using \"PBES2\" (Key Encryption Mode).');\n        }\n\n        // Verify that the JWE Encrypted Key value is present.\n        if (encryptedKey === undefined) {\n          throw new CryptoError(CryptoErrorCode.InvalidJwe, 'JWE \"encrypted_key\" is required when using \"PBES2\" (Key Encryption Mode).');\n        }\n\n        // Derive the Key Encryption Key (KEK) from the given passphrase, salt, and iteration count.\n        const kek = await JweKeyManagement.derivePbes2Kek({\n          alg        : joseHeader.alg as Pbes2Alg,\n          passphrase : key,\n          p2c        : joseHeader.p2c,\n          p2s        : joseHeader.p2s\n        });\n\n        // Decrypt the Content Encryption Key (CEK) with the derived KEK.\n        return await AesKw.unwrapKey({\n          decryptionKey       : kek,\n          wrappedKeyBytes     : encryptedKey,\n          wrappedKeyAlgorithm : joseHeader.enc\n        });\n      }\n\n      default: {\n        throw new CryptoError(\n          CryptoErrorCode.AlgorithmNotSupported,\n          `Unsupported \"alg\" (Algorithm) Header Parameter value: ${joseHeader.alg}`\n        );\n      }\n    }\n  }\n\n  /**\n   * Encrypts a Content Encryption Key (CEK) using the key management algorithm specified in the\n   * JWE Header's \"alg\" parameter.\n   *\n   * This method supports various key management algorithms, including Direct Encryption (dir),\n   * Direct Key Agreement (ECDH-ES), and PBES2 with key wrapping.\n   *\n   * For PBES2, it generates a random CEK for the specified encryption algorithm in the JWE header,\n   * which can then be used to encrypt the actual payload, and returns the CEK along with the\n   * encrypted key. For ECDH-ES, it generates a fresh ephemeral X25519 key pair, derives the CEK\n   * from the shared secret, and returns the ephemeral public key as a header parameter that MUST\n   * be merged into the JWE Protected Header.\n   *\n   * @example\n   * ```ts\n   * // Encrypting the CEK with the PBES2-HS512+A256KW algorithm\n   * const { cek, encryptedKey } = await JweKeyManagement.encrypt({\n   *   key        : Convert.string(passphrase).toUint8Array(),\n   *   joseHeader : {\n   *     alg : 'PBES2-HS512+A256KW',\n   *     enc : 'A256GCM',\n   *     p2c : 210_000,\n   *     p2s : Convert.uint8Array(saltInput).toBase64Url(),\n   *   }\n   * });\n   * ```\n   *\n   * @param params - The encryption parameters.\n   * @returns The encrypted key result containing the CEK, optionally the encrypted CEK\n   *          (JWE Encrypted Key), and optionally header parameters that must be added to the JWE\n   *          Protected Header.\n   * @throws Throws an error if the key management algorithm is not supported or if required\n   *         parameters are missing or invalid.\n   */\n  public static async encrypt({ key, joseHeader }: JweKeyManagementEncryptParams\n  ): Promise<JweKeyManagementEncryptResult> {\n    let cek: KeyIdentifier | Jwk;\n    let encryptedKey: Uint8Array | undefined;\n    let headerParams: Partial<JweHeaderParams> | undefined;\n\n    // Determine the Key Management Mode employed by the algorithm specified by the \"alg\"\n    // (algorithm) Header Parameter.\n    switch (joseHeader.alg) {\n      case 'dir': {\n        // In Direct Encryption mode (dir), a JWE \"Encrypted Key\" is not provided. Instead, the\n        // provided key management `key` is directly used as the Content Encryption Key (CEK) to\n        // decrypt the JWE payload.\n\n        // Verify the key management `key` is a Key Identifier or JWK.\n        if (key instanceof Uint8Array || isJweEcdhEsKey(key)) {\n          throw new CryptoError(CryptoErrorCode.InvalidJwe, 'Key management \"key\" must be a Key URI or JWK when using \"dir\" (Direct Encryption Mode).');\n        }\n\n        // Set the CEK to the key management `key`.\n        cek = key;\n\n        break;\n      }\n\n      case 'ECDH-ES': {\n        // In Direct Key Agreement mode (ECDH-ES), a fresh ephemeral X25519 key pair is generated\n        // and an ECDH shared secret is computed between the ephemeral private key and the\n        // recipient's static public key. The Content Encryption Key (CEK) is derived from the\n        // shared secret using the Concat KDF per RFC 7518, Section 4.6, and the ephemeral public\n        // key is placed in the JWE Protected Header as the \"epk\" parameter.\n\n        // Verify the key management `key` is an ECDH-ES encrypt input with a peer public key.\n        if (!(isJweEcdhEsKey(key) && 'peerPublicKey' in key)) {\n          throw new CryptoError(CryptoErrorCode.InvalidJwe,\n            'Key management \"key\" must be an object with \"mode\": \"ecdh-es\" and \"peerPublicKey\" when using \"ECDH-ES\" (Direct Key Agreement Mode).'\n          );\n        }\n\n        // Only the X25519 curve is supported for ECDH-ES key agreement.\n        if (!(key.peerPublicKey.kty === 'OKP' && key.peerPublicKey.crv === 'X25519' && typeof key.peerPublicKey.x === 'string')) {\n          throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported,\n            `Unsupported ECDH-ES peer public key: must be an OKP JWK on the X25519 curve with an \"x\" value.`\n          );\n        }\n\n        // Generate a fresh ephemeral X25519 key pair for this encryption operation.\n        const ephemeralPrivateKey = await X25519.generateKey();\n\n        // Compute the ECDH shared secret between the ephemeral private key and the recipient's\n        // static public key.\n        const sharedSecret = await X25519.sharedSecret({\n          privateKeyA : ephemeralPrivateKey,\n          publicKeyB  : key.peerPublicKey\n        });\n\n        // Derive the CEK from the shared secret using the Concat KDF (and the optional PIN\n        // strengthening wrapper).\n        cek = await JweKeyManagement.deriveEcdhEsCek({ sharedSecret, joseHeader, pin: key.pin });\n\n        // The ephemeral public key MUST be integrity-protected, so return it as a header\n        // parameter to be merged into the JWE Protected Header.\n        headerParams = { epk: { kty: 'OKP', crv: 'X25519', x: ephemeralPrivateKey.x } };\n\n        break;\n      }\n\n      case 'PBES2-HS256+A128KW':\n      case 'PBES2-HS384+A192KW':\n      case 'PBES2-HS512+A256KW': {\n        // In Key Encryption mode (PBES2) with key wrapping (A128KW, A192KW, A256KW), a randomly\n        // generated Content Encryption Key (CEK) is encrypted with a Key Encryption Key (KEK)\n        // derived from the given passphrase, salt (p2s), and iteration count (p2c) using the\n        // PBKDF2 key derivation function.\n\n        if (typeof joseHeader.p2c !== 'number') {\n          throw new CryptoError(CryptoErrorCode.InvalidJwe, 'JOSE Header \"p2c\" (PBES2 Count) is missing or not a number.');\n        }\n\n        if (typeof joseHeader.p2s !== 'string') {\n          throw new CryptoError(CryptoErrorCode.InvalidJwe, 'JOSE Header \"p2s\" (PBES2 salt) is missing or not a string.');\n        }\n\n        // Throw an error if the key management `key` is not a byte array.\n        if (!(key instanceof Uint8Array)) {\n          throw new CryptoError(CryptoErrorCode.InvalidJwe, 'Key management \"key\" must be a Uint8Array when using \"PBES2\" (Key Encryption Mode).');\n        }\n\n        // Generate a random Content Encryption Key (CEK) using the algorithm specified by the \"enc\"\n        // (encryption) Header Parameter.\n        cek = await generateCek(joseHeader.enc);\n\n        // Derive a Key Encryption Key (KEK) from the given passphrase, salt, and iteration count.\n        const kek = await JweKeyManagement.derivePbes2Kek({\n          alg        : joseHeader.alg as Pbes2Alg,\n          passphrase : key,\n          p2c        : joseHeader.p2c,\n          p2s        : joseHeader.p2s\n        });\n\n        // Encrypt the randomly generated CEK with the derived Key Encryption Key (KEK).\n        encryptedKey = await AesKw.wrapKey({ encryptionKey: kek, unwrappedKey: cek });\n\n        break;\n      }\n\n      default: {\n        throw new CryptoError(\n          CryptoErrorCode.AlgorithmNotSupported,\n          `Unsupported \"alg\" (Algorithm) Header Parameter value: ${joseHeader.alg}`\n        );\n      }\n    }\n\n    return { cek, encryptedKey, headerParams };\n  }\n\n  /**\n   * Derives the Content Encryption Key (CEK) for \"ECDH-ES\" (Direct Key Agreement Mode) from an\n   * ECDH shared secret using the Concat KDF, per\n   * {@link https://datatracker.ietf.org/doc/html/rfc7518#section-4.6.2 | RFC 7518, Section 4.6.2}:\n   * - AlgorithmID is the value of the \"enc\" Header Parameter.\n   * - PartyUInfo / PartyVInfo are the decoded values of the \"apu\" / \"apv\" Header Parameters, or\n   *   the empty octet sequence when absent.\n   * - SuppPubInfo is keydatalen, the bit length of the key used by the \"enc\" algorithm.\n   *\n   * When a `pin` is provided, the derived CEK is additionally passed through HKDF-SHA256 with\n   * salt UTF8(pin) and info UTF8('enbox/connect/v2/pin'). The PIN never transits; a recipient\n   * using the wrong PIN derives a different CEK and fails closed with an AEAD authentication tag\n   * failure.\n   *\n   * @param params - The CEK derivation parameters.\n   * @returns A Promise that resolves to the derived CEK in JWK format.\n   * @throws {@link CryptoError} if the shared secret is all zeros (low-order point rejection), the\n   *         \"enc\" value is unsupported, or the \"apu\" / \"apv\" values cannot be decoded.\n   */\n  private static async deriveEcdhEsCek({ sharedSecret, joseHeader, pin }: {\n    sharedSecret: Uint8Array;\n    joseHeader: JweHeaderParams;\n    pin?: string;\n  }): Promise<Jwk> {\n    // Reject an all-zero shared secret, which results from an X25519 exchange with a low-order\n    // public key and would yield an attacker-predictable CEK.\n    if (sharedSecret.every((byte): boolean => byte === 0)) {\n      throw new CryptoError(CryptoErrorCode.InvalidJwe, 'ECDH-ES shared secret must not be all zeros.');\n    }\n\n    // Determine the desired CEK length (keydatalen) from the \"enc\" (Encryption Algorithm)\n    // Header Parameter value.\n    const keyDataLen = CEK_BIT_LENGTH_BY_ENC[joseHeader.enc as JweEnc];\n    if (keyDataLen === undefined) {\n      throw new CryptoError(\n        CryptoErrorCode.AlgorithmNotSupported,\n        `Unsupported \"enc\" (Encryption Algorithm) Header Parameter value: ${joseHeader.enc}`\n      );\n    }\n\n    // Decode the \"apu\" (Agreement PartyUInfo) and \"apv\" (Agreement PartyVInfo) Header Parameters,\n    // which default to the empty octet sequence when absent.\n    const partyUInfo = JweKeyManagement.decodeAgreementParty('apu', joseHeader.apu);\n    const partyVInfo = JweKeyManagement.decodeAgreementParty('apv', joseHeader.apv);\n\n    // Derive the CEK from the shared secret using the Concat KDF.\n    let cekBytes = await ConcatKdf.deriveKey({\n      sharedSecret,\n      keyDataLen,\n      fixedInfo: {\n        algorithmId : joseHeader.enc,\n        partyUInfo,\n        partyVInfo,\n        suppPubInfo : keyDataLen,\n      }\n    });\n\n    // If a PIN was provided, strengthen the CEK with the HKDF-SHA256 PIN wrapper.\n    if (pin !== undefined) {\n      cekBytes = await Hkdf.deriveKeyBytes({\n        baseKeyBytes : cekBytes,\n        hash         : 'SHA-256',\n        salt         : Convert.string(pin).toUint8Array(),\n        info         : Convert.string(ECDH_ES_PIN_KDF_INFO).toUint8Array(),\n        length       : keyDataLen,\n      });\n    }\n\n    // Convert the derived CEK bytes to JWK format using the \"enc\" appropriate converter.\n    return joseHeader.enc === 'XC20P'\n      ? await XChaCha20Poly1305.bytesToPrivateKey({ privateKeyBytes: cekBytes })\n      : await AesGcm.bytesToPrivateKey({ privateKeyBytes: cekBytes });\n  }\n\n  /**\n   * Decodes an agreement party (\"apu\" / \"apv\") Header Parameter from Base64 URL format to a byte\n   * array, returning the empty octet sequence when the parameter is absent.\n   *\n   * @param param - The name of the Header Parameter being decoded; used for error messaging.\n   * @param value - The Base64 URL encoded value of the Header Parameter, if present.\n   * @returns The decoded value as a byte array.\n   * @throws {@link CryptoError} if the value is present but not a properly encoded Base64 URL\n   *         string.\n   */\n  private static decodeAgreementParty(param: string, value?: unknown): Uint8Array {\n    if (value === undefined) {\n      return new Uint8Array(0);\n    }\n\n    try {\n      if (typeof value !== 'string') { throw new Error(); }\n      return Convert.base64Url(value).toUint8Array();\n    } catch {\n      throw new CryptoError(CryptoErrorCode.EncodingError, `Failed to decode the JOSE Header \"${param}\" value from Base64 URL format.`);\n    }\n  }\n\n  /**\n   * Derives the PBES2 Key Encryption Key (KEK) from a passphrase using PBKDF2, per\n   * {@link https://www.rfc-editor.org/rfc/rfc7518.html#section-4.8 | RFC 7518, Section 4.8}.\n   *\n   * The salt value used is (UTF8(Alg) || 0x00 || Salt Input), where Alg is the \"alg\" (algorithm)\n   * Header Parameter value. This reduces the potential for a precomputed dictionary attack (also\n   * known as a rainbow table attack).\n   *\n   * @param params - The KEK derivation parameters.\n   * @returns A Promise that resolves to the derived AES Key Wrap KEK in JWK format.\n   * @throws {@link CryptoError} if the \"p2s\" value cannot be decoded.\n   */\n  private static async derivePbes2Kek({ alg, passphrase, p2c, p2s }: {\n    alg: Pbes2Alg;\n    passphrase: Uint8Array;\n    p2c: number;\n    p2s: string;\n  }): Promise<Jwk> {\n    // Map the PBES2 \"alg\" value to the PBKDF2 hash function and derived key length in bits.\n    const { hash, length } = {\n      'PBES2-HS256+A128KW' : { hash: 'SHA-256' as const, length: 128 },\n      'PBES2-HS384+A192KW' : { hash: 'SHA-384' as const, length: 192 },\n      'PBES2-HS512+A256KW' : { hash: 'SHA-512' as const, length: 256 },\n    }[alg];\n\n    // Per {@link https://www.rfc-editor.org/rfc/rfc7518.html#section-4.8.1.1 | RFC 7518, Section 4.8.1.1},\n    // the salt value used with PBES2 should be of the format (UTF8(Alg) || 0x00 || Salt Input),\n    // where Alg is the \"alg\" (algorithm) Header Parameter value.\n    let salt: Uint8Array;\n    try {\n      salt = new Uint8Array([\n        ...Convert.string(alg).toUint8Array(),\n        0x00,\n        ...Convert.base64Url(p2s).toUint8Array()\n      ]);\n    } catch {\n      throw new CryptoError(CryptoErrorCode.EncodingError, 'Failed to decode the JOSE Header \"p2s\" (PBES2 salt) value.');\n    }\n\n    // Derive the KEK bytes from the given passphrase, salt, and iteration count using PBKDF2.\n    const kekBytes = await Pbkdf2.deriveKeyBytes({\n      baseKeyBytes : passphrase,\n      hash,\n      salt,\n      iterations   : p2c,\n      length,\n    });\n\n    // Convert the derived KEK bytes to an AES Key Wrap JWK.\n    return await AesKw.bytesToPrivateKey({ privateKeyBytes: kekBytes });\n  }\n\n  /**\n   * Validates the \"epk\" (Ephemeral Public Key) Header Parameter for ECDH-ES key agreement.\n   *\n   * @param epk - The \"epk\" value from the JOSE Header.\n   * @returns The validated ephemeral public key in JWK format.\n   * @throws {@link CryptoError} if the \"epk\" value is missing, malformed, or uses an unsupported\n   *         curve.\n   */\n  private static validateEpk(epk: unknown): Jwk {\n    if (typeof epk !== 'object' || epk === null || !('kty' in epk)) {\n      throw new CryptoError(CryptoErrorCode.InvalidJwe, 'JOSE Header \"epk\" (Ephemeral Public Key) is missing or not a JWK.');\n    }\n\n    const ephemeralPublicKey = epk as Jwk;\n\n    // Only the X25519 curve is supported for ECDH-ES key agreement.\n    if (!(ephemeralPublicKey.kty === 'OKP' && ephemeralPublicKey.crv === 'X25519' && typeof ephemeralPublicKey.x === 'string')) {\n      throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported,\n        `Unsupported JOSE Header \"epk\" (Ephemeral Public Key): must be an OKP JWK on the X25519 curve with an \"x\" value.`\n      );\n    }\n\n    return ephemeralPublicKey;\n  }\n}\n", "import type { Jwk } from '../jwk.js';\nimport type { KeyIdentifier } from '../../types/identifier.js';\nimport type { JweAlg, JweCipher, JweDecryptOptions, JweEnc, JweEncryptOptions, JweHeaderParams } from './header.js';\nimport type { JweKeyManagementDecryptKey, JweKeyManagementEncryptKey } from './key-management.js';\n\nimport { Convert } from '@enbox/common';\n\nimport { AesGcm } from '../../primitives/aes-gcm.js';\nimport { CryptoUtils } from '../../utils.js';\nimport { isValidJweHeader } from './header.js';\nimport { XChaCha20Poly1305 } from '../../primitives/xchacha20-poly1305.js';\nimport { CryptoError, CryptoErrorCode } from '../../crypto-error.js';\nimport { generateCek, JweKeyManagement } from './key-management.js';\n\n/**\n * Parameters required for decrypting a flattened JWE.\n */\nexport interface FlattenedJweDecryptParams {\n  /** The flattened JWE. */\n  jwe: FlattenedJweParams | FlattenedJwe;\n\n  /**\n   * The decryption key which can be a Key Identifier such as a KMS key URI, a JSON Web Key (JWK),\n   * raw key material represented as a byte array, or an ECDH-ES key agreement input.\n   */\n  key: JweKeyManagementDecryptKey;\n\n  /**\n   * Cipher used to decrypt the JWE payload when the Content Encryption Key is referenced by a\n   * Key Identifier (e.g. a KMS URI) rather than provided as a JWK. Required only for\n   * Key Identifier CEKs.\n   */\n  keyManager?: JweCipher;\n\n  /** {@inheritDoc JweDecryptOptions} */\n  options: JweDecryptOptions;\n}\n\n/**\n * Result of decrypting a flattened JWE, containing the plaintext and related information.\n */\nexport interface FlattenedJweDecryptResult {\n  /** JWE Additional Authenticated Data (AAD). */\n  additionalAuthenticatedData?: Uint8Array;\n\n  /** Plaintext. */\n  plaintext: Uint8Array;\n\n  /** JWE Protected Header. */\n  protectedHeader?: Partial<JweHeaderParams>;\n\n  /** JWE Shared Unprotected Header. */\n  sharedUnprotectedHeader?: Partial<JweHeaderParams>;\n\n  /** JWE Per-Recipient Unprotected Header. */\n  unprotectedHeader?: Partial<JweHeaderParams>;\n}\n\n/**\n * Parameters for encrypting data into a flattened JWE format.\n */\nexport interface FlattenedJweEncryptParams extends FlattenedJweDecryptResult {\n  /**\n   * The encryption key which can be a Key Identifier such as a KMS key URI, a JSON Web Key (JWK),\n   * raw key material represented as a byte array, or an ECDH-ES key agreement input.\n   */\n  key: JweKeyManagementEncryptKey;\n\n  /**\n   * Cipher used to encrypt the JWE payload when the Content Encryption Key is referenced by a\n   * Key Identifier (e.g. a KMS URI) rather than provided as a JWK. Required only for\n   * Key Identifier CEKs.\n   */\n  keyManager?: JweCipher;\n\n  /** {@inheritDoc JweEncryptOptions} */\n  options?: JweEncryptOptions;\n}\n\n/**\n * Represents the parameters for a flattened JWE object, typically used in single-recipient\n * scenarios.\n */\nexport interface FlattenedJweParams {\n  /** Base64URL encoded additional authenticated data. */\n  aad?: string;\n\n  /** Base64URL encoded ciphertext. */\n  ciphertext: string;\n\n  /** Base64URL encoded encrypted key. */\n  encrypted_key?: string;\n\n  /** Per-Recipient Unprotected Header parameters. */\n  header?: Partial<JweHeaderParams>;\n\n  /** Base64URL encoded initialization vector. */\n  iv?: string;\n\n  /** Base64URL encoded string of the Protected Header. */\n  protected?: string;\n\n  /** Base64URL encoded authentication tag. */\n  tag?: string;\n\n  /** Shared Unprotected Header parameters. */\n  unprotected?: Partial<JweHeaderParams>;\n}\n\n/**\n * A helper utility function used internally to decode a JWE header parameter from a Base64 URL\n * encoded string to a Uint8Array. It's designed to process individual JWE header parameter values,\n * ensuring they are correctly formatted and decoded.\n *\n * @param param - The name of the JWE header parameter being decoded; used for error messaging.\n * @param value - The Base64 URL encoded string value of the header parameter to decode.\n * @returns The decoded parameter as a Uint8Array, or undefined if the input value is undefined.\n * @throws {@link CryptoError} if the value is not a properly encoded Base64 URL string or if it's\n *         not a string.\n */\nfunction decodeHeaderParam(param: string, value?: string): Uint8Array | undefined {\n  // If the parameter value is not present, return undefined.\n  if (value === undefined) {return undefined;}\n\n  try {\n    if (typeof value !== 'string') {throw new Error();}\n    return Convert.base64Url(value).toUint8Array();\n  } catch {\n    throw new CryptoError(CryptoErrorCode.InvalidJwe,\n      `Failed to decode the JWE Header parameter '${param}' from Base64 URL format to ` +\n      'Uint8Array. Ensure the value is properly encoded in Base64 URL format without padding.'\n    );\n  }\n}\n\n/**\n * Decrypts the JWE ciphertext with the given Content Encryption Key (CEK) using the content\n * encryption algorithm specified by the \"enc\" (Encryption Algorithm) Header Parameter.\n *\n * @param params - The content decryption parameters.\n * @returns A Promise that resolves to the decrypted plaintext as a byte array.\n * @throws {@link CryptoError} if the \"enc\" value is unsupported or the JWE Initialization Vector\n *         is missing.\n */\nasync function decryptContent({ enc, cek, ciphertext, iv, additionalData }: {\n  enc: string;\n  cek: Jwk;\n  ciphertext: Uint8Array;\n  iv?: Uint8Array;\n  additionalData?: Uint8Array;\n}): Promise<Uint8Array> {\n  if (iv === undefined) {\n    throw new CryptoError(CryptoErrorCode.InvalidJwe, `JWE Initialization Vector is required when using \"${enc}\" content encryption.`);\n  }\n\n  switch (enc) {\n    case 'A128GCM':\n    case 'A192GCM':\n    case 'A256GCM':\n      return await AesGcm.decrypt({ key: cek, data: ciphertext, iv, additionalData });\n\n    case 'XC20P':\n      return await XChaCha20Poly1305.decrypt({ key: cek, data: ciphertext, nonce: iv, additionalData });\n\n    default:\n      throw new CryptoError(\n        CryptoErrorCode.AlgorithmNotSupported,\n        `Unsupported \"enc\" (Encryption Algorithm) Header Parameter value: ${enc}`\n      );\n  }\n}\n\n/**\n * Encrypts the plaintext with the given Content Encryption Key (CEK) using the content encryption\n * algorithm specified by the \"enc\" (Encryption Algorithm) Header Parameter.\n *\n * @param params - The content encryption parameters.\n * @returns A Promise that resolves to the ciphertext (with the authentication tag appended) as a\n *          byte array.\n * @throws {@link CryptoError} if the \"enc\" value is unsupported.\n */\nasync function encryptContent({ enc, cek, plaintext, iv, additionalData }: {\n  enc: string;\n  cek: Jwk;\n  plaintext: Uint8Array;\n  iv: Uint8Array;\n  additionalData?: Uint8Array;\n}): Promise<Uint8Array> {\n  switch (enc) {\n    case 'A128GCM':\n    case 'A192GCM':\n    case 'A256GCM':\n      return await AesGcm.encrypt({ key: cek, data: plaintext, iv, additionalData });\n\n    case 'XC20P':\n      return await XChaCha20Poly1305.encrypt({ key: cek, data: plaintext, nonce: iv, additionalData });\n\n    default:\n      throw new CryptoError(\n        CryptoErrorCode.AlgorithmNotSupported,\n        `Unsupported \"enc\" (Encryption Algorithm) Header Parameter value: ${enc}`\n      );\n  }\n}\n\n/**\n * Generates a random JWE Initialization Vector of the size required by the given \"enc\"\n * (Encryption Algorithm) Header Parameter value, or the empty octet sequence if the algorithm\n * does not use an Initialization Vector.\n *\n * @param enc - The JWE \"enc\" value identifying the content encryption algorithm.\n * @returns The generated Initialization Vector as a byte array.\n */\nfunction generateInitializationVector(enc: string): Uint8Array {\n  switch (enc) {\n    case 'A128GCM':\n    case 'A192GCM':\n    case 'A256GCM':\n      return CryptoUtils.randomBytes(12);\n\n    case 'XC20P':\n      // XChaCha20-Poly1305 uses an extended 192-bit (24-byte) nonce.\n      return CryptoUtils.randomBytes(24);\n\n    default:\n      return new Uint8Array(0);\n  }\n}\n\n/**\n * The `FlattenedJwe` class handles the encryption and decryption of JSON Web Encryption (JWE)\n * objects in the flattened serialization format. This format is a compact, URL-safe means of\n * representing encrypted content, typically used when dealing with a single recipient or when\n * bandwidth efficiency is important.\n *\n * This class provides methods to encrypt plaintext to a flattened JWE and decrypt a flattened JWE\n * back to plaintext, utilizing a variety of supported cryptographic algorithms as specified in the\n * JWE header parameters.\n *\n * @example\n * ```ts\n *  // Example usage of encrypt method\n * const plaintext = new TextEncoder().encode(\"Secret Message\");\n * const key = { kty: \"oct\", k: \"your-secret-key\" }; // Example symmetric key\n * const protectedHeader = { alg: \"dir\", enc: \"A256GCM\" };\n * const encryptedJwe = await FlattenedJwe.encrypt({\n *   plaintext,\n *   protectedHeader,\n *   key,\n * });\n * ```\n *\n * @example\n * // Decryption example\n * const { plaintext, protectedHeader } = await FlattenedJwe.decrypt({\n *   jwe: yourFlattenedJweObject,\n *   key: yourDecryptionKey,\n *   options: { allowedAlgs: ['dir'], allowedEncs: ['A256GCM'] },\n * });\n */\nexport class FlattenedJwe {\n  /** Base64URL encoded additional authenticated data. */\n  public aad?: string;\n\n  /** Base64URL encoded ciphertext. */\n  public ciphertext: string = '';\n\n  /** Base64URL encoded encrypted key. */\n  public encrypted_key?: string;\n\n  /** Per-Recipient Unprotected Header parameters. */\n  public header?: Partial<JweHeaderParams>;\n\n  /** Base64URL encoded initialization vector. */\n  public iv?: string;\n\n  /** Base64URL encoded string of the Protected Header. */\n  public protected?: string;\n\n  /** Base64URL encoded authentication tag. */\n  public tag?: string;\n\n  /** Shared Unprotected Header parameters. */\n  public unprotected?: Partial<JweHeaderParams>;\n\n  constructor(params: FlattenedJweParams) {\n    Object.assign(this, params);\n  }\n\n  public static async decrypt({ jwe, key, keyManager, options }:\n    FlattenedJweDecryptParams\n  ): Promise<FlattenedJweDecryptResult> {\n    // Verify that at least one of the JOSE header objects is present.\n    if (!jwe.protected && !jwe.header && !jwe.unprotected) {\n      throw new CryptoError(CryptoErrorCode.InvalidJwe,\n        'JWE is missing the required JOSE header parameters. ' +\n        'Please provide at least one of the following: \"protected\", \"header\", or \"unprotected\"'\n      );\n    }\n\n    // Verify that the JWE Ciphertext is present.\n    if (typeof jwe.ciphertext !== 'string') {\n      throw new CryptoError(CryptoErrorCode.InvalidJwe, 'JWE Ciphertext is missing or not a string.');\n    }\n\n    // Parse the JWE Protected Header, if present.\n    let parsedProtectedHeader: Partial<JweHeaderParams> | undefined;\n    if (jwe.protected) {\n      try {\n        parsedProtectedHeader = Convert.base64Url(jwe.protected).toObject();\n      } catch {\n        throw new Error('JWE Protected Header is invalid');\n      }\n    }\n\n    // Per {@link https://www.rfc-editor.org/rfc/rfc7516#section-5.2 | RFC7516 Section 5.2}\n    // the resulting JOSE Header MUST NOT contain duplicate Header Parameter names. In other words,\n    // the same Header Parameter name MUST NOT occur in the `header`, `protected`, and\n    // `unprotected` JSON object values that together comprise the JOSE Header.\n    if (hasDuplicateProperties(parsedProtectedHeader, jwe.header, jwe.unprotected)){\n      throw new Error(\n        'Duplicate properties detected. Please ensure that each parameter is defined only once ' +\n        'across the JWE \"header\", \"protected\", and \"unprotected\" objects.'\n      );\n    }\n\n    // The JOSE Header is the union of the members of the JWE Protected Header (`protected`), the\n    // JWE Shared Unprotected Header (`unprotected`), and the corresponding JWE Per-Recipient\n    // Unprotected Header (`header`).\n    const joseHeader = { ...parsedProtectedHeader, ...jwe.header, ...jwe.unprotected };\n\n    if (!isValidJweHeader(joseHeader)) {\n      throw new Error('JWE Header is missing required \"alg\" (Algorithm) and/or \"enc\" (Encryption) Header Parameters');\n    }\n\n    // Enforce the caller-supplied algorithm allow-lists before any key management processing to\n    // prevent algorithm-confusion attacks between callers that share the same engine.\n    if (!options.allowedAlgs.includes(joseHeader.alg as JweAlg)) {\n      throw new CryptoError(\n        CryptoErrorCode.AlgorithmNotSupported,\n        `JWE \"alg\" (Algorithm) Header Parameter value is not allowed by the caller: ${joseHeader.alg}`\n      );\n    }\n    if (!options.allowedEncs.includes(joseHeader.enc as JweEnc)) {\n      throw new CryptoError(\n        CryptoErrorCode.AlgorithmNotSupported,\n        `JWE \"enc\" (Encryption Algorithm) Header Parameter value is not allowed by the caller: ${joseHeader.enc}`\n      );\n    }\n\n    let cek: KeyIdentifier | Jwk;\n    try {\n      const encryptedKey = jwe.encrypted_key\n        ? Convert.base64Url(jwe.encrypted_key).toUint8Array()\n        : undefined;\n\n      cek = await JweKeyManagement.decrypt(\n        { key, encryptedKey, joseHeader },\n        { minP2cCount: options.minP2cCount }\n      );\n\n    } catch (error: any) {\n      // If the error is a CryptoError with code \"InvalidJwe\" or \"AlgorithmNotSupported\", re-throw.\n      if (error instanceof CryptoError\n          && (error.code === CryptoErrorCode.InvalidJwe || error.code === CryptoErrorCode.AlgorithmNotSupported)) {\n        throw error;\n      }\n\n      // Otherwise, generate a random CEK and proceed to the next step.\n      // As noted in\n      // {@link https://datatracker.ietf.org/doc/html/rfc7516#section-11.5 | RFC 7516 Section 11.5},\n      // to mitigate the attacks described in\n      // {@link https://datatracker.ietf.org/doc/html/rfc3218 | RFC 3218}, the recipient MUST NOT\n      // distinguish between format, padding, and length errors of encrypted keys. It is strongly\n      // recommended, in the event of receiving an improperly formatted key, that the recipient\n      // substitute a randomly generated CEK and proceed to the next step, to mitigate timing\n      // attacks.\n      cek = await generateCek(joseHeader.enc);\n    }\n\n    // If present, decode the JWE Initialization Vector (IV) and Authentication Tag.\n    const iv = decodeHeaderParam('iv', jwe.iv);\n    const tag = decodeHeaderParam('tag', jwe.tag);\n\n    // Decode the JWE Ciphertext to a byte array, and if present, append the Authentication Tag.\n    const ciphertext = tag === undefined\n      ? Convert.base64Url(jwe.ciphertext).toUint8Array()\n      : new Uint8Array([\n        ...Convert.base64Url(jwe.ciphertext).toUint8Array(),\n        ...(tag ?? [])\n      ]);\n\n    // If the JWE Additional Authenticated Data (AAD) is present, the Additional Authenticated Data\n    // input to the Content Encryption Algorithm is\n    // ASCII(Encoded Protected Header || '.' || BASE64URL(JWE AAD)). If the JWE AAD is absent, the\n    // Additional Authenticated Data is ASCII(BASE64URL(UTF8(JWE Protected Header))).\n    const additionalData = jwe.aad === undefined\n      ? Convert.string(jwe.protected ?? '').toUint8Array()\n      : new Uint8Array([\n        ...Convert.string(jwe.protected ?? '').toUint8Array(),\n        ...Convert.string('.').toUint8Array(),\n        ...Convert.string(jwe.aad).toUint8Array()\n      ]);\n\n    // Decrypt the JWE using the Content Encryption Key (CEK) with:\n    // - Key Manager: If the CEK is a Key Identifier.\n    // - Content encryption primitives: If the CEK is a JWK.\n    let plaintext: Uint8Array;\n    if (typeof cek === 'string') {\n      if (keyManager === undefined) {\n        throw new CryptoError(CryptoErrorCode.OperationNotSupported, 'A \"keyManager\" is required to decrypt with a Key Identifier CEK.');\n      }\n      plaintext = await keyManager.decrypt({ keyUri: cek, data: ciphertext, iv, additionalData });\n    } else {\n      plaintext = await decryptContent({ enc: joseHeader.enc, cek, ciphertext, iv, additionalData });\n    }\n\n    return {\n      plaintext,\n      protectedHeader             : parsedProtectedHeader,\n      additionalAuthenticatedData : decodeHeaderParam('aad', jwe.aad),\n      sharedUnprotectedHeader     : jwe.unprotected,\n      unprotectedHeader           : jwe.header\n    };\n  }\n\n  public static async encrypt({\n    key,\n    plaintext,\n    additionalAuthenticatedData,\n    protectedHeader,\n    sharedUnprotectedHeader,\n    unprotectedHeader,\n    keyManager,\n  }: FlattenedJweEncryptParams): Promise<FlattenedJwe> {\n    // Verify that at least one of the JOSE header objects is present.\n    if (!protectedHeader && !sharedUnprotectedHeader && !unprotectedHeader) {\n      throw new CryptoError(CryptoErrorCode.InvalidJwe,\n        'JWE is missing the required JOSE header parameters. ' +\n            'Please provide at least one of the following: \"protectedHeader\", \"sharedUnprotectedHeader\", or \"unprotectedHeader\"'\n      );\n    }\n\n    // Verify that the Plaintext is present.\n    if (!(plaintext instanceof Uint8Array)) {\n      throw new CryptoError(CryptoErrorCode.InvalidJwe, 'Plaintext is missing or not a byte array.');\n    }\n\n    // Per {@link https://www.rfc-editor.org/rfc/rfc7516#section-5.2 | RFC7516 Section 5.2}\n    // the resulting JOSE Header MUST NOT contain duplicate Header Parameter names. In other words,\n    // the same Header Parameter name MUST NOT occur in the `header`, `protected`, and\n    // `unprotected` JSON object values that together comprise the JOSE Header.\n    if (hasDuplicateProperties(protectedHeader, sharedUnprotectedHeader, unprotectedHeader)){\n      throw new Error(\n        'Duplicate properties detected. Please ensure that each parameter is defined only once ' +\n        'across the JWE \"protectedHeader\", \"sharedUnprotectedHeader\", and \"unprotectedHeader\" objects.'\n      );\n    }\n\n    // The JOSE Header is the union of the members of the JWE Protected Header (`protectedHeader`),\n    // the JWE Shared Unprotected Header (`sharedUnprotectedHeader`), and the corresponding JWE\n    // Per-Recipient Unprotected Header (`unprotectedHeader`).\n    const joseHeader = { ...protectedHeader, ...sharedUnprotectedHeader, ...unprotectedHeader };\n\n    if (!isValidJweHeader(joseHeader)) {\n      throw new Error('JWE Header is missing required \"alg\" (Algorithm) and/or \"enc\" (Encryption) Header Parameters');\n    }\n\n    const { cek, encryptedKey, headerParams } = await JweKeyManagement.encrypt({ key, joseHeader });\n\n    // Merge any header parameters produced during key management (e.g. the ECDH-ES \"epk\" value)\n    // into the JWE Protected Header so that they are covered by the Additional Authenticated Data.\n    if (headerParams !== undefined) {\n      protectedHeader = { ...protectedHeader, ...headerParams };\n    }\n\n    // If required for the Content Encryption Algorithm, generate a random JWE Initialization\n    // Vector (IV) of the correct size; otherwise, let the JWE Initialization Vector be the empty\n    // octet sequence.\n    const iv = generateInitializationVector(joseHeader.enc);\n\n    // Compute the Encoded Protected Header value BASE64URL(UTF8(JWE Protected Header)).  If the JWE\n    // Protected Header is not present, let this value be the empty string.\n    const encodedProtectedHeader = protectedHeader\n      ? Convert.object(protectedHeader).toBase64Url()\n      : '';\n\n    // If the JWE Additional Authenticated Data (AAD) is present, the Additional Authenticated Data\n    // input to the Content Encryption Algorithm is\n    // ASCII(Encoded Protected Header || '.' || BASE64URL(JWE AAD)). If the JWE AAD is absent, the\n    // Additional Authenticated Data is ASCII(BASE64URL(UTF8(JWE Protected Header))).\n    let additionalData: Uint8Array;\n    let encodedAad: string | undefined;\n    if (additionalAuthenticatedData) {\n      encodedAad = Convert.uint8Array(additionalAuthenticatedData).toBase64Url();\n      additionalData = Convert.string(encodedProtectedHeader + '.' + encodedAad).toUint8Array();\n    } else {\n      additionalData = Convert.string(encodedProtectedHeader).toUint8Array();\n    }\n\n    // Encrypt the plaintext using the CEK, the JWE Initialization Vector, and the Additional\n    // Authenticated Data value using the specified content encryption algorithm to create the JWE\n    // Ciphertext value and the JWE Authentication Tag.\n    let ciphertextWithTag: Uint8Array;\n    if (typeof cek === 'string') {\n      if (keyManager === undefined) {\n        throw new CryptoError(CryptoErrorCode.OperationNotSupported, 'A \"keyManager\" is required to encrypt with a Key Identifier CEK.');\n      }\n      ciphertextWithTag = await keyManager.encrypt({ keyUri: cek, data: plaintext, iv, additionalData });\n    } else {\n      ciphertextWithTag = await encryptContent({ enc: joseHeader.enc, cek, plaintext, iv, additionalData });\n    }\n    const ciphertext = ciphertextWithTag.slice(0, -16);\n    const authenticationTag = ciphertextWithTag.slice(-16);\n\n    // Create the Flattened JWE JSON Serialization output, which is based upon the General syntax,\n    // but flattens it, optimizing it for the single-recipient case. It flattens it by removing the\n    // \"recipients\" member and instead placing those members defined for use in the \"recipients\"\n    // array (the \"header\" and \"encrypted_key\" members) in the top-level JSON object (at the same\n    // level as the \"ciphertext\" member).\n    const jwe = new FlattenedJwe({\n      ciphertext: Convert.uint8Array(ciphertext).toBase64Url(),\n    });\n    if (encryptedKey) {jwe.encrypted_key = Convert.uint8Array(encryptedKey).toBase64Url();}\n    if (protectedHeader) {jwe.protected = encodedProtectedHeader;}\n    if (sharedUnprotectedHeader) {jwe.unprotected = sharedUnprotectedHeader;}\n    if (unprotectedHeader) {jwe.header = unprotectedHeader;}\n    if (iv) {jwe.iv = Convert.uint8Array(iv).toBase64Url();}\n    if (encodedAad) {jwe.aad = encodedAad;}\n    if (authenticationTag) {jwe.tag = Convert.uint8Array(authenticationTag).toBase64Url();}\n\n    return jwe;\n  }\n}\n\n/** Check whether any two of the given objects share the same property name. */\nfunction hasDuplicateProperties(...objects: Array<Record<string, any> | undefined>): boolean {\n  const propertySet = new Set<string>();\n  const objectsWithoutUndefined = objects.filter(Boolean);\n\n  for (const obj of objectsWithoutUndefined) {\n    for (const key in obj) {\n      if (propertySet.has(key)) {\n        return true;\n      }\n      propertySet.add(key);\n    }\n  }\n\n  return false;\n}\n", "import type { JweCipher, JweDecryptOptions, JweEncryptOptions, JweHeaderParams } from './header.js';\nimport type { JweKeyManagementDecryptKey, JweKeyManagementEncryptKey } from './key-management.js';\n\nimport { FlattenedJwe } from './flattened.js';\nimport { isValidJweHeader } from './header.js';\nimport { CryptoError, CryptoErrorCode } from '../../crypto-error.js';\n\n/**\n * Parameters required for decrypting a JWE in Compact Serialization format.\n */\nexport interface CompactJweDecryptParams {\n  /** The JWE string in Compact Serialization format. */\n  jwe: string;\n\n  /**\n   * The decryption key which can be a Key Identifier such as a KMS key URI, a JSON Web Key (JWK),\n   * raw key material represented as a byte array, or an ECDH-ES key agreement input.\n   */\n  key: JweKeyManagementDecryptKey;\n\n  /**\n   * Cipher used to decrypt the JWE payload when the Content Encryption Key is referenced by a\n   * Key Identifier (e.g. a KMS URI) rather than provided as a JWK. Required only for\n   * Key Identifier CEKs.\n   */\n  keyManager?: JweCipher;\n\n  /** {@inheritDoc JweDecryptOptions} */\n  options: JweDecryptOptions;\n}\n\n/**\n * Result of decrypting a JWE in Compact Serialization format.\n */\nexport interface CompactJweDecryptResult {\n  /** Decrypted plaintext as a byte array. */\n  plaintext: Uint8Array;\n\n  /** The protected header of the JWE. */\n  protectedHeader: JweHeaderParams;\n}\n\n/**\n * Parameters required for encrypting data into a JWE in Compact Serialization format.\n */\nexport interface CompactJweEncryptParams {\n  /** The plaintext data to be encrypted as a byte array. */\n  plaintext: Uint8Array;\n\n  /** JWE Protected Header containing encryption algorithm details. */\n  protectedHeader: JweHeaderParams;\n\n  /**\n   * The encryption key which can be a Key Identifier such as a KMS key URI, a JSON Web Key (JWK),\n   * raw key material represented as a byte array, or an ECDH-ES key agreement input.\n   */\n  key: JweKeyManagementEncryptKey;\n\n  /**\n   * Cipher used to encrypt the JWE payload when the Content Encryption Key is referenced by a\n   * Key Identifier (e.g. a KMS URI) rather than provided as a JWK. Required only for\n   * Key Identifier CEKs.\n   */\n  keyManager?: JweCipher;\n\n  /** {@inheritDoc JweEncryptOptions} */\n  options?: JweEncryptOptions;\n}\n\n/**\n * The `CompactJwe` class facilitates encryption and decryption processes using the JSON Web\n * Encryption (JWE) Compact Serialization format. This class adheres to the specifications\n * outlined in {@link https://datatracker.ietf.org/doc/html/rfc7516 | RFC 7516}, enabling secure\n * data encapsulation through various cryptographic algorithms.\n *\n * Compact Serialization is a space-efficient representation of JWE, suitable for contexts\n * where verbose data structures are impractical, such as HTTP headers. It provides mechanisms to\n * encrypt content and protect its integrity with authenticated encryption, ensuring\n * confidentiality, authenticity, and non-repudiation.\n *\n * This class supports the following operations:\n * - Decrypting data from a compact serialized JWE string.\n * - Encrypting data and producing a compact serialized JWE string.\n *\n * Usage involves specifying the cryptographic details, such as keys and algorithms, and the class\n * handles the complexities of the JWE processing, including parsing, validating, and applying the\n * cryptographic operations defined in the JWE specification.\n *\n * @example\n * ```ts\n *  // Example usage of encrypt method\n * const plaintext = new TextEncoder().encode(\"Secret Message\");\n * const key = { kty: \"oct\", k: \"your-secret-key\" }; // Example symmetric key\n * const protectedHeader = { alg: \"dir\", enc: \"A256GCM\" };\n * const encryptedJweString = await CompactJwe.encrypt({\n *   plaintext,\n *   protectedHeader,\n *   key,\n * });\n * console.log(encryptedJweString); // Outputs the JWE string in Compact Serialization format\n * ```\n *\n * @example\n * ```ts\n * // Example usage of decrypt method\n * const jweString = \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\"; // A JWE in Compact Serialization\n * const decryptionKey = { kty: \"oct\", k: \"your-secret-key\" }; // The key must match the one used for encryption\n * const { plaintext, protectedHeader } = await CompactJwe.decrypt({\n *   jwe     : jweString,\n *   key     : decryptionKey,\n *   options : { allowedAlgs: ['dir'], allowedEncs: ['A256GCM'] },\n * });\n * console.log(new TextDecoder().decode(plaintext)); // Outputs the decrypted message\n * ```\n */\nexport class CompactJwe {\n  /**\n   * Decrypts a JWE string in Compact Serialization format, extracting the plaintext and\n   * reconstructing the JWE Protected Header.\n   *\n   * This method parses the compact JWE, validates its structure, and applies the appropriate\n   * decryption algorithm as specified in the JWE Protected Header. It returns the decrypted\n   * plaintext along with the reconstructed protected header, ensuring the data's authenticity\n   * and integrity.\n   *\n   * @param params - The decryption parameters including the JWE string, cryptographic key, and\n   *                 required decryption options (algorithm allow-lists).\n   * @returns A promise resolving to the decrypted content and the JWE Protected Header.\n   * @throws {@link CryptoError} if the JWE format is invalid or decryption fails.\n   */\n  public static async decrypt({ jwe, key, keyManager, options }:\n    CompactJweDecryptParams\n  ): Promise<CompactJweDecryptResult> {\n    if (typeof jwe !== 'string') {\n      throw new CryptoError(CryptoErrorCode.InvalidJwe, 'Invalid JWE format. JWE must be a string.');\n    }\n\n    // Split the JWE into its constituent parts.\n    const {\n      0: protectedHeader,\n      1: encryptedKey,\n      2: initializationVector,\n      3: ciphertext,\n      4: authenticationTag,\n      length,\n    } = jwe.split('.');\n\n    // Ensure that the JWE has the required number of parts.\n    if (length !== 5) {\n      throw new CryptoError(CryptoErrorCode.InvalidJwe, 'Invalid JWE format. JWE must have 5 parts.');\n    }\n\n    // Decrypt the JWE.\n    const flattenedJwe = await FlattenedJwe.decrypt({\n      jwe: {\n        ciphertext,\n        encrypted_key : encryptedKey || undefined,\n        iv            : initializationVector || undefined,\n        protected     : protectedHeader,\n        tag           : authenticationTag || undefined,\n      },\n      key,\n      keyManager,\n      options\n    });\n\n    if (!isValidJweHeader(flattenedJwe.protectedHeader)) {\n      throw new CryptoError(CryptoErrorCode.InvalidJwe, 'Decrypt operation failed due to missing or malformed JWE Protected Header');\n    }\n\n    return { plaintext: flattenedJwe.plaintext, protectedHeader: flattenedJwe.protectedHeader };\n  }\n\n  /**\n   * Encrypts plaintext to a JWE string in Compact Serialization format, encapsulating the content\n   * with the specified cryptographic protections.\n   *\n   * It constructs the JWE by encrypting the plaintext, then serializing the output to the\n   * compact format, which includes concatenating various components like the protected header,\n   * encrypted key, initialization vector, ciphertext, and authentication tag.\n   *\n   * @param params - The encryption parameters, including plaintext, JWE Protected Header, and\n   *                 cryptographic key.\n   * @returns A promise that resolves to a string representing the JWE in Compact Serialization\n   *          format.\n   * @throws {@link CryptoError} if encryption fails or the input parameters are invalid.\n   */\n  public static async encrypt({ plaintext, protectedHeader, key, keyManager, options }:\n    CompactJweEncryptParams\n  ): Promise<string> {\n    const jwe = await FlattenedJwe.encrypt({ plaintext, protectedHeader, key, keyManager, options });\n\n    // Create the Compact Serialization, which is the string BASE64URL(UTF8(JWE Protected Header))\n    // || '.' || BASE64URL(JWE Encrypted Key) || '.' || BASE64URL(JWE Initialization Vector)\n    // || '.' || BASE64URL(JWE Ciphertext) || '.' || BASE64URL(JWE Authentication Tag).\n    return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.');\n  }\n}\n", "import { Convert } from '@enbox/common';\n\nimport type { Jwk } from '../jose/jwk.js';\n\nimport { getWebcryptoSubtle } from './webcrypto.js';\nimport { computeJwkThumbprint, isOctPrivateJwk } from '../jose/jwk.js';\n\n/**\n * Constant defining the AES block size in bits.\n *\n * @remarks\n * In AES Counter (CTR) mode, the counter length must match the block size of the AES algorithm,\n * which is 128 bits. NIST publication 800-38A, which provides guidelines for block cipher modes of\n * operation, specifies this requirement. Maintaining a counter length of 128 bits is essential for\n * the correct operation and security of AES-CTR.\n *\n * This implementation does not support counter lengths that are different from the value defined by\n * this constant.\n *\n * @see {@link https://doi.org/10.6028/NIST.SP.800-38A | NIST SP 800-38A}\n */\nconst AES_BLOCK_SIZE = 128;\n\n/**\n * Constant defining the AES key length values in bits.\n *\n * @remarks\n * NIST publication FIPS 197 states:\n * > The AES algorithm is capable of using cryptographic keys of 128, 192, and 256 bits to encrypt\n * > and decrypt data in blocks of 128 bits.\n *\n * This implementation does not support key lengths that are different from the three values\n * defined by this constant.\n *\n * @see {@link https://doi.org/10.6028/NIST.FIPS.197-upd1 | NIST FIPS 197}\n */\nconst AES_KEY_LENGTHS = [128, 192, 256] as const;\n\n/**\n * Constant defining the maximum length of the counter in bits.\n *\n * @remarks\n * The rightmost bits of the counter block are used as the actual counter value, while the leftmost\n * bits are used as the nonce. The maximum length of the counter is 128 bits, which is the same as\n * the AES block size.\n */\nconst COUNTER_MAX_LENGTH = AES_BLOCK_SIZE;\n\n/**\n * The `AesCtr` class provides a comprehensive set of utilities for cryptographic operations\n * using the Advanced Encryption Standard (AES) in Counter (CTR) mode. This class includes\n * methods for key generation, encryption, decryption, and conversions between raw byte arrays\n * and JSON Web Key (JWK) formats. It is designed to support AES-CTR, a symmetric key algorithm\n * that is widely used in various cryptographic applications for its efficiency and security.\n *\n * AES-CTR mode operates as a stream cipher using a block cipher (AES) and is well-suited for\n * scenarios where parallel processing is beneficial or where the same key is required to\n * encrypt multiple data blocks. The class adheres to standard cryptographic practices, ensuring\n * compatibility and security in its implementations.\n *\n * Key Features:\n * - Key Generation: Generate AES symmetric keys in JWK format.\n * - Key Conversion: Transform keys between raw byte arrays and JWK formats.\n * - Encryption: Encrypt data using AES-CTR with the provided symmetric key.\n * - Decryption: Decrypt data encrypted with AES-CTR using the corresponding symmetric key.\n *\n * The methods in this class are asynchronous, returning Promises to accommodate various\n * JavaScript environments.\n *\n * @example\n * ```ts\n * // Key Generation\n * const length = 256; // Length of the key in bits (e.g., 128, 192, 256)\n * const privateKey = await AesCtr.generateKey({ length });\n *\n * // Encryption\n * const data = new TextEncoder().encode('Messsage');\n * const counter = new Uint8Array(16); // 16-byte (128-bit) counter block\n * const encryptedData = await AesCtr.encrypt({\n *   data,\n *   counter,\n *   key: privateKey,\n *   length: 64 // Length of the counter in bits\n * });\n *\n * // Decryption\n * const decryptedData = await AesCtr.decrypt({\n *   data: encryptedData,\n *   counter,\n *   key: privateKey,\n *   length: 64 // Length of the counter in bits\n * });\n *\n * // Key Conversion\n * const privateKeyBytes = await AesCtr.privateKeyToBytes({ privateKey });\n * ```\n */\nexport class AesCtr {\n  /**\n   * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method takes a symmetric key represented as a byte array (Uint8Array) and\n   * converts it into a JWK object for use with AES (Advanced Encryption Standard)\n   * in Counter (CTR) mode. The conversion process involves encoding the key into\n   * base64url format and setting the appropriate JWK parameters.\n   *\n   * The resulting JWK object includes the following properties:\n   * - `kty`: Key Type, set to 'oct' for Octet Sequence (representing a symmetric key).\n   * - `k`: The symmetric key, base64url-encoded.\n   * - `kid`: Key ID, generated based on the JWK thumbprint.\n   *\n   * @example\n   * ```ts\n   * const privateKeyBytes = new Uint8Array([...]); // Replace with actual symmetric key bytes\n   * const privateKey = await AesCtr.bytesToPrivateKey({ privateKeyBytes });\n   * ```\n   *\n   * @param params - The parameters for the symmetric key conversion.\n   * @param params.privateKeyBytes - The raw symmetric key as a Uint8Array.\n   *\n   * @returns A Promise that resolves to the symmetric key in JWK format.\n   */\n  public static async bytesToPrivateKey({ privateKeyBytes }: {\n    privateKeyBytes: Uint8Array;\n  }): Promise<Jwk> {\n    // Construct the private key in JWK format.\n    const privateKey: Jwk = {\n      k   : Convert.uint8Array(privateKeyBytes).toBase64Url(),\n      kty : 'oct'\n    };\n\n    // Compute the JWK thumbprint and set as the key ID.\n    privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n    return privateKey;\n  }\n\n  /**\n   * Decrypts the provided data using AES in Counter (CTR) mode.\n   *\n   * @remarks\n   * This method performs AES-CTR decryption on the given encrypted data using the specified key.\n   * Similar to the encryption process, it requires an initial counter block and the length\n   * of the counter block, along with the encrypted data and the decryption key. The method\n   * returns the decrypted data as a Uint8Array.\n   *\n   * @example\n   * ```ts\n   * const encryptedData = new Uint8Array([...]); // Encrypted data\n   * const counter = new Uint8Array(16); // 16-byte (128-bit) counter block used during encryption\n   * const key = { ... }; // A Jwk object representing the same AES key used for encryption\n   * const decryptedData = await AesCtr.decrypt({\n   *   data: encryptedData,\n   *   counter,\n   *   key,\n   *   length: 64 // Length of the counter in bits\n   * });\n   * ```\n   *\n   * @param params - The parameters for the decryption operation.\n   * @param params.key - The key to use for decryption, represented in JWK format.\n   * @param params.data - The encrypted data to decrypt, as a Uint8Array.\n   * @param params.counter - The initial value of the counter block.\n   * @param params.length - The number of bits in the counter block that are used for the actual counter.\n   *\n   * @returns A Promise that resolves to the decrypted data as a Uint8Array.\n   */\n  public static async decrypt({ key, data, counter, length }: {\n    key: Jwk;\n    data: Uint8Array;\n    counter: Uint8Array;\n    length: number;\n  }): Promise<Uint8Array> {\n    // Validate the initial counter block length matches the AES block size.\n    if (counter.byteLength !== AES_BLOCK_SIZE / 8) {\n      throw new TypeError(`The counter must be ${AES_BLOCK_SIZE} bits in length`);\n    }\n\n    // Validate the length of the counter.\n    if (length === 0 || length > COUNTER_MAX_LENGTH) {\n      throw new TypeError(`The 'length' property must be in the range 1 to ${COUNTER_MAX_LENGTH}`);\n    }\n\n    // Get the Web Crypto API interface.\n    const webCrypto = getWebcryptoSubtle();\n\n    // Import the JWK into the Web Crypto API to use for the decrypt operation.\n    const webCryptoKey = await webCrypto.importKey('jwk', key, { name: 'AES-CTR' }, true, ['decrypt']);\n\n    // Decrypt the data.\n    const plaintextBuffer = await webCrypto.decrypt(\n      { name: 'AES-CTR', counter, length },\n      webCryptoKey,\n      data\n    );\n\n    // Convert from ArrayBuffer to Uint8Array.\n    const plaintext = new Uint8Array(plaintextBuffer);\n\n    return plaintext;\n  }\n\n  /**\n   * Encrypts the provided data using AES in Counter (CTR) mode.\n   *\n   * @remarks\n   * This method performs AES-CTR encryption on the given data using the specified key.\n   * It requires the initial counter block and the length of the counter block, alongside\n   * the data and key. The method is designed to work asynchronously and returns the\n   * encrypted data as a Uint8Array.\n   *\n   * @example\n   * ```ts\n   * const data = new TextEncoder().encode('Messsage');\n   * const counter = new Uint8Array(16); // 16-byte (128-bit) counter block\n   * const key = { ... }; // A Jwk object representing an AES key\n   * const encryptedData = await AesCtr.encrypt({\n   *   data,\n   *   counter,\n   *   key,\n   *   length: 64 // Length of the counter in bits\n   * });\n   * ```\n   *\n   * @param params - The parameters for the encryption operation.\n   * @param params.key - The key to use for encryption, represented in JWK format.\n   * @param params.data - The data to encrypt, represented as a Uint8Array.\n   * @param params.counter - The initial value of the counter block.\n   * @param params.length - The number of bits in the counter block that are used for the actual counter.\n   *\n   * @returns A Promise that resolves to the encrypted data as a Uint8Array.\n   */\n  public static async encrypt({ key, data, counter, length }: {\n    key: Jwk;\n    data: Uint8Array;\n    counter: Uint8Array;\n    length: number;\n  }): Promise<Uint8Array> {\n    // Validate the initial counter block value length.\n    if (counter.byteLength !== AES_BLOCK_SIZE / 8) {\n      throw new TypeError(`The counter must be ${AES_BLOCK_SIZE} bits in length`);\n    }\n\n    // Validate the length of the counter.\n    if (length === 0 || length > COUNTER_MAX_LENGTH) {\n      throw new TypeError(`The 'length' property must be in the range 1 to ${COUNTER_MAX_LENGTH}`);\n    }\n\n    // Get the Web Crypto API interface.\n    const webCrypto = getWebcryptoSubtle();\n\n    // Import the JWK into the Web Crypto API to use for the encrypt operation.\n    const webCryptoKey = await webCrypto.importKey('jwk', key, { name: 'AES-CTR' }, true, ['encrypt', 'decrypt']);\n\n    // Encrypt the data.\n    const ciphertextBuffer = await webCrypto.encrypt(\n      { name: 'AES-CTR', counter, length },\n      webCryptoKey,\n      data\n    );\n\n    // Convert from ArrayBuffer to Uint8Array.\n    const ciphertext = new Uint8Array(ciphertextBuffer);\n\n    return ciphertext;\n  }\n\n  /**\n   * Generates a symmetric key for AES in Counter (CTR) mode in JSON Web Key (JWK) format.\n   *\n   * @remarks\n   * This method creates a new symmetric key of a specified length suitable for use with\n   * AES-CTR encryption. It uses cryptographically secure random number generation to\n   * ensure the uniqueness and security of the key. The generated key adheres to the JWK\n   * format, making it compatible with common cryptographic standards and easy to use in\n   * various cryptographic processes.\n   *\n   * The generated key includes the following components:\n   * - `kty`: Key Type, set to 'oct' for Octet Sequence.\n   * - `k`: The symmetric key component, base64url-encoded.\n   * - `kid`: Key ID, generated based on the JWK thumbprint.\n   *\n   * @example\n   * ```ts\n   * const length = 256; // Length of the key in bits (e.g., 128, 192, 256)\n   * const privateKey = await AesCtr.generateKey({ length });\n   * ```\n   *\n   * @param params - The parameters for the key generation.\n   * @param params.length - The length of the key in bits. Common lengths are 128, 192, and 256 bits.\n   *\n   * @returns A Promise that resolves to the generated symmetric key in JWK format.\n   */\n  public static async generateKey({ length }: {\n    length: typeof AES_KEY_LENGTHS[number];\n  }): Promise<Jwk> {\n    // Validate the key length.\n    if (!(AES_KEY_LENGTHS as readonly number[]).includes(length)) {\n      throw new RangeError(`The key length is invalid: Must be ${AES_KEY_LENGTHS.join(', ')} bits`);\n    }\n\n    // Get the Web Crypto API interface.\n    const webCrypto = getWebcryptoSubtle();\n\n    // Generate a random private key.\n    // See https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#usage_notes for\n    // an explanation for why Web Crypto generateKey() is used instead of getRandomValues().\n    const webCryptoKey = await webCrypto.generateKey( { name: 'AES-CTR', length }, true, ['encrypt']);\n\n    // Export the private key in JWK format.\n    const { ext, key_ops, ...privateKey } = await webCrypto.exportKey('jwk', webCryptoKey);\n\n    // Compute the JWK thumbprint and set as the key ID.\n    privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n    return privateKey;\n  }\n\n  /**\n   * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n   *\n   * @remarks\n   * This method takes a symmetric key in JWK format and extracts its raw byte representation.\n   * It decodes the 'k' parameter of the JWK value, which represents the symmetric key in base64url\n   * encoding, into a byte array.\n   *\n   * @example\n   * ```ts\n   * const privateKey = { ... }; // A symmetric key in JWK format\n   * const privateKeyBytes = await AesCtr.privateKeyToBytes({ privateKey });\n   * ```\n   *\n   * @param params - The parameters for the symmetric key conversion.\n   * @param params.privateKey - The symmetric key in JWK format.\n   *\n   * @returns A Promise that resolves to the symmetric key as a Uint8Array.\n   */\n  public static async privateKeyToBytes({ privateKey }: {\n    privateKey: Jwk;\n  }): Promise<Uint8Array> {\n    // Verify the provided JWK represents a valid oct private key.\n    if (!isOctPrivateJwk(privateKey)) {\n      throw new Error(`AesCtr: The provided key is not a valid oct private key.`);\n    }\n\n    // Decode the provided private key to bytes.\n    const privateKeyBytes = Convert.base64Url(privateKey.k).toUint8Array();\n\n    return privateKeyBytes;\n  }\n}\n"],
  "mappings": "6FAGO,IAAMA,EAAN,MAAMC,UAAoB,KAAM,CAOrC,YAAmBC,EAAuBC,EAAiB,CACzD,MAAMA,CAAO,EADI,UAAAD,EAEjB,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AExDA,CACT,CAqBA,aAAoB,kBAAkB,CAAE,WAAAA,CAAW,EAE3B,CAEtB,GAAI,CAACc,GAAgBd,CAAU,EAC7B,MAAM,IAAI,MAAM,0DAA0D,EAM5E,OAFwBC,EAAQ,UAAUD,EAAW,CAAC,EAAE,aAAa,CAGvE,CACF",
  "names": ["CryptoError", "_CryptoError", "code", "message", "CryptoErrorCode", "empty", "equals", "aa", "bb", "ii", "coerce", "o", "toArrayBufferBackedArray", "isByteArrayWithArrayBuffer", "b", "toArrayBufferBackedArray", "base", "ALPHABET", "name", "caseInsensitive", "BASE_MAP", "j", "x", "xc", "xl", "xu", "BASE", "LEADER", "FACTOR", "iFACTOR", "encode", "source", "zeroes", "length", "pbegin", "pend", "size", "b58", "carry", "i", "it1", "it2", "str", "decodeUnsafe", "psz", "b256", "it3", "it4", "vch", "decode", "string", "buffer", "src", "_brrp__multiformats_scope_baseX", "base_x_default", "Encoder", "name", "prefix", "baseEncode", "bytes", "Decoder", "baseDecode", "prefixCodePoint", "text", "decoder", "or", "ComposedDecoder", "decoders", "input", "left", "right", "Codec", "from", "encode", "decode", "baseX", "alphabet", "caseInsensitive", "base_x_default", "coerce", "string", "alphabetIdx", "bitsPerChar", "end", "out", "bits", "buffer", "written", "i", "value", "data", "pad", "mask", "createAlphabetIdx", "lower", "upper", "rfc4648", "base32", "rfc4648", "base32upper", "base32pad", "base32padupper", "base32hex", "base32hexupper", "base32hexpad", "base32hexpadupper", "base32z", "base58btc", "baseX", "base58flickr", "base64", "rfc4648", "base64pad", "base64url", "base64urlpad", "isArrayBufferSlice", "arrayBufferView", "isAsyncIterable", "obj", "universalTypeOf", "value", "typeString", "match", "_", "type", "textEncoder", "textDecoder", "Convert", "_Convert", "data", "format", "isAsyncIterable", "base58btc", "base64url", "universalTypeOf", "isArrayBufferSlice", "base32z", "u8a", "string", "chunks", "_d", "_e", "__asyncValues", "_f", "_a", "_c", "chunk", "hexes", "v", "i", "hex", "text", "str", "dataType", "byteValue", "arrayBuffer", "LogLevel", "EnboxLogger", "logLevel", "message", "logger", "base36", "baseX", "base36upper", "varint_exports", "__export", "decode", "encodeTo", "encodingLength", "encode_1", "encode", "MSB", "REST", "MSBALL", "INT", "num", "out", "offset", "oldOffset", "decode", "read", "MSB$1", "REST$1", "buf", "res", "shift", "counter", "b", "l", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "length", "value", "varint", "_brrp_varint", "varint_default", "decode", "data", "offset", "varint_default", "encodeTo", "int", "target", "encodingLength", "create", "code", "digest", "size", "sizeOffset", "encodingLength", "digestOffset", "bytes", "encodeTo", "Digest", "decode", "multihash", "coerce", "equals", "a", "b", "data", "toArrayBufferBackedArray", "format", "link", "base", "bytes", "version", "toStringV0", "baseCache", "base58btc", "toStringV1", "base32", "cache", "baseCache", "cid", "CID", "_CID", "version", "code", "multihash", "bytes", "toArrayBufferBackedArray", "DAG_PB_CODE", "SHA_256_CODE", "digest", "create", "other", "self", "unknown", "equals", "base", "format", "input", "value", "encodeCID", "cidSymbol", "decode", "remainder", "specs", "prefixSize", "multihashBytes", "coerce", "digestBytes", "Digest", "initialBytes", "offset", "next", "i", "length", "codec", "multihashCode", "digestSize", "size", "multihashSize", "source", "prefix", "parseCIDtoBytes", "decoder", "base58btc", "base32", "base36", "toStringV0", "toStringV1", "codeOffset", "encodingLength", "hashOffset", "encodeTo", "Multicodec", "_Multicodec", "options", "code", "data", "name", "_a", "prefixLength", "varint_exports", "dataWithPrefix", "prefixedData", "_", "codec", "codeByteLength", "removeUndefinedProperties", "obj", "key", "value", "MemoryStore", "id", "key", "durationUnitMultipliers", "CryptoAlgorithm", "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", "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", "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", "equalBytes", "a", "b", "abytes", "diff", "i", "copyBytes", "bytes", "asciiToBytes", "ascii", "c", "charCode", "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", "h", "msgs", "concatBytes", "reseed", "seed", "gen", "out", "sl", "pred", "res", "validateObject", "object", "fields", "optFields", "checkField", "fieldName", "expectedType", "isOpt", "val", "current", "iter", "f", "notImplemented", "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", "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", "_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", "isNegativeLE", "num", "FIELD_FIELDS", "validateField", "field", "initial", "opts", "map", "val", "validateObject", "asafenumber", "FpPow", "p", "d", "FpInvertBatch", "nums", "passZero", "inverted", "multipliedAcc", "acc", "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", "i2osp", "value", "length", "asafenumber", "res", "i", "strxor", "a", "b", "arr", "normDST", "DST", "isBytes", "dst", "asciiToBytes", "expand_message_xmd", "msg", "lenInBytes", "H", "abytes", "concatBytes", "b_in_bytes", "r_in_bytes", "ell", "DST_prime", "Z_pad", "l_i_b_str", "b_0", "args", "_DST_scalar", "_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", "Q", "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", "canonicalize", "obj", "sortObjKeys", "sortedKeys", "a", "b", "sortedObj", "key", "Sha256", "data", "sha256", "KEY_URI_PREFIX_JWK", "computeJwkThumbprint", "jwk", "keyType", "normalizedJwk", "removeUndefinedProperties", "serializedJwk", "canonicalize", "utf8Bytes", "Convert", "digest", "Sha256", "isEcPrivateJwk", "obj", "isEcPublicJwk", "isOctPrivateJwk", "isOkpPrivateJwk", "isOkpPublicJwk", "isPrivateJwk", "isPublicJwk", "Secp256k1", "_Secp256k1", "signature", "signatureObject", "secp256k1", "privateKeyBytes", "point", "privateKey", "Convert", "computeJwkThumbprint", "publicKeyBytes", "publicKey", "key", "derSignature", "isEcPrivateJwk", "d", "isEcPublicJwk", "prefix", "x", "y", "privateKeyA", "publicKeyB", "privateKeyABytes", "publicKeyBBytes", "data", "digest", "sha256", "keyBytes", "numberToBytesBE", "p256_CURVE", "p256_Point", "weierstrass", "p256_CURVE", "p256", "ecdsa", "sha256", "Secp256r1", "_Secp256r1", "signature", "signatureObject", "p256", "privateKeyBytes", "point", "privateKey", "Convert", "computeJwkThumbprint", "publicKeyBytes", "publicKey", "key", "derSignature", "isEcPrivateJwk", "d", "isEcPublicJwk", "prefix", "x", "y", "privateKeyA", "publicKeyB", "privateKeyABytes", "publicKeyBBytes", "data", "digest", "sha256", "keyBytes", "numberToBytesBE", "EcdsaAlgorithm", "CryptoAlgorithm", "algorithm", "privateKeyBytes", "privateKey", "Secp256k1", "Secp256r1", "CryptoError", "publicKeyBytes", "publicKey", "key", "isEcPrivateJwk", "data", "signature", "isEcPublicJwk", "_0n", "_1n", "_2n", "_8n", "isEdValidXY", "Fp", "CURVE", "x", "y", "x2", "y2", "left", "right", "edwards", "params", "extraOpts", "opts", "validated", "createCurveFields", "Fn", "cofactor", "validateObject", "MASK", "modP", "n", "uvRatio", "u", "v", "acoord", "title", "banZero", "min", "aInRange", "aedpoint", "other", "Point", "X", "Y", "Z", "T", "p", "bytes", "zip215", "len", "a", "d", "copyBytes", "abytes", "abool", "normed", "lastByte", "bytesToNumberLE", "max", "isValid", "isXOdd", "isLastByteOdd", "hex", "hexToBytes", "windowSize", "isLazy", "wnaf", "X2", "Y2", "Z2", "Z4", "aX2", "XY", "ZT", "X1", "Y1", "Z1", "X1Z2", "X2Z1", "Y1Z2", "Y2Z1", "A", "B", "C", "x1y1", "E", "G", "F", "H", "X3", "Y3", "T3", "Z3", "T1", "T2", "D", "scalar", "f", "normalizeZ", "invertedZ", "iz", "is0", "zz", "bytesToHex", "wNAF", "PrimeEdwardsPoint", "ep", "_bytes", "notImplemented", "_hex", "eddsa", "cHash", "eddsaOpts", "hash", "prehash", "BASE", "outputLen", "expectedLen", "asafenumber", "randomBytes", "adjustScalarBytes", "domain", "data", "ctx", "phflag", "modN_LE", "getPrivateScalar", "key", "lengths", "hashed", "head", "prefix", "getExtendedPublicKey", "secretKey", "point", "pointBytes", "getPublicKey", "hashDomainToScalar", "context", "msgs", "msg", "concatBytes", "sign", "options", "r", "R", "k", "s", "rs", "verifyOpts", "verify", "sig", "publicKey", "mid", "SB", "_size", "randomSecretKey", "seed", "isValidSecretKey", "isBytes", "isValidPublicKey", "utils", "size", "is25519", "createKeygen", "_0n", "_1n", "_2n", "validateOpts", "curve", "validateObject", "montgomery", "curveDef", "CURVE", "P", "type", "adjustScalarBytes", "powPminus2", "rand", "is25519", "randomBytes_", "randomBytes", "montgomeryBits", "fieldLen", "Gu", "a24", "minScalar", "maxAdded", "maxScalar", "modP", "n", "mod", "GuBytes", "encodeU", "u", "numberToBytesLE", "decodeU", "_u", "copyBytes", "abytes", "bytesToNumberLE", "decodeScalar", "scalar", "scalarMult", "pu", "montgomeryLadder", "scalarMultBase", "getPublicKey", "getSharedSecret", "cswap", "swap", "x_2", "x_3", "dummy", "aInRange", "k", "x_1", "z_2", "z_3", "t", "k_t", "A", "AA", "B", "BB", "E", "C", "D", "DA", "CB", "dacb", "da_cb", "z2", "lengths", "randomSecretKey", "seed", "utils", "createKeygen", "_0n", "_1n", "_2n", "_3n", "_5n", "_8n", "ed25519_CURVE_p", "ed25519_CURVE", "ed25519_pow_2_252_3", "x", "_10n", "_20n", "_40n", "_80n", "P", "b2", "b4", "pow2", "b5", "b10", "b20", "b40", "b80", "b160", "b240", "b250", "adjustScalarBytes", "bytes", "ED25519_SQRT_M1", "uvRatio", "u", "v", "v3", "mod", "v7", "pow", "vx2", "root1", "root2", "useRoot1", "useRoot2", "noRoot", "isNegativeLE", "ed25519_Point", "edwards", "Fp", "Fn", "ed", "opts", "eddsa", "ed25519_Point", "sha512", "adjustScalarBytes", "ed25519", "x25519", "P", "ed25519_CURVE_p", "montgomery", "x", "pow_p_5_8", "b2", "ed25519_pow_2_252_3", "mod", "pow2", "_3n", "adjustScalarBytes", "SQRT_M1", "ED25519_SQRT_M1", "SQRT_AD_MINUS_ONE", "INVSQRT_A_MINUS_D", "ONE_MINUS_D_SQ", "D_MINUS_ONE_SQ", "invertSqrt", "number", "uvRatio", "_1n", "MAX_255B", "bytes255ToNumberLE", "bytes", "Fp", "bytesToNumberLE", "calcElligatorRistrettoMap", "r0", "d", "ed25519_CURVE", "P", "ed25519_CURVE_p", "mod", "n", "r", "Ns", "c", "D", "Ns_D_is_sq", "s", "s_", "isNegativeLE", "Nt", "s2", "W0", "W1", "W2", "W3", "ed25519_Point", "_RistrettoPoint", "__RistrettoPoint", "PrimeEdwardsPoint", "Fn", "ep", "ap", "other", "abytes", "a", "equalBytes", "u1", "u2", "u1_2", "u2_2", "v", "isValid", "I", "Dx", "Dy", "x", "y", "t", "_0n", "hex", "hexToBytes", "X", "Y", "Z", "T", "u2sq", "invsqrt", "D1", "D2", "zInv", "_x", "_y", "X1", "Y1", "X2", "Y2", "one", "two", "ristretto255_hasher", "_RistrettoPoint", "msg", "options", "DST", "xmd", "expand_message_xmd", "sha512", "_DST_scalar", "Fn", "bytesToNumberLE", "bytes", "abytes", "r1", "bytes255ToNumberLE", "R1", "calcElligatorRistrettoMap", "r2", "R2", "Ed25519", "_Ed25519", "privateKeyBytes", "publicKeyBytes", "ed25519", "privateKey", "Convert", "computeJwkThumbprint", "publicKey", "key", "ed25519PrivateKeyBytes", "x25519PrivateKeyBytes", "x25519PublicKeyBytes", "x25519", "x25519PrivateKey", "ed25519PublicKeyBytes", "x25519PublicKey", "isOkpPrivateJwk", "d", "isOkpPublicJwk", "data", "signature", "EdDsaAlgorithm", "CryptoAlgorithm", "algorithm", "privateKeyBytes", "privateKey", "Ed25519", "CryptoError", "publicKeyBytes", "publicKey", "key", "isOkpPrivateJwk", "data", "signature", "isOkpPublicJwk", "Sha2Algorithm", "CryptoAlgorithm", "algorithm", "data", "Sha256", "X25519", "_X25519", "privateKeyBytes", "publicKeyBytes", "x25519", "privateKey", "Convert", "computeJwkThumbprint", "publicKey", "key", "isOkpPrivateJwk", "d", "isOkpPublicJwk", "privateKeyA", "publicKeyB", "privateKeyABytes", "publicKeyBBytes", "X25519Algorithm", "CryptoAlgorithm", "algorithm", "privateKeyBytes", "X25519", "CryptoError", "key", "isOkpPrivateJwk", "privateKey", "supportedAlgorithms", "EdDsaAlgorithm", "EcdsaAlgorithm", "Sha2Algorithm", "X25519Algorithm", "LocalKeyManager", "params", "MemoryStore", "algorithm", "data", "keyUri", "key", "KEY_URI_PREFIX_JWK", "jwkThumbprint", "computeJwkThumbprint", "privateKey", "isPrivateJwk", "signature", "AlgorithmImplementation", "algProperty", "crvProperty", "algName", "algorithmInfo", "getWebcrypto", "webCrypto", "getWebcryptoSubtle", "subtle", "CryptoUtils", "_CryptoUtils", "publicKey", "curveToJoseAlgorithm", "bytesLength", "randomBytes", "getWebcrypto", "length", "pinRange", "byteLength", "randomSpace", "unbiasedLimit", "randomValue", "randomBuffer", "byte", "isCipher", "obj", "objectTypeNames", "is", "value", "typeOf", "objectType", "getObjectType", "objectTypeName", "Type", "major", "name", "terminal", "typ", "a", "b", "Token", "type", "value", "encodedLength", "useBuffer", "textEncoder", "isBuffer", "buf", "asU8A", "FROM_STRING_THRESHOLD_BUFFER", "FROM_STRING_THRESHOLD_TEXTENCODER", "fromString", "string", "utf8ToBytes", "fromArray", "arr", "slice", "bytes", "start", "end", "concat", "chunks", "length", "c", "out", "off", "b", "alloc", "size", "compare", "b1", "b2", "isBuffer", "i", "utf8ToBytes", "str", "out", "p", "c", "defaultChunkSize", "Bl", "chunkSize", "bytes", "topChunk", "chunkPos", "alloc", "reset", "byts", "chunk", "slice", "concat", "U8Bl", "dest", "decodeErrPrefix", "encodeErrPrefix", "uintMinorPrefixBytes", "assertEnoughData", "data", "pos", "need", "uintBoundaries", "readUint8", "data", "offset", "options", "assertEnoughData", "value", "decodeErrPrefix", "readUint16", "readUint32", "readUint64", "hi", "lo", "decodeUint8", "pos", "_minor", "Token", "Type", "decodeUint16", "decodeUint32", "decodeUint64", "encodeUint", "writer", "token", "encodeUintValue", "major", "uint", "nuint", "buint", "set", "tok1", "tok2", "decodeNegint8", "data", "pos", "_minor", "options", "Token", "Type", "readUint8", "decodeNegint16", "readUint16", "decodeNegint32", "readUint32", "neg1b", "pos1b", "decodeNegint64", "int", "readUint64", "value", "decodeErrPrefix", "encodeNegint", "writer", "token", "negint", "unsigned", "encodeUintValue", "uintBoundaries", "tok1", "tok2", "toToken", "data", "pos", "prefix", "length", "assertEnoughData", "buf", "Token", "Type", "decodeBytesCompact", "minor", "_options", "decodeBytes8", "_minor", "options", "readUint8", "decodeBytes16", "readUint16", "decodeBytes32", "readUint32", "decodeBytes64", "l", "readUint64", "decodeErrPrefix", "tokenBytes", "token", "fromString", "encodeBytes", "writer", "bytes", "encodeUintValue", "tok1", "tok2", "compareBytes", "b1", "b2", "compare", "textDecoder", "ASCII_THRESHOLD", "toStr", "bytes", "start", "end", "str", "c", "toToken", "data", "pos", "prefix", "length", "options", "totLength", "assertEnoughData", "tok", "Token", "Type", "decodeStringCompact", "minor", "decodeString8", "_minor", "readUint8", "decodeString16", "readUint16", "decodeString32", "readUint32", "decodeString64", "l", "readUint64", "decodeErrPrefix", "encodeString", "encodeBytes", "toToken", "_data", "_pos", "prefix", "length", "Token", "Type", "decodeArrayCompact", "data", "pos", "minor", "_options", "decodeArray8", "_minor", "options", "readUint8", "decodeArray16", "readUint16", "decodeArray32", "readUint32", "decodeArray64", "l", "readUint64", "decodeErrPrefix", "decodeArrayIndefinite", "encodeArray", "writer", "token", "encodeUintValue", "encodeUint", "toToken", "_data", "_pos", "prefix", "length", "Token", "Type", "decodeMapCompact", "data", "pos", "minor", "_options", "decodeMap8", "_minor", "options", "readUint8", "decodeMap16", "readUint16", "decodeMap32", "readUint32", "decodeMap64", "l", "readUint64", "decodeErrPrefix", "decodeMapIndefinite", "encodeMap", "writer", "token", "encodeUintValue", "encodeUint", "decodeTagCompact", "_data", "_pos", "minor", "_options", "Token", "Type", "decodeTag8", "data", "pos", "_minor", "options", "readUint8", "decodeTag16", "readUint16", "decodeTag32", "readUint32", "decodeTag64", "readUint64", "encodeTag", "writer", "token", "encodeUintValue", "encodeUint", "MINOR_FALSE", "MINOR_TRUE", "MINOR_NULL", "MINOR_UNDEFINED", "decodeUndefined", "_data", "_pos", "_minor", "options", "decodeErrPrefix", "Token", "Type", "decodeBreak", "createToken", "value", "bytes", "decodeFloat16", "data", "pos", "readFloat16", "decodeFloat32", "readFloat32", "decodeFloat64", "readFloat64", "encodeFloat", "writer", "token", "float", "decoded", "success", "encodeFloat16", "ui8a", "encodeFloat32", "encodeFloat64", "buffer", "dataView", "inp", "valu32", "exponent", "mantissa", "logicalExponent", "half", "exp", "mant", "val", "offset", "encodeUint", "invalidMinor", "data", "pos", "minor", "decodeErrPrefix", "errorer", "msg", "jump", "i", "decodeUint8", "decodeUint16", "decodeUint32", "decodeUint64", "decodeNegint8", "decodeNegint16", "decodeNegint32", "decodeNegint64", "decodeBytesCompact", "decodeBytes8", "decodeBytes16", "decodeBytes32", "decodeBytes64", "decodeStringCompact", "decodeString8", "decodeString16", "decodeString32", "decodeString64", "decodeArrayCompact", "decodeArray8", "decodeArray16", "decodeArray32", "decodeArray64", "decodeArrayIndefinite", "decodeMapCompact", "decodeMap8", "decodeMap16", "decodeMap32", "decodeMap64", "decodeMapIndefinite", "decodeTagCompact", "decodeTag8", "decodeTag16", "decodeTag32", "decodeTag64", "decodeUndefined", "decodeFloat16", "decodeFloat32", "decodeFloat64", "decodeBreak", "quick", "Token", "Type", "quickEncodeToken", "token", "fromArray", "defaultEncodeOptions", "mapSorter", "quickEncodeToken", "rfc8949EncodeOptions", "rfc8949MapSorter", "makeCborEncoders", "encoders", "Type", "encodeUint", "encodeNegint", "encodeBytes", "encodeString", "encodeArray", "encodeMap", "encodeTag", "encodeFloat", "cborEncoders", "defaultWriter", "Bl", "Ref", "_Ref", "obj", "parent", "p", "stack", "encodeErrPrefix", "simpleTokens", "Token", "typeEncoders", "_typ", "_options", "_refStack", "_obj", "options", "refStack", "entries", "e", "objectToTokens", "typ", "isMap", "keys", "maxLength", "skipUndefined", "i", "key", "value", "sortMapEntries", "is", "customTypeEncoder", "tokens", "typeEncoder", "e1", "e2", "keyToken1", "keyToken2", "major", "tcmp", "t1", "t2", "encodeRfc8949", "compare", "data", "encodeCustom", "tokensToEncoded", "writer", "token", "MAJOR_UINT", "MAJOR_NEGINT", "MAJOR_BYTES", "MAJOR_STRING", "MAJOR_ARRAY", "SIMPLE_FALSE", "MINOR_FALSE", "SIMPLE_TRUE", "MINOR_TRUE", "SIMPLE_NULL", "MINOR_NULL", "SIMPLE_UNDEFINED", "MINOR_UNDEFINED", "neg1b", "pos1b", "canDirectEncode", "directEncode", "customEncoder", "encodeUintValue", "bytes", "fromString", "elem", "destination", "hasDest", "writeTo", "U8Bl", "quickBytes", "encoder", "size", "asU8A", "encode", "defaultDecodeOptions", "Tokeniser", "data", "options", "byt", "token", "quick", "decoder", "jump", "decodeErrPrefix", "minor", "DONE", "BREAK", "tokenToArray", "tokeniser", "arr", "i", "value", "tokensToObject", "tokenToMap", "useMaps", "rejectDuplicateMapKeys", "obj", "m", "key", "Type", "tagged", "decodeFirst", "u8aData", "asU8A", "decoded", "decode", "remainder", "Cbor", "value", "encode", "data", "decode", "CoseKeyType", "CoseEllipticCurve", "CoseAlgorithm", "jwkCrvToCose", "coseCrvToJwk", "jwkAlgToCose", "coseAlgToJwk", "CoseKey", "_CoseKey", "jwk", "coseKey", "crv", "CryptoError", "Convert", "kty", "x", "d", "y", "alg", "kid", "CoseSign1", "_CoseSign1", "params", "key", "payload", "externalAad", "detachedPayload", "alg", "CoseKey", "protectedHeaderMap", "protectedHeaderBytes", "Cbor", "unprotectedHeaderMap", "sigStructure", "toBeSigned", "signature", "coseSign1Array", "coseSign1", "decoded", "CryptoError", "tagged", "protectedHeader", "contentType", "kid", "header", "map", "data", "Ed25519", "Secp256r1", "EatClaimKey", "EatDebugStatus", "EatSecurityLevel", "Eat", "_Eat", "token", "coseSign1", "CoseSign1", "CryptoError", "claims", "params", "key", "externalAad", "payload", "rawClaims", "decoded", "Cbor", "error", "iss", "sub", "aud", "exp", "nbf", "iat", "cti", "nonce", "ueid", "hwmodel", "hwversion", "dbgstat", "measres", "submods", "AES_GCM_IV_LENGTH", "AES_KEY_LENGTHS", "AES_GCM_TAG_LENGTHS", "AesGcm", "privateKeyBytes", "privateKey", "Convert", "computeJwkThumbprint", "key", "data", "iv", "additionalData", "tagLength", "webCrypto", "getWebcryptoSubtle", "webCryptoKey", "algorithm", "plaintextBuffer", "ciphertextBuffer", "length", "ext", "key_ops", "isOctPrivateJwk", "AesGcmAlgorithm", "CryptoAlgorithm", "privateKeyBytes", "privateKey", "AesGcm", "params", "algorithm", "length", "isBytes", "a", "abool", "b", "anumber", "n", "abytes", "value", "length", "title", "bytes", "len", "needsLen", "prefix", "ofLen", "got", "message", "aexists", "instance", "checkFinished", "aoutput", "out", "onlyAligned", "min", "isAligned32", "u32", "arr", "clean", "arrays", "i", "createView", "isLE", "byteSwap", "word", "swap8IfBE", "n", "byteSwap32", "swap32IfBE", "u", "concatBytes", "arrays", "sum", "i", "a", "abytes", "res", "pad", "checkOpts", "defaults", "opts", "equalBytes", "b", "diff", "wrapMacConstructor", "keyLen", "macCons", "fromMsg", "mac", "getArgs", "macC", "msg", "key", "tmp", "args", "wrapCipher", "params", "constructor", "wrappedCipher", "nonce", "tagl", "cipher", "checkOutput", "fnLength", "output", "called", "data", "getOutput", "expectedLength", "out", "onlyAligned", "isAligned32", "u64Lengths", "dataLength", "aadLength", "isLE", "anumber", "abool", "num", "view", "createView", "bytes", "copyBytes", "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", "isBytes32", "a", "encryptBlock", "xk", "block", "abytes", "b32", "u32", "swap32IfBE", "s0", "s1", "s2", "s3", "encrypt", "decryptBlock", "decrypt", "AESW", "kek", "out", "expandKeyLE", "o32", "a0", "a1", "j", "ctr", "pos", "byteSwap", "expandKeyDecLE", "chunks", "AESKW_IV", "aeskw", "wrapCipher", "plaintext", "concatBytes", "ciphertext", "copyBytes", "equalBytes", "AES_KEY_LENGTHS", "webCryptoAesKwSupport", "hasWebCryptoAesKw", "getWebcryptoSubtle", "_resetWebCryptoAesKwDetection", "AesKw", "_AesKw", "privateKeyBytes", "privateKey", "Convert", "computeJwkThumbprint", "lengthInBits", "length", "getWebcrypto", "webCrypto", "webCryptoKey", "ext", "key_ops", "isOctPrivateJwk", "wrappedKeyBytes", "wrappedKeyAlgorithm", "decryptionKey", "CryptoError", "webCryptoAlgorithm", "decryptionKeyBytes", "unwrappedKeyBytes", "aeskw", "algorithmFamily", "unwrappedKey", "decryptionCryptoKey", "unwrappedCryptoKey", "unwrappedJsonWebKey", "encryptionKey", "encryptionKeyBytes", "encryptionCryptoKey", "wrappedKeyBuffer", "AesKwAlgorithm", "CryptoAlgorithm", "privateKeyBytes", "privateKey", "AesKw", "algorithm", "length", "params", "Hkdf", "baseKeyBytes", "length", "hash", "salt", "info", "webCrypto", "getWebcryptoSubtle", "webCryptoKey", "saltBytes", "Convert", "infoBytes", "derivedKeyBuffer", "HkdfAlgorithm", "CryptoAlgorithm", "algorithm", "params", "hash", "Hkdf", "Pbkdf2", "hash", "password", "salt", "iterations", "length", "webCrypto", "getWebcryptoSubtle", "webCryptoKey", "derivedKeyBuffer", "baseKeyBytes", "Pbkdf2Algorithm", "CryptoAlgorithm", "algorithm", "params", "hashFunction", "hash", "Pbkdf2", "isValidJweHeader", "obj", "encodeStr", "str", "c", "sigma16_32", "swap32IfBE", "u32", "sigma32_32", "rotl", "a", "b", "BLOCK_LEN", "BLOCK_LEN32", "MAX_COUNTER", "U32_EMPTY", "runCipher", "core", "sigma", "key", "nonce", "data", "output", "counter", "rounds", "len", "block", "b32", "isAligned", "isLE", "isAligned32", "d32", "o32", "pos", "take", "j", "posj", "pos32", "createCipher", "opts", "allowShortKeys", "extendNonceFn", "counterLength", "counterRight", "checkOpts", "anumber", "abool", "abytes", "getOutput", "toClean", "l", "k", "copyBytes", "k32", "n16", "sigmaRaw", "clean", "nonceNcLen", "nc", "n32", "u8to16", "a", "i", "Poly1305", "key", "copyBytes", "abytes", "t0", "u8to16", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "i", "data", "offset", "isLast", "hibit", "h", "r", "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "h0", "h1", "h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9", "c", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "pad", "g", "mask", "f", "clean", "aexists", "buffer", "blockLen", "len", "pos", "take", "out", "aoutput", "opos", "outputLen", "res", "poly1305", "wrapMacConstructor", "chachaCore", "s", "k", "n", "out", "cnt", "rounds", "y00", "y01", "y02", "y03", "y04", "y05", "y06", "y07", "y08", "y09", "y10", "y11", "y12", "y13", "y14", "y15", "x00", "x01", "x02", "x03", "x04", "x05", "x06", "x07", "x08", "x09", "x10", "x11", "x12", "x13", "x14", "x15", "r", "rotl", "oi", "hchacha", "i", "swap8IfBE", "swap32IfBE", "xchacha20", "createCipher", "chachaCore", "hchacha", "ZEROS16", "updatePadded", "h", "msg", "leftover", "ZEROS32", "computeTag", "fn", "key", "nonce", "ciphertext", "AAD", "abytes", "authKey", "lengths", "u64Lengths", "poly1305", "res", "clean", "_poly1305_aead", "xorStream", "plaintext", "output", "plength", "getOutput", "oPlain", "tag", "data", "passedTag", "equalBytes", "xchacha20poly1305", "wrapCipher", "_poly1305_aead", "xchacha20", "POLY1305_TAG_LENGTH", "XChaCha20Poly1305", "_XChaCha20Poly1305", "privateKeyBytes", "privateKey", "Convert", "computeJwkThumbprint", "data", "key", "nonce", "additionalData", "keyBytes", "xchacha20poly1305", "webCrypto", "getWebcryptoSubtle", "webCryptoKey", "alg", "ext", "key_ops", "isOctPrivateJwk", "ConcatKdf", "_ConcatKdf", "keyDataLen", "fixedInfo", "sharedSecret", "roundCount", "counter", "fixedInfoBytes", "sha256", "concatBytes", "params", "algorithmId", "partyUInfo", "partyVInfo", "suppPubInfo", "suppPrivInfo", "data", "variableLength", "encodedData", "dataType", "universalTypeOf", "dataU8A", "Convert", "bufferLength", "ECDH_ES_PIN_KDF_INFO", "CEK_BIT_LENGTH_BY_ENC", "isJweEcdhEsKey", "key", "generateCek", "enc", "AesGcm", "XChaCha20Poly1305", "CryptoError", "JweKeyManagement", "_JweKeyManagement", "encryptedKey", "joseHeader", "options", "minP2cCount", "ephemeralPublicKey", "sharedSecret", "X25519", "kek", "AesKw", "cek", "headerParams", "ephemeralPrivateKey", "pin", "byte", "keyDataLen", "partyUInfo", "partyVInfo", "cekBytes", "ConcatKdf", "Hkdf", "Convert", "param", "value", "alg", "passphrase", "p2c", "p2s", "hash", "length", "salt", "kekBytes", "Pbkdf2", "epk", "decodeHeaderParam", "param", "value", "Convert", "CryptoError", "decryptContent", "enc", "cek", "ciphertext", "iv", "additionalData", "AesGcm", "XChaCha20Poly1305", "encryptContent", "plaintext", "generateInitializationVector", "CryptoUtils", "FlattenedJwe", "_FlattenedJwe", "params", "jwe", "key", "keyManager", "options", "parsedProtectedHeader", "hasDuplicateProperties", "joseHeader", "isValidJweHeader", "encryptedKey", "JweKeyManagement", "error", "generateCek", "tag", "additionalAuthenticatedData", "protectedHeader", "sharedUnprotectedHeader", "unprotectedHeader", "headerParams", "encodedProtectedHeader", "encodedAad", "ciphertextWithTag", "authenticationTag", "objects", "propertySet", "objectsWithoutUndefined", "obj", "CompactJwe", "jwe", "key", "keyManager", "options", "CryptoError", "protectedHeader", "encryptedKey", "initializationVector", "ciphertext", "authenticationTag", "length", "flattenedJwe", "FlattenedJwe", "isValidJweHeader", "plaintext", "AES_BLOCK_SIZE", "AES_KEY_LENGTHS", "COUNTER_MAX_LENGTH", "AesCtr", "privateKeyBytes", "privateKey", "Convert", "computeJwkThumbprint", "key", "data", "counter", "length", "webCrypto", "getWebcryptoSubtle", "webCryptoKey", "plaintextBuffer", "ciphertextBuffer", "ext", "key_ops", "isOctPrivateJwk"]
}
