@notabene/verify-proof 1.0.0 → 1.0.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/bitcoin.ts","../node_modules/ox/_esm/core/Errors.js","../node_modules/@noble/hashes/esm/_assert.js","../node_modules/@noble/hashes/esm/utils.js","../node_modules/@noble/hashes/esm/_u64.js","../node_modules/@noble/hashes/esm/sha3.js","../node_modules/@noble/curves/esm/abstract/utils.js","../node_modules/ox/_esm/core/Json.js","../node_modules/ox/_esm/core/internal/bytes.js","../node_modules/ox/_esm/core/internal/hex.js","../node_modules/ox/_esm/core/Hex.js","../node_modules/ox/_esm/core/Bytes.js","../node_modules/ox/_esm/core/Hash.js","../node_modules/ox/_esm/core/internal/lru.js","../node_modules/ox/_esm/core/Caches.js","../node_modules/ox/_esm/core/PublicKey.js","../node_modules/ox/_esm/core/Address.js","../node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js","../node_modules/@noble/curves/node_modules/@noble/hashes/esm/crypto.js","../node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js","../node_modules/@noble/curves/node_modules/@noble/hashes/esm/_md.js","../node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha256.js","../node_modules/@noble/curves/node_modules/@noble/hashes/esm/hmac.js","../node_modules/@noble/curves/esm/abstract/modular.js","../node_modules/@noble/curves/esm/abstract/curve.js","../node_modules/@noble/curves/esm/abstract/weierstrass.js","../node_modules/@noble/curves/esm/_shortw_utils.js","../node_modules/@noble/curves/esm/secp256k1.js","../node_modules/ox/_esm/core/Signature.js","../src/index.ts","../src/eth.ts","../node_modules/ox/_esm/core/Secp256k1.js","../node_modules/ox/_esm/core/PersonalMessage.js","../src/solana.ts"],"sourcesContent":["import { ProofStatus, SignatureProof } from \"@notabene/javascript-sdk\";\nimport { bech32 } from \"bech32\";\n\nimport {\n secp256k1,\n hash160,\n hash256,\n RecoveryId,\n encodeBase58AddressFormat,\n} from \"@bitauth/libauth\";\nimport { encode as encodeLength } from \"varuint-bitcoin\";\nimport { decode as decodeBase64 } from \"@stablelib/base64\";\n\nenum SEGWIT_TYPES {\n P2WPKH = \"p2wpkh\",\n P2SH_P2WPKH = \"p2sh(p2wpkh)\",\n}\n\nconst messagePrefix = \"\\u0018Bitcoin Signed Message:\\n\";\n\nenum DerivationMode {\n LEGACY = \"Legacy\",\n NATIVE = \"Native SegWit\",\n SEGWIT = \"SegWit\",\n P2SH_SEGWIT = \"p2sh\",\n BCH = \"Bitcoin Cash\",\n ETHEREUM = \"Ethereum\",\n DOGECOIN = \"Dogecoin\",\n UNKNOWN = \"Unknown\",\n}\n\nexport async function verifyBTCSignature(\n proof: SignatureProof,\n): Promise<SignatureProof> {\n const [ns, _, address] = proof.address.split(/:/);\n if (ns !== \"bip122\") return { ...proof, status: ProofStatus.FAILED };\n try {\n // const messageToBeSigned = message.replace(/\\s+/g, \" \").trim();\n const segwit = [DerivationMode.SEGWIT, DerivationMode.NATIVE].includes(\n getDerivationMode(address),\n );\n const verified = verify(proof.attestation, address, proof.proof, segwit);\n\n return {\n ...proof,\n status: verified ? ProofStatus.VERIFIED : ProofStatus.FAILED,\n };\n } catch (error) {\n return { ...proof, status: ProofStatus.FAILED };\n }\n}\n\nfunction getDerivationMode(address: string) {\n if (address.match(\"^(bc1|tb1|ltc1).*\")) {\n return DerivationMode.NATIVE;\n } else if (address.match(\"^[32M].*\")) {\n return DerivationMode.SEGWIT;\n } else if (address.match(\"^[1nmL].*\")) {\n return DerivationMode.LEGACY;\n } else if (address.match(\"^(D).*\")) {\n return DerivationMode.DOGECOIN;\n } else {\n throw new Error(\n \"INVALID ADDRESS: \"\n .concat(address)\n .concat(\" is not a valid or a supported address\"),\n );\n }\n}\n\ntype DecodedSignature = {\n compressed: boolean;\n segwitType?: SEGWIT_TYPES;\n recovery: RecoveryId;\n signature: Uint8Array;\n};\n\nfunction decodeSignature(proof: string): DecodedSignature {\n const signature = decodeBase64(proof);\n if (signature.length !== 65) throw new Error(\"Invalid signature length\");\n\n const flagByte = signature[0] - 27;\n if (flagByte > 15 || flagByte < 0) {\n throw new Error(\"Invalid signature parameter\");\n }\n\n return {\n compressed: !!(flagByte & 12),\n segwitType: !(flagByte & 8)\n ? undefined\n : !(flagByte & 4)\n ? SEGWIT_TYPES.P2SH_P2WPKH\n : SEGWIT_TYPES.P2WPKH,\n recovery: (flagByte & 3) as RecoveryId,\n signature: signature.slice(1),\n };\n}\n\nfunction verify(\n attestation: string,\n address: string,\n proof: string,\n checkSegwitAlways: boolean,\n) {\n const { compressed, segwitType, recovery, signature } =\n decodeSignature(proof);\n if (checkSegwitAlways && !compressed) {\n throw new Error(\n \"checkSegwitAlways can only be used with a compressed pubkey signature flagbyte\",\n );\n }\n\n const hash = magicHash(attestation);\n const publicKey: Uint8Array | string = compressed\n ? secp256k1.recoverPublicKeyCompressed(signature, recovery, hash)\n : secp256k1.recoverPublicKeyUncompressed(signature, recovery, hash);\n if (typeof publicKey === \"string\") throw new Error(publicKey);\n const publicKeyHash = hash160(publicKey);\n let actual: string = \"\";\n\n if (segwitType) {\n if (segwitType === SEGWIT_TYPES.P2SH_P2WPKH) {\n actual = encodeBech32Address(publicKeyHash);\n } else {\n // parsed.segwitType === SEGWIT_TYPES.P2WPKH\n // must be true since we only return null, P2SH_P2WPKH, or P2WPKH\n // from the decodeSignature function.\n actual = encodeBech32Address(publicKeyHash);\n }\n } else {\n if (checkSegwitAlways) {\n try {\n actual = encodeBech32Address(publicKeyHash);\n // if address is bech32 it is not p2sh\n } catch (e) {\n actual = encodeBech32Address(publicKeyHash);\n // base58 can be p2pkh or p2sh-p2wpkh\n }\n } else {\n actual = encodeBase58AddressFormat(0, publicKeyHash);\n }\n }\n\n return actual === address;\n}\n\nfunction magicHash(attestation: string) {\n const prefix = new TextEncoder().encode(messagePrefix);\n const message = new TextEncoder().encode(attestation);\n const length = encodeLength(message.length).buffer;\n const buffer = new Uint8Array(\n prefix.length + length.byteLength + message.length,\n );\n buffer.set(prefix);\n buffer.set(new Uint8Array(length), prefix.length);\n buffer.set(message, prefix.length + length.byteLength);\n return hash256(buffer);\n}\n\nfunction encodeBech32Address(publicKeyHash: Uint8Array): string {\n const bwords = bech32.toWords(publicKeyHash);\n bwords.unshift(0);\n return bech32.encode(\"bc\", bwords);\n}\n","import { getVersion } from './internal/errors.js';\n/**\n * Base error class inherited by all errors thrown by ox.\n *\n * @example\n * ```ts\n * import { Errors } from 'ox'\n * throw new Errors.BaseError('An error occurred')\n * ```\n */\nexport class BaseError extends Error {\n constructor(shortMessage, options = {}) {\n const details = (() => {\n if (options.cause instanceof BaseError) {\n if (options.cause.details)\n return options.cause.details;\n if (options.cause.shortMessage)\n return options.cause.shortMessage;\n }\n if (options.cause?.message)\n return options.cause.message;\n return options.details;\n })();\n const docsPath = (() => {\n if (options.cause instanceof BaseError)\n return options.cause.docsPath || options.docsPath;\n return options.docsPath;\n })();\n const docsBaseUrl = 'https://oxlib.sh';\n const docs = `${docsBaseUrl}${docsPath ?? ''}`;\n const message = [\n shortMessage || 'An error occurred.',\n ...(options.metaMessages ? ['', ...options.metaMessages] : []),\n ...(details || docsPath\n ? [\n '',\n details ? `Details: ${details}` : undefined,\n docsPath ? `See: ${docs}` : undefined,\n ]\n : []),\n ]\n .filter((x) => typeof x === 'string')\n .join('\\n');\n super(message, options.cause ? { cause: options.cause } : undefined);\n Object.defineProperty(this, \"details\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"docs\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"docsPath\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"shortMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"cause\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'BaseError'\n });\n Object.defineProperty(this, \"version\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: `ox@${getVersion()}`\n });\n this.cause = options.cause;\n this.details = details;\n this.docs = docs;\n this.docsPath = docsPath;\n this.shortMessage = shortMessage;\n }\n walk(fn) {\n return walk(this, fn);\n }\n}\n/** @internal */\nfunction walk(err, fn) {\n if (fn?.(err))\n return err;\n if (err && typeof err === 'object' && 'cause' in err && err.cause)\n return walk(err.cause, fn);\n return fn ? null : err;\n}\n//# sourceMappingURL=Errors.js.map","function anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n// copied from utils\nfunction isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\nfunction abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\nfunction ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\nfunction aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\nexport { anumber, anumber as number, abytes, abytes as bytes, ahash, aexists, aoutput };\nconst assert = {\n number: anumber,\n bytes: abytes,\n hash: ahash,\n exists: aexists,\n output: aoutput,\n};\nexport default assert;\n//# sourceMappingURL=_assert.js.map","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n// The rotate left (circular left shift) operation for uint32\nexport const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0);\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n// The byte swap operation for uint32\nexport const byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nexport const byteSwapIfBE = isLE ? (n) => n : (n) => byteSwap(n);\n// In place byte swap for Uint32Array\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// 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 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\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)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('utf8ToBytes expected string, got ' + typeof str);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\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// For runtime check if class implements interface\nexport class Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nexport function wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return crypto.randomBytes(bytesLength);\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n// BigUint64Array is too slow as per 2024, so we implement it using Uint32Array.\n// TODO: re-check https://issues.chromium.org/issues/42212588\nfunction fromBig(n, le = false) {\n if (le)\n 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}\nfunction split(lst, le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","import { abytes, aexists, anumber, aoutput } from './_assert.js';\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.js';\nimport { Hash, u32, toBytes, wrapConstructor, wrapXOFConstructorWithOpts, isLE, byteSwap32, } from './utils.js';\n// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.\n// It's called a sponge function.\n// Various per round constants calculations\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = [];\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nconst _7n = /* @__PURE__ */ BigInt(7);\nconst _256n = /* @__PURE__ */ BigInt(256);\nconst _0x71n = /* @__PURE__ */ BigInt(0x71);\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true);\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n// Same as keccakf1600, but allows to skip some rounds\nexport function keccakP(s, rounds = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++)\n B[x] = s[y + x];\n for (let x = 0; x < 10; x++)\n s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n B.fill(0);\n}\nexport class Keccak extends Hash {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n super();\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n // Can be passed from user as dkLen\n anumber(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n if (0 >= this.blockLen || this.blockLen >= 200)\n throw new Error('Sha3 supports only keccak-f1600 function');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n keccak() {\n if (!isLE)\n byteSwap32(this.state32);\n keccakP(this.state32, this.rounds);\n if (!isLE)\n byteSwap32(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n aexists(this);\n const { blockLen, state } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n aexists(this, false);\n abytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF)\n throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes) {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n aoutput(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n this.state.fill(0);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen));\nexport const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8);\n/**\n * SHA3-256 hash function\n * @param message - that would be hashed\n */\nexport const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8);\nexport const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8);\nexport const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8);\nexport const keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8);\n/**\n * keccak-256 hash function. Different from SHA3-256.\n * @param message - that would be hashed\n */\nexport const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8);\nexport const keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8);\nexport const keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8);\nconst genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));\nexport const shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8);\nexport const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8);\n//# sourceMappingURL=sha3.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\nexport function abytes(item) {\n if (!isBytes(item))\n throw new Error('Uint8Array expected');\n}\nexport function abool(title, value) {\n if (typeof value !== 'boolean')\n throw new Error(title + ' boolean expected, got ' + value);\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\nexport function numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\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 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n abytes(bytes);\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n return hexToBytes(numberToHexUnpadded(n));\n}\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title, hex, expectedLength) {\n let res;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n }\n catch (e) {\n throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n }\n }\n else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n }\n else {\n throw new Error(title + ' must be hex string or Uint8Array');\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n return res;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\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// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n// Is positive bigint\nconst isPosBig = (n) => typeof n === 'bigint' && _0n <= n;\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title, n, min, max) {\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 Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n, pos, value) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;\n// DRBG\nconst u8n = (data) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr) => Uint8Array.from(arr); // another shortcut\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG<Key>(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function')\n throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000)\n throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out = [];\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, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n// Validating curves and fields\nconst validatorFns = {\n bigint: (val) => typeof val === 'bigint',\n function: (val) => typeof val === 'function',\n boolean: (val) => typeof val === 'boolean',\n string: (val) => typeof val === 'string',\n stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val) => Number.isSafeInteger(val),\n array: (val) => Array.isArray(val),\n field: (val, object) => object.Fp.isValid(val),\n hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n};\n// type Record<K extends string | number | symbol, T> = { [P in K]: T; }\nexport function validateObject(object, validators, optValidators = {}) {\n const checkField = (fieldName, type, isOptional) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error('invalid validator function');\n const val = object[fieldName];\n if (isOptional && val === undefined)\n return;\n if (!checkVal(val, object)) {\n throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);\n }\n };\n for (const [fieldName, type] of Object.entries(validators))\n checkField(fieldName, type, false);\n for (const [fieldName, type] of Object.entries(optValidators))\n checkField(fieldName, type, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n/**\n * throws not implemented error\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized(fn) {\n const map = new WeakMap();\n return (arg, ...args) => {\n const val = map.get(arg);\n if (val !== undefined)\n return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n//# sourceMappingURL=utils.js.map","const bigIntSuffix = /*#__PURE__*/ '#__bigint';\n/**\n * Parses a JSON string, with support for `bigint`.\n *\n * @example\n * ```ts twoslash\n * import { Json } from 'ox'\n *\n * const json = Json.parse('{\"foo\":\"bar\",\"baz\":\"69420694206942069420694206942069420694206942069420#__bigint\"}')\n * // @log: {\n * // @log: foo: 'bar',\n * // @log: baz: 69420694206942069420694206942069420694206942069420n\n * // @log: }\n * ```\n *\n * @param string - The value to parse.\n * @param reviver - A function that transforms the results.\n * @returns The parsed value.\n */\nexport function parse(string, reviver) {\n return JSON.parse(string, (key, value_) => {\n const value = value_;\n if (typeof value === 'string' && value.endsWith(bigIntSuffix))\n return BigInt(value.slice(0, -bigIntSuffix.length));\n return typeof reviver === 'function' ? reviver(key, value) : value;\n });\n}\n/**\n * Stringifies a value to its JSON representation, with support for `bigint`.\n *\n * @example\n * ```ts twoslash\n * import { Json } from 'ox'\n *\n * const json = Json.stringify({\n * foo: 'bar',\n * baz: 69420694206942069420694206942069420694206942069420n,\n * })\n * // @log: '{\"foo\":\"bar\",\"baz\":\"69420694206942069420694206942069420694206942069420#__bigint\"}'\n * ```\n *\n * @param value - The value to stringify.\n * @param replacer - A function that transforms the results. It is passed the key and value of the property, and must return the value to be used in the JSON string. If this function returns `undefined`, the property is not included in the resulting JSON string.\n * @param space - A string or number that determines the indentation of the JSON string. If it is a number, it indicates the number of spaces to use as indentation; if it is a string (e.g. `'\\t'`), it uses the string as the indentation character.\n * @returns The JSON string.\n */\nexport function stringify(value, replacer, space) {\n return JSON.stringify(value, (key, value) => {\n if (typeof replacer === 'function')\n return replacer(key, value);\n if (typeof value === 'bigint')\n return value.toString() + bigIntSuffix;\n return value;\n }, space);\n}\n//# sourceMappingURL=Json.js.map","import * as Bytes from '../Bytes.js';\n/** @internal */\nexport function assertSize(bytes, size_) {\n if (Bytes.size(bytes) > size_)\n throw new Bytes.SizeOverflowError({\n givenSize: Bytes.size(bytes),\n maxSize: size_,\n });\n}\n/** @internal */\nexport function assertStartOffset(value, start) {\n if (typeof start === 'number' && start > 0 && start > Bytes.size(value) - 1)\n throw new Bytes.SliceOffsetOutOfBoundsError({\n offset: start,\n position: 'start',\n size: Bytes.size(value),\n });\n}\n/** @internal */\nexport function assertEndOffset(value, start, end) {\n if (typeof start === 'number' &&\n typeof end === 'number' &&\n Bytes.size(value) !== end - start) {\n throw new Bytes.SliceOffsetOutOfBoundsError({\n offset: end,\n position: 'end',\n size: Bytes.size(value),\n });\n }\n}\n/** @internal */\nexport const charCodeMap = {\n zero: 48,\n nine: 57,\n A: 65,\n F: 70,\n a: 97,\n f: 102,\n};\n/** @internal */\nexport function charCodeToBase16(char) {\n if (char >= charCodeMap.zero && char <= charCodeMap.nine)\n return char - charCodeMap.zero;\n if (char >= charCodeMap.A && char <= charCodeMap.F)\n return char - (charCodeMap.A - 10);\n if (char >= charCodeMap.a && char <= charCodeMap.f)\n return char - (charCodeMap.a - 10);\n return undefined;\n}\n/** @internal */\nexport function pad(bytes, options = {}) {\n const { dir, size = 32 } = options;\n if (size === 0)\n return bytes;\n if (bytes.length > size)\n throw new Bytes.SizeExceedsPaddingSizeError({\n size: bytes.length,\n targetSize: size,\n type: 'Bytes',\n });\n const paddedBytes = new Uint8Array(size);\n for (let i = 0; i < size; i++) {\n const padEnd = dir === 'right';\n paddedBytes[padEnd ? i : size - i - 1] =\n bytes[padEnd ? i : bytes.length - i - 1];\n }\n return paddedBytes;\n}\n/** @internal */\nexport function trim(value, options = {}) {\n const { dir = 'left' } = options;\n let data = value;\n let sliceLength = 0;\n for (let i = 0; i < data.length - 1; i++) {\n if (data[dir === 'left' ? i : data.length - i - 1].toString() === '0')\n sliceLength++;\n else\n break;\n }\n data =\n dir === 'left'\n ? data.slice(sliceLength)\n : data.slice(0, data.length - sliceLength);\n return data;\n}\n//# sourceMappingURL=bytes.js.map","import * as Hex from '../Hex.js';\n/** @internal */\nexport function assertSize(hex, size_) {\n if (Hex.size(hex) > size_)\n throw new Hex.SizeOverflowError({\n givenSize: Hex.size(hex),\n maxSize: size_,\n });\n}\n/** @internal */\nexport function assertStartOffset(value, start) {\n if (typeof start === 'number' && start > 0 && start > Hex.size(value) - 1)\n throw new Hex.SliceOffsetOutOfBoundsError({\n offset: start,\n position: 'start',\n size: Hex.size(value),\n });\n}\n/** @internal */\nexport function assertEndOffset(value, start, end) {\n if (typeof start === 'number' &&\n typeof end === 'number' &&\n Hex.size(value) !== end - start) {\n throw new Hex.SliceOffsetOutOfBoundsError({\n offset: end,\n position: 'end',\n size: Hex.size(value),\n });\n }\n}\n/** @internal */\nexport function pad(hex_, options = {}) {\n const { dir, size = 32 } = options;\n if (size === 0)\n return hex_;\n const hex = hex_.replace('0x', '');\n if (hex.length > size * 2)\n throw new Hex.SizeExceedsPaddingSizeError({\n size: Math.ceil(hex.length / 2),\n targetSize: size,\n type: 'Hex',\n });\n return `0x${hex[dir === 'right' ? 'padEnd' : 'padStart'](size * 2, '0')}`;\n}\n/** @internal */\nexport function trim(value, options = {}) {\n const { dir = 'left' } = options;\n let data = value.replace('0x', '');\n let sliceLength = 0;\n for (let i = 0; i < data.length - 1; i++) {\n if (data[dir === 'left' ? i : data.length - i - 1].toString() === '0')\n sliceLength++;\n else\n break;\n }\n data =\n dir === 'left'\n ? data.slice(sliceLength)\n : data.slice(0, data.length - sliceLength);\n if (data === '0')\n return '0x';\n if (dir === 'right' && data.length % 2 === 1)\n return `0x${data}0`;\n return `0x${data}`;\n}\n//# sourceMappingURL=hex.js.map","import { equalBytes } from '@noble/curves/abstract/utils';\nimport * as Bytes from './Bytes.js';\nimport * as Errors from './Errors.js';\nimport * as Json from './Json.js';\nimport * as internal_bytes from './internal/bytes.js';\nimport * as internal from './internal/hex.js';\nconst encoder = /*#__PURE__*/ new TextEncoder();\nconst hexes = /*#__PURE__*/ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, '0'));\n/**\n * Asserts if the given value is {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.assert('abc')\n * // @error: InvalidHexValueTypeError:\n * // @error: Value `\"abc\"` of type `string` is an invalid hex type.\n * // @error: Hex types must be represented as `\"0x\\${string}\"`.\n * ```\n *\n * @param value - The value to assert.\n * @param options - Options.\n */\nexport function assert(value, options = {}) {\n const { strict = false } = options;\n if (!value)\n throw new InvalidHexTypeError(value);\n if (typeof value !== 'string')\n throw new InvalidHexTypeError(value);\n if (strict) {\n if (!/^0x[0-9a-fA-F]*$/.test(value))\n throw new InvalidHexValueError(value);\n }\n if (!value.startsWith('0x'))\n throw new InvalidHexValueError(value);\n}\n/**\n * Concatenates two or more {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.concat('0x123', '0x456')\n * // @log: '0x123456'\n * ```\n *\n * @param values - The {@link ox#Hex.Hex} values to concatenate.\n * @returns The concatenated {@link ox#Hex.Hex} value.\n */\nexport function concat(...values) {\n return `0x${values.reduce((acc, x) => acc + x.replace('0x', ''), '')}`;\n}\n/**\n * Instantiates a {@link ox#Hex.Hex} value from a hex string or {@link ox#Bytes.Bytes} value.\n *\n * :::tip\n *\n * To instantiate from a **Boolean**, **String**, or **Number**, use one of the following:\n *\n * - `Hex.fromBoolean`\n *\n * - `Hex.fromString`\n *\n * - `Hex.fromNumber`\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Hex } from 'ox'\n *\n * Hex.from('0x48656c6c6f20576f726c6421')\n * // @log: '0x48656c6c6f20576f726c6421'\n *\n * Hex.from(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // @log: '0x48656c6c6f20576f726c6421'\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} value to encode.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function from(value) {\n if (value instanceof Uint8Array)\n return fromBytes(value);\n if (Array.isArray(value))\n return fromBytes(new Uint8Array(value));\n return value;\n}\n/**\n * Encodes a boolean into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromBoolean(true)\n * // @log: '0x1'\n *\n * Hex.fromBoolean(false)\n * // @log: '0x0'\n *\n * Hex.fromBoolean(true, { size: 32 })\n * // @log: '0x0000000000000000000000000000000000000000000000000000000000000001'\n * ```\n *\n * @param value - The boolean value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromBoolean(value, options = {}) {\n const hex = `0x${Number(value)}`;\n if (typeof options.size === 'number') {\n internal.assertSize(hex, options.size);\n return padLeft(hex, options.size);\n }\n return hex;\n}\n/**\n * Encodes a {@link ox#Bytes.Bytes} value into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Hex } from 'ox'\n *\n * Hex.fromBytes(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // @log: '0x48656c6c6f20576f726c6421'\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromBytes(value, options = {}) {\n let string = '';\n for (let i = 0; i < value.length; i++)\n string += hexes[value[i]];\n const hex = `0x${string}`;\n if (typeof options.size === 'number') {\n internal.assertSize(hex, options.size);\n return padRight(hex, options.size);\n }\n return hex;\n}\n/**\n * Encodes a number or bigint into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromNumber(420)\n * // @log: '0x1a4'\n *\n * Hex.fromNumber(420, { size: 32 })\n * // @log: '0x00000000000000000000000000000000000000000000000000000000000001a4'\n * ```\n *\n * @param value - The number or bigint value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromNumber(value, options = {}) {\n const { signed, size } = options;\n const value_ = BigInt(value);\n let maxValue;\n if (size) {\n if (signed)\n maxValue = (1n << (BigInt(size) * 8n - 1n)) - 1n;\n else\n maxValue = 2n ** (BigInt(size) * 8n) - 1n;\n }\n else if (typeof value === 'number') {\n maxValue = BigInt(Number.MAX_SAFE_INTEGER);\n }\n const minValue = typeof maxValue === 'bigint' && signed ? -maxValue - 1n : 0;\n if ((maxValue && value_ > maxValue) || value_ < minValue) {\n const suffix = typeof value === 'bigint' ? 'n' : '';\n throw new IntegerOutOfRangeError({\n max: maxValue ? `${maxValue}${suffix}` : undefined,\n min: `${minValue}${suffix}`,\n signed,\n size,\n value: `${value}${suffix}`,\n });\n }\n const stringValue = (signed && value_ < 0 ? (1n << BigInt(size * 8)) + BigInt(value_) : value_).toString(16);\n const hex = `0x${stringValue}`;\n if (size)\n return padLeft(hex, size);\n return hex;\n}\n/**\n * Encodes a string into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n * Hex.fromString('Hello World!')\n * // '0x48656c6c6f20576f726c6421'\n *\n * Hex.fromString('Hello World!', { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n * ```\n *\n * @param value - The string value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromString(value, options = {}) {\n return fromBytes(encoder.encode(value), options);\n}\n/**\n * Checks if two {@link ox#Hex.Hex} values are equal.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.isEqual('0xdeadbeef', '0xdeadbeef')\n * // @log: true\n *\n * Hex.isEqual('0xda', '0xba')\n * // @log: false\n * ```\n *\n * @param hexA - The first {@link ox#Hex.Hex} value.\n * @param hexB - The second {@link ox#Hex.Hex} value.\n * @returns `true` if the two {@link ox#Hex.Hex} values are equal, `false` otherwise.\n */\nexport function isEqual(hexA, hexB) {\n return equalBytes(Bytes.fromHex(hexA), Bytes.fromHex(hexB));\n}\n/**\n * Pads a {@link ox#Hex.Hex} value to the left with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.padLeft('0x1234', 4)\n * // @log: '0x00001234'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to pad.\n * @param size - The size (in bytes) of the output hex value.\n * @returns The padded {@link ox#Hex.Hex} value.\n */\nexport function padLeft(value, size) {\n return internal.pad(value, { dir: 'left', size });\n}\n/**\n * Pads a {@link ox#Hex.Hex} value to the right with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts\n * import { Hex } from 'ox'\n *\n * Hex.padRight('0x1234', 4)\n * // @log: '0x12340000'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to pad.\n * @param size - The size (in bytes) of the output hex value.\n * @returns The padded {@link ox#Hex.Hex} value.\n */\nexport function padRight(value, size) {\n return internal.pad(value, { dir: 'right', size });\n}\n/**\n * Generates a random {@link ox#Hex.Hex} value of the specified length.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * const hex = Hex.random(32)\n * // @log: '0x...'\n * ```\n *\n * @returns Random {@link ox#Hex.Hex} value.\n */\nexport function random(length) {\n return fromBytes(Bytes.random(length));\n}\n/**\n * Returns a section of a {@link ox#Bytes.Bytes} value given a start/end bytes offset.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.slice('0x0123456789', 1, 4)\n * // @log: '0x234567'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to slice.\n * @param start - The start offset (in bytes).\n * @param end - The end offset (in bytes).\n * @param options - Options.\n * @returns The sliced {@link ox#Hex.Hex} value.\n */\nexport function slice(value, start, end, options = {}) {\n const { strict } = options;\n internal.assertStartOffset(value, start);\n const value_ = `0x${value\n .replace('0x', '')\n .slice((start ?? 0) * 2, (end ?? value.length) * 2)}`;\n if (strict)\n internal.assertEndOffset(value_, start, end);\n return value_;\n}\n/**\n * Retrieves the size of a {@link ox#Hex.Hex} value (in bytes).\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.size('0xdeadbeef')\n * // @log: 4\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to get the size of.\n * @returns The size of the {@link ox#Hex.Hex} value (in bytes).\n */\nexport function size(value) {\n return Math.ceil((value.length - 2) / 2);\n}\n/**\n * Trims leading zeros from a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.trimLeft('0x00000000deadbeef')\n * // @log: '0xdeadbeef'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to trim.\n * @returns The trimmed {@link ox#Hex.Hex} value.\n */\nexport function trimLeft(value) {\n return internal.trim(value, { dir: 'left' });\n}\n/**\n * Trims trailing zeros from a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.trimRight('0xdeadbeef00000000')\n * // @log: '0xdeadbeef'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to trim.\n * @returns The trimmed {@link ox#Hex.Hex} value.\n */\nexport function trimRight(value) {\n return internal.trim(value, { dir: 'right' });\n}\n/**\n * Decodes a {@link ox#Hex.Hex} value into a BigInt.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toBigInt('0x1a4')\n * // @log: 420n\n *\n * Hex.toBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // @log: 420n\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded BigInt.\n */\nexport function toBigInt(hex, options = {}) {\n const { signed } = options;\n if (options.size)\n internal.assertSize(hex, options.size);\n const value = BigInt(hex);\n if (!signed)\n return value;\n const size = (hex.length - 2) / 2;\n const max_unsigned = (1n << (BigInt(size) * 8n)) - 1n;\n const max_signed = max_unsigned >> 1n;\n if (value <= max_signed)\n return value;\n return value - max_unsigned - 1n;\n}\n/**\n * Decodes a {@link ox#Hex.Hex} value into a boolean.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toBoolean('0x01')\n * // @log: true\n *\n * Hex.toBoolean('0x0000000000000000000000000000000000000000000000000000000000000001', { size: 32 })\n * // @log: true\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded boolean.\n */\nexport function toBoolean(hex, options = {}) {\n if (options.size)\n internal.assertSize(hex, options.size);\n const hex_ = trimLeft(hex);\n if (hex_ === '0x')\n return false;\n if (hex_ === '0x1')\n return true;\n throw new InvalidHexBooleanError(hex);\n}\n/**\n * Decodes a {@link ox#Hex.Hex} value into a {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * const data = Hex.toBytes('0x48656c6c6f20776f726c6421')\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded {@link ox#Bytes.Bytes}.\n */\nexport function toBytes(hex, options = {}) {\n return Bytes.fromHex(hex, options);\n}\n/**\n * Decodes a {@link ox#Hex.Hex} value into a number.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toNumber('0x1a4')\n * // @log: 420\n *\n * Hex.toNumber('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // @log: 420\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded number.\n */\nexport function toNumber(hex, options = {}) {\n const { signed, size } = options;\n if (!signed && !size)\n return Number(hex);\n return Number(toBigInt(hex, options));\n}\n/**\n * Decodes a {@link ox#Hex.Hex} value into a string.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toString('0x48656c6c6f20576f726c6421')\n * // @log: 'Hello world!'\n *\n * Hex.toString('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n * size: 32,\n * })\n * // @log: 'Hello world'\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded string.\n */\nexport function toString(hex, options = {}) {\n const { size } = options;\n let bytes = Bytes.fromHex(hex);\n if (size) {\n internal_bytes.assertSize(bytes, size);\n bytes = Bytes.trimRight(bytes);\n }\n return new TextDecoder().decode(bytes);\n}\n/**\n * Checks if the given value is {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Hex } from 'ox'\n *\n * Hex.validate('0xdeadbeef')\n * // @log: true\n *\n * Hex.validate(Bytes.from([1, 2, 3]))\n * // @log: false\n * ```\n *\n * @param value - The value to check.\n * @param options - Options.\n * @returns `true` if the value is a {@link ox#Hex.Hex}, `false` otherwise.\n */\nexport function validate(value, options = {}) {\n const { strict = false } = options;\n try {\n assert(value, { strict });\n return true;\n }\n catch {\n return false;\n }\n}\n/**\n * Thrown when the provided integer is out of range, and cannot be represented as a hex value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromNumber(420182738912731283712937129)\n * // @error: Hex.IntegerOutOfRangeError: Number \\`4.2018273891273126e+26\\` is not in safe unsigned integer range (`0` to `9007199254740991`)\n * ```\n */\nexport class IntegerOutOfRangeError extends Errors.BaseError {\n constructor({ max, min, signed, size, value, }) {\n super(`Number \\`${value}\\` is not in safe${size ? ` ${size * 8}-bit` : ''}${signed ? ' signed' : ' unsigned'} integer range ${max ? `(\\`${min}\\` to \\`${max}\\`)` : `(above \\`${min}\\`)`}`);\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Hex.IntegerOutOfRangeError'\n });\n }\n}\n/**\n * Thrown when the provided hex value cannot be represented as a boolean.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toBoolean('0xa')\n * // @error: Hex.InvalidHexBooleanError: Hex value `\"0xa\"` is not a valid boolean.\n * // @error: The hex value must be `\"0x0\"` (false) or `\"0x1\"` (true).\n * ```\n */\nexport class InvalidHexBooleanError extends Errors.BaseError {\n constructor(hex) {\n super(`Hex value \\`\"${hex}\"\\` is not a valid boolean.`, {\n metaMessages: [\n 'The hex value must be `\"0x0\"` (false) or `\"0x1\"` (true).',\n ],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Hex.InvalidHexBooleanError'\n });\n }\n}\n/**\n * Thrown when the provided value is not a valid hex type.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.assert(1)\n * // @error: Hex.InvalidHexTypeError: Value `1` of type `number` is an invalid hex type.\n * ```\n */\nexport class InvalidHexTypeError extends Errors.BaseError {\n constructor(value) {\n super(`Value \\`${typeof value === 'object' ? Json.stringify(value) : value}\\` of type \\`${typeof value}\\` is an invalid hex type.`, {\n metaMessages: ['Hex types must be represented as `\"0x${string}\"`.'],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Hex.InvalidHexTypeError'\n });\n }\n}\n/**\n * Thrown when the provided hex value is invalid.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.assert('0x0123456789abcdefg')\n * // @error: Hex.InvalidHexValueError: Value `0x0123456789abcdefg` is an invalid hex value.\n * // @error: Hex values must start with `\"0x\"` and contain only hexadecimal characters (0-9, a-f, A-F).\n * ```\n */\nexport class InvalidHexValueError extends Errors.BaseError {\n constructor(value) {\n super(`Value \\`${value}\\` is an invalid hex value.`, {\n metaMessages: [\n 'Hex values must start with `\"0x\"` and contain only hexadecimal characters (0-9, a-f, A-F).',\n ],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Hex.InvalidHexValueError'\n });\n }\n}\n/**\n * Thrown when the provided hex value is an odd length.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.fromHex('0xabcde')\n * // @error: Hex.InvalidLengthError: Hex value `\"0xabcde\"` is an odd length (5 nibbles).\n * ```\n */\nexport class InvalidLengthError extends Errors.BaseError {\n constructor(value) {\n super(`Hex value \\`\"${value}\"\\` is an odd length (${value.length - 2} nibbles).`, {\n metaMessages: ['It must be an even length.'],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Hex.InvalidLengthError'\n });\n }\n}\n/**\n * Thrown when the size of the value exceeds the expected max size.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromString('Hello World!', { size: 8 })\n * // @error: Hex.SizeOverflowError: Size cannot exceed `8` bytes. Given size: `12` bytes.\n * ```\n */\nexport class SizeOverflowError extends Errors.BaseError {\n constructor({ givenSize, maxSize }) {\n super(`Size cannot exceed \\`${maxSize}\\` bytes. Given size: \\`${givenSize}\\` bytes.`);\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Hex.SizeOverflowError'\n });\n }\n}\n/**\n * Thrown when the slice offset exceeds the bounds of the value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.slice('0x0123456789', 6)\n * // @error: Hex.SliceOffsetOutOfBoundsError: Slice starting at offset `6` is out-of-bounds (size: `5`).\n * ```\n */\nexport class SliceOffsetOutOfBoundsError extends Errors.BaseError {\n constructor({ offset, position, size, }) {\n super(`Slice ${position === 'start' ? 'starting' : 'ending'} at offset \\`${offset}\\` is out-of-bounds (size: \\`${size}\\`).`);\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Hex.SliceOffsetOutOfBoundsError'\n });\n }\n}\n/**\n * Thrown when the size of the value exceeds the pad size.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.padLeft('0x1a4e12a45a21323123aaa87a897a897a898a6567a578a867a98778a667a85a875a87a6a787a65a675a6a9', 32)\n * // @error: Hex.SizeExceedsPaddingSizeError: Hex size (`43`) exceeds padding size (`32`).\n * ```\n */\nexport class SizeExceedsPaddingSizeError extends Errors.BaseError {\n constructor({ size, targetSize, type, }) {\n super(`${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (\\`${size}\\`) exceeds padding size (\\`${targetSize}\\`).`);\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Hex.SizeExceedsPaddingSizeError'\n });\n }\n}\n//# sourceMappingURL=Hex.js.map","import { equalBytes } from '@noble/curves/abstract/utils';\nimport * as Errors from './Errors.js';\nimport * as Hex from './Hex.js';\nimport * as Json from './Json.js';\nimport * as internal from './internal/bytes.js';\nimport * as internal_hex from './internal/hex.js';\nconst decoder = /*#__PURE__*/ new TextDecoder();\nconst encoder = /*#__PURE__*/ new TextEncoder();\n/**\n * Asserts if the given value is {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.assert('abc')\n * // @error: Bytes.InvalidBytesTypeError:\n * // @error: Value `\"abc\"` of type `string` is an invalid Bytes value.\n * // @error: Bytes values must be of type `Uint8Array`.\n * ```\n *\n * @param value - Value to assert.\n */\nexport function assert(value) {\n if (value instanceof Uint8Array)\n return;\n if (!value)\n throw new InvalidBytesTypeError(value);\n if (typeof value !== 'object')\n throw new InvalidBytesTypeError(value);\n if (!('BYTES_PER_ELEMENT' in value))\n throw new InvalidBytesTypeError(value);\n if (value.BYTES_PER_ELEMENT !== 1 || value.constructor.name !== 'Uint8Array')\n throw new InvalidBytesTypeError(value);\n}\n/**\n * Concatenates two or more {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const bytes = Bytes.concat(\n * Bytes.from([1]),\n * Bytes.from([69]),\n * Bytes.from([420, 69]),\n * )\n * // @log: Uint8Array [ 1, 69, 420, 69 ]\n * ```\n *\n * @param values - Values to concatenate.\n * @returns Concatenated {@link ox#Bytes.Bytes}.\n */\nexport function concat(...values) {\n let length = 0;\n for (const arr of values) {\n length += arr.length;\n }\n const result = new Uint8Array(length);\n for (let i = 0, index = 0; i < values.length; i++) {\n const arr = values[i];\n result.set(arr, index);\n index += arr.length;\n }\n return result;\n}\n/**\n * Instantiates a {@link ox#Bytes.Bytes} value from a `Uint8Array`, a hex string, or an array of unsigned 8-bit integers.\n *\n * :::tip\n *\n * To instantiate from a **Boolean**, **String**, or **Number**, use one of the following:\n *\n * - `Bytes.fromBoolean`\n *\n * - `Bytes.fromString`\n *\n * - `Bytes.fromNumber`\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.from([255, 124, 5, 4])\n * // @log: Uint8Array([255, 124, 5, 4])\n *\n * const data = Bytes.from('0xdeadbeef')\n * // @log: Uint8Array([222, 173, 190, 239])\n * ```\n *\n * @param value - Value to convert.\n * @returns A {@link ox#Bytes.Bytes} instance.\n */\nexport function from(value) {\n if (value instanceof Uint8Array)\n return value;\n if (typeof value === 'string')\n return fromHex(value);\n return fromArray(value);\n}\n/**\n * Converts an array of unsigned 8-bit integers into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromArray([255, 124, 5, 4])\n * // @log: Uint8Array([255, 124, 5, 4])\n * ```\n *\n * @param value - Value to convert.\n * @returns A {@link ox#Bytes.Bytes} instance.\n */\nexport function fromArray(value) {\n return value instanceof Uint8Array ? value : new Uint8Array(value);\n}\n/**\n * Encodes a boolean value into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromBoolean(true)\n * // @log: Uint8Array([1])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromBoolean(true, { size: 32 })\n * // @log: Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])\n * ```\n *\n * @param value - Boolean value to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromBoolean(value, options = {}) {\n const { size } = options;\n const bytes = new Uint8Array(1);\n bytes[0] = Number(value);\n if (typeof size === 'number') {\n internal.assertSize(bytes, size);\n return padLeft(bytes, size);\n }\n return bytes;\n}\n/**\n * Encodes a {@link ox#Hex.Hex} value into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromHex('0x48656c6c6f20776f726c6421')\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromHex('0x48656c6c6f20776f726c6421', { size: 32 })\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n * ```\n *\n * @param value - {@link ox#Hex.Hex} value to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromHex(value, options = {}) {\n const { size } = options;\n let hex = value;\n if (size) {\n internal_hex.assertSize(value, size);\n hex = Hex.padRight(value, size);\n }\n let hexString = hex.slice(2);\n if (hexString.length % 2)\n hexString = `0${hexString}`;\n const length = hexString.length / 2;\n const bytes = new Uint8Array(length);\n for (let index = 0, j = 0; index < length; index++) {\n const nibbleLeft = internal.charCodeToBase16(hexString.charCodeAt(j++));\n const nibbleRight = internal.charCodeToBase16(hexString.charCodeAt(j++));\n if (nibbleLeft === undefined || nibbleRight === undefined) {\n throw new Errors.BaseError(`Invalid byte sequence (\"${hexString[j - 2]}${hexString[j - 1]}\" in \"${hexString}\").`);\n }\n bytes[index] = nibbleLeft * 16 + nibbleRight;\n }\n return bytes;\n}\n/**\n * Encodes a number value into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromNumber(420)\n * // @log: Uint8Array([1, 164])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromNumber(420, { size: 4 })\n * // @log: Uint8Array([0, 0, 1, 164])\n * ```\n *\n * @param value - Number value to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromNumber(value, options) {\n const hex = Hex.fromNumber(value, options);\n return fromHex(hex);\n}\n/**\n * Encodes a string into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromString('Hello world!')\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromString('Hello world!', { size: 32 })\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n * ```\n *\n * @param value - String to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromString(value, options = {}) {\n const { size } = options;\n const bytes = encoder.encode(value);\n if (typeof size === 'number') {\n internal.assertSize(bytes, size);\n return padRight(bytes, size);\n }\n return bytes;\n}\n/**\n * Checks if two {@link ox#Bytes.Bytes} values are equal.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.isEqual(Bytes.from([1]), Bytes.from([1]))\n * // @log: true\n *\n * Bytes.isEqual(Bytes.from([1]), Bytes.from([2]))\n * // @log: false\n * ```\n *\n * @param bytesA - First {@link ox#Bytes.Bytes} value.\n * @param bytesB - Second {@link ox#Bytes.Bytes} value.\n * @returns `true` if the two values are equal, otherwise `false`.\n */\nexport function isEqual(bytesA, bytesB) {\n return equalBytes(bytesA, bytesB);\n}\n/**\n * Pads a {@link ox#Bytes.Bytes} value to the left with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.padLeft(Bytes.from([1]), 4)\n * // @log: Uint8Array([0, 0, 0, 1])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value to pad.\n * @param size - Size to pad the {@link ox#Bytes.Bytes} value to.\n * @returns Padded {@link ox#Bytes.Bytes} value.\n */\nexport function padLeft(value, size) {\n return internal.pad(value, { dir: 'left', size });\n}\n/**\n * Pads a {@link ox#Bytes.Bytes} value to the right with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.padRight(Bytes.from([1]), 4)\n * // @log: Uint8Array([1, 0, 0, 0])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value to pad.\n * @param size - Size to pad the {@link ox#Bytes.Bytes} value to.\n * @returns Padded {@link ox#Bytes.Bytes} value.\n */\nexport function padRight(value, size) {\n return internal.pad(value, { dir: 'right', size });\n}\n/**\n * Generates random {@link ox#Bytes.Bytes} of the specified length.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const bytes = Bytes.random(32)\n * // @log: Uint8Array([... x32])\n * ```\n *\n * @param length - Length of the random {@link ox#Bytes.Bytes} to generate.\n * @returns Random {@link ox#Bytes.Bytes} of the specified length.\n */\nexport function random(length) {\n return crypto.getRandomValues(new Uint8Array(length));\n}\n/**\n * Retrieves the size of a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.size(Bytes.from([1, 2, 3, 4]))\n * // @log: 4\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value.\n * @returns Size of the {@link ox#Bytes.Bytes} value.\n */\nexport function size(value) {\n return value.length;\n}\n/**\n * Returns a section of a {@link ox#Bytes.Bytes} value given a start/end bytes offset.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.slice(\n * Bytes.from([1, 2, 3, 4, 5, 6, 7, 8, 9]),\n * 1,\n * 4,\n * )\n * // @log: Uint8Array([2, 3, 4])\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} value.\n * @param start - Start offset.\n * @param end - End offset.\n * @param options - Slice options.\n * @returns Sliced {@link ox#Bytes.Bytes} value.\n */\nexport function slice(value, start, end, options = {}) {\n const { strict } = options;\n internal.assertStartOffset(value, start);\n const value_ = value.slice(start, end);\n if (strict)\n internal.assertEndOffset(value_, start, end);\n return value_;\n}\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a bigint.\n *\n * @example\n * ```ts\n * import { Bytes } from 'ox'\n *\n * Bytes.toBigInt(Bytes.from([1, 164]))\n * // @log: 420n\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Decoding options.\n * @returns Decoded bigint.\n */\nexport function toBigInt(bytes, options = {}) {\n const { size } = options;\n if (typeof size !== 'undefined')\n internal.assertSize(bytes, size);\n const hex = Hex.fromBytes(bytes, options);\n return Hex.toBigInt(hex, options);\n}\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a boolean.\n *\n * @example\n * ```ts\n * import { Bytes } from 'ox'\n *\n * Bytes.toBoolean(Bytes.from([1]))\n * // @log: true\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Decoding options.\n * @returns Decoded boolean.\n */\nexport function toBoolean(bytes, options = {}) {\n const { size } = options;\n let bytes_ = bytes;\n if (typeof size !== 'undefined') {\n internal.assertSize(bytes_, size);\n bytes_ = trimLeft(bytes_);\n }\n if (bytes_.length > 1 || bytes_[0] > 1)\n throw new InvalidBytesBooleanError(bytes_);\n return Boolean(bytes_[0]);\n}\n/**\n * Encodes a {@link ox#Bytes.Bytes} value into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.toHex(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // '0x48656c6c6f20576f726c6421'\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Options.\n * @returns Decoded {@link ox#Hex.Hex} value.\n */\nexport function toHex(value, options = {}) {\n return Hex.fromBytes(value, options);\n}\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a number.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.toNumber(Bytes.from([1, 164]))\n * // @log: 420\n * ```\n */\nexport function toNumber(bytes, options = {}) {\n const { size } = options;\n if (typeof size !== 'undefined')\n internal.assertSize(bytes, size);\n const hex = Hex.fromBytes(bytes, options);\n return Hex.toNumber(hex, options);\n}\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a string.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.toString(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // @log: 'Hello world'\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Options.\n * @returns Decoded string.\n */\nexport function toString(bytes, options = {}) {\n const { size } = options;\n let bytes_ = bytes;\n if (typeof size !== 'undefined') {\n internal.assertSize(bytes_, size);\n bytes_ = trimRight(bytes_);\n }\n return decoder.decode(bytes_);\n}\n/**\n * Trims leading zeros from a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.trimLeft(Bytes.from([0, 0, 0, 0, 1, 2, 3]))\n * // @log: Uint8Array([1, 2, 3])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value.\n * @returns Trimmed {@link ox#Bytes.Bytes} value.\n */\nexport function trimLeft(value) {\n return internal.trim(value, { dir: 'left' });\n}\n/**\n * Trims trailing zeros from a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.trimRight(Bytes.from([1, 2, 3, 0, 0, 0, 0]))\n * // @log: Uint8Array([1, 2, 3])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value.\n * @returns Trimmed {@link ox#Bytes.Bytes} value.\n */\nexport function trimRight(value) {\n return internal.trim(value, { dir: 'right' });\n}\n/**\n * Checks if the given value is {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.validate('0x')\n * // @log: false\n *\n * Bytes.validate(Bytes.from([1, 2, 3]))\n * // @log: true\n * ```\n *\n * @param value - Value to check.\n * @returns `true` if the value is {@link ox#Bytes.Bytes}, otherwise `false`.\n */\nexport function validate(value) {\n try {\n assert(value);\n return true;\n }\n catch {\n return false;\n }\n}\n/**\n * Thrown when the bytes value cannot be represented as a boolean.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.toBoolean(Bytes.from([5]))\n * // @error: Bytes.InvalidBytesBooleanError: Bytes value `[5]` is not a valid boolean.\n * // @error: The bytes array must contain a single byte of either a `0` or `1` value.\n * ```\n */\nexport class InvalidBytesBooleanError extends Errors.BaseError {\n constructor(bytes) {\n super(`Bytes value \\`${bytes}\\` is not a valid boolean.`, {\n metaMessages: [\n 'The bytes array must contain a single byte of either a `0` or `1` value.',\n ],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Bytes.InvalidBytesBooleanError'\n });\n }\n}\n/**\n * Thrown when a value cannot be converted to bytes.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Bytes } from 'ox'\n *\n * Bytes.from('foo')\n * // @error: Bytes.InvalidBytesTypeError: Value `foo` of type `string` is an invalid Bytes value.\n * ```\n */\nexport class InvalidBytesTypeError extends Errors.BaseError {\n constructor(value) {\n super(`Value \\`${typeof value === 'object' ? Json.stringify(value) : value}\\` of type \\`${typeof value}\\` is an invalid Bytes value.`, {\n metaMessages: ['Bytes values must be of type `Bytes`.'],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Bytes.InvalidBytesTypeError'\n });\n }\n}\n/**\n * Thrown when a size exceeds the maximum allowed size.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.fromString('Hello World!', { size: 8 })\n * // @error: Bytes.SizeOverflowError: Size cannot exceed `8` bytes. Given size: `12` bytes.\n * ```\n */\nexport class SizeOverflowError extends Errors.BaseError {\n constructor({ givenSize, maxSize }) {\n super(`Size cannot exceed \\`${maxSize}\\` bytes. Given size: \\`${givenSize}\\` bytes.`);\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Bytes.SizeOverflowError'\n });\n }\n}\n/**\n * Thrown when a slice offset is out-of-bounds.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.slice(Bytes.from([1, 2, 3]), 4)\n * // @error: Bytes.SliceOffsetOutOfBoundsError: Slice starting at offset `4` is out-of-bounds (size: `3`).\n * ```\n */\nexport class SliceOffsetOutOfBoundsError extends Errors.BaseError {\n constructor({ offset, position, size, }) {\n super(`Slice ${position === 'start' ? 'starting' : 'ending'} at offset \\`${offset}\\` is out-of-bounds (size: \\`${size}\\`).`);\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Bytes.SliceOffsetOutOfBoundsError'\n });\n }\n}\n/**\n * Thrown when a the padding size exceeds the maximum allowed size.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.padLeft(Bytes.fromString('Hello World!'), 8)\n * // @error: [Bytes.SizeExceedsPaddingSizeError: Bytes size (`12`) exceeds padding size (`8`).\n * ```\n */\nexport class SizeExceedsPaddingSizeError extends Errors.BaseError {\n constructor({ size, targetSize, type, }) {\n super(`${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (\\`${size}\\`) exceeds padding size (\\`${targetSize}\\`).`);\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Bytes.SizeExceedsPaddingSizeError'\n });\n }\n}\n//# sourceMappingURL=Bytes.js.map","import { ripemd160 as noble_ripemd160 } from '@noble/hashes/ripemd160';\nimport { keccak_256 as noble_keccak256 } from '@noble/hashes/sha3';\nimport { sha256 as noble_sha256 } from '@noble/hashes/sha256';\nimport * as Bytes from './Bytes.js';\nimport * as Hex from './Hex.js';\n/**\n * Calculates the [Keccak256](https://en.wikipedia.org/wiki/SHA-3) hash of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `keccak_256` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.keccak256('0xdeadbeef')\n * // @log: '0xd4fd4e189132273036449fc9e11198c739161b4c0116a9a2dccdfa1c492006f1'\n * ```\n *\n * @example\n * ### Calculate Hash of a String\n *\n * ```ts twoslash\n * import { Hash, Hex } from 'ox'\n *\n * Hash.keccak256(Hex.fromString('hello world'))\n * // @log: '0x3ea2f1d0abf3fc66cf29eebb70cbd4e7fe762ef8a09bcc06c8edf641230afec0'\n * ```\n *\n * @example\n * ### Configure Return Type\n *\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.keccak256('0xdeadbeef', { as: 'Bytes' })\n * // @log: Uint8Array [...]\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns Keccak256 hash.\n */\nexport function keccak256(value, options = {}) {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options;\n const bytes = noble_keccak256(Bytes.from(value));\n if (as === 'Bytes')\n return bytes;\n return Hex.fromBytes(bytes);\n}\n/**\n * Calculates the [Ripemd160](https://en.wikipedia.org/wiki/RIPEMD) hash of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `ripemd160` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.ripemd160('0xdeadbeef')\n * // '0x226821c2f5423e11fe9af68bd285c249db2e4b5a'\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns Ripemd160 hash.\n */\nexport function ripemd160(value, options = {}) {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options;\n const bytes = noble_ripemd160(Bytes.from(value));\n if (as === 'Bytes')\n return bytes;\n return Hex.fromBytes(bytes);\n}\n/**\n * Calculates the [Sha256](https://en.wikipedia.org/wiki/SHA-256) hash of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `sha256` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.sha256('0xdeadbeef')\n * // '0x5f78c33274e43fa9de5659265c1d917e25c03722dcb0b8d27db8d5feaa813953'\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns Sha256 hash.\n */\nexport function sha256(value, options = {}) {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options;\n const bytes = noble_sha256(Bytes.from(value));\n if (as === 'Bytes')\n return bytes;\n return Hex.fromBytes(bytes);\n}\n/**\n * Checks if a string is a valid hash value.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.validate('0x')\n * // @log: false\n *\n * Hash.validate('0x3ea2f1d0abf3fc66cf29eebb70cbd4e7fe762ef8a09bcc06c8edf641230afec0')\n * // @log: true\n * ```\n *\n * @param value - Value to check.\n * @returns Whether the value is a valid hash.\n */\nexport function validate(value) {\n return Hex.validate(value) && Hex.size(value) === 32;\n}\n//# sourceMappingURL=Hash.js.map","/**\n * @internal\n *\n * Map with a LRU (Least recently used) policy.\n * @see https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n */\nexport class LruMap extends Map {\n constructor(size) {\n super();\n Object.defineProperty(this, \"maxSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.maxSize = size;\n }\n get(key) {\n const value = super.get(key);\n if (super.has(key) && value !== undefined) {\n this.delete(key);\n super.set(key, value);\n }\n return value;\n }\n set(key, value) {\n super.set(key, value);\n if (this.maxSize && this.size > this.maxSize) {\n const firstKey = this.keys().next().value;\n if (firstKey)\n this.delete(firstKey);\n }\n return this;\n }\n}\n//# sourceMappingURL=lru.js.map","import { LruMap } from './internal/lru.js';\nconst caches = {\n checksum: /*#__PURE__*/ new LruMap(8192),\n};\nexport const checksum = caches.checksum;\n/**\n * Clears all global caches.\n *\n * @example\n * ```ts\n * import { Caches } from 'ox'\n * Caches.clear()\n * ```\n */\nexport function clear() {\n for (const cache of Object.values(caches))\n cache.clear();\n}\n//# sourceMappingURL=Caches.js.map","import * as Bytes from './Bytes.js';\nimport * as Errors from './Errors.js';\nimport * as Hex from './Hex.js';\nimport * as Json from './Json.js';\n/**\n * Asserts that a {@link ox#PublicKey.PublicKey} is valid.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * PublicKey.assert({\n * prefix: 4,\n * y: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * })\n * // @error: PublicKey.InvalidError: Value \\`{\"y\":\"1\"}\\` is not a valid public key.\n * // @error: Public key must contain:\n * // @error: - an `x` and `prefix` value (compressed)\n * // @error: - an `x`, `y`, and `prefix` value (uncompressed)\n * ```\n *\n * @param publicKey - The public key object to assert.\n */\nexport function assert(publicKey, options = {}) {\n const { compressed } = options;\n const { prefix, x, y } = publicKey;\n // Uncompressed\n if (compressed === false ||\n (typeof x === 'bigint' && typeof y === 'bigint')) {\n if (prefix !== 4)\n throw new InvalidPrefixError({\n prefix,\n cause: new InvalidUncompressedPrefixError(),\n });\n return;\n }\n // Compressed\n if (compressed === true ||\n (typeof x === 'bigint' && typeof y === 'undefined')) {\n if (prefix !== 3 && prefix !== 2)\n throw new InvalidPrefixError({\n prefix,\n cause: new InvalidCompressedPrefixError(),\n });\n return;\n }\n // Unknown/invalid\n throw new InvalidError({ publicKey });\n}\n/**\n * Compresses a {@link ox#PublicKey.PublicKey}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n *\n * const compressed = PublicKey.compress(publicKey) // [!code focus]\n * // @log: {\n * // @log: prefix: 3,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: }\n * ```\n *\n * @param publicKey - The public key to compress.\n * @returns The compressed public key.\n */\nexport function compress(publicKey) {\n const { x, y } = publicKey;\n return {\n prefix: y % 2n === 0n ? 2 : 3,\n x,\n };\n}\n/**\n * Instantiates a typed {@link ox#PublicKey.PublicKey} object from a {@link ox#PublicKey.PublicKey}, {@link ox#Bytes.Bytes}, or {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @example\n * ### From Serialized\n *\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from('0x048318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5')\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @param value - The public key value to instantiate.\n * @returns The instantiated {@link ox#PublicKey.PublicKey}.\n */\nexport function from(value) {\n const publicKey = (() => {\n if (Hex.validate(value))\n return fromHex(value);\n if (Bytes.validate(value))\n return fromBytes(value);\n const { prefix, x, y } = value;\n if (typeof x === 'bigint' && typeof y === 'bigint')\n return { prefix: prefix ?? 0x04, x, y };\n return { prefix, x };\n })();\n assert(publicKey);\n return publicKey;\n}\n/**\n * Deserializes a {@link ox#PublicKey.PublicKey} from a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.fromBytes(new Uint8Array([128, 3, 131, ...]))\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @param publicKey - The serialized public key.\n * @returns The deserialized public key.\n */\nexport function fromBytes(publicKey) {\n return fromHex(Hex.fromBytes(publicKey));\n}\n/**\n * Deserializes a {@link ox#PublicKey.PublicKey} from a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.fromHex('0x8318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5')\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @example\n * ### Deserializing a Compressed Public Key\n *\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.fromHex('0x038318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed75')\n * // @log: {\n * // @log: prefix: 3,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: }\n * ```\n *\n * @param publicKey - The serialized public key.\n * @returns The deserialized public key.\n */\nexport function fromHex(publicKey) {\n if (publicKey.length !== 132 &&\n publicKey.length !== 130 &&\n publicKey.length !== 68)\n throw new InvalidSerializedSizeError({ publicKey });\n if (publicKey.length === 130) {\n const x = BigInt(Hex.slice(publicKey, 0, 32));\n const y = BigInt(Hex.slice(publicKey, 32, 64));\n return {\n prefix: 4,\n x,\n y,\n };\n }\n if (publicKey.length === 132) {\n const prefix = Number(Hex.slice(publicKey, 0, 1));\n const x = BigInt(Hex.slice(publicKey, 1, 33));\n const y = BigInt(Hex.slice(publicKey, 33, 65));\n return {\n prefix,\n x,\n y,\n };\n }\n const prefix = Number(Hex.slice(publicKey, 0, 1));\n const x = BigInt(Hex.slice(publicKey, 1, 33));\n return {\n prefix,\n x,\n };\n}\n/**\n * Serializes a {@link ox#PublicKey.PublicKey} to {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n *\n * const bytes = PublicKey.toBytes(publicKey) // [!code focus]\n * // @log: Uint8Array [128, 3, 131, ...]\n * ```\n *\n * @param publicKey - The public key to serialize.\n * @returns The serialized public key.\n */\nexport function toBytes(publicKey, options = {}) {\n return Bytes.fromHex(toHex(publicKey, options));\n}\n/**\n * Serializes a {@link ox#PublicKey.PublicKey} to {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n *\n * const hex = PublicKey.toHex(publicKey) // [!code focus]\n * // @log: '0x048318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5'\n * ```\n *\n * @param publicKey - The public key to serialize.\n * @returns The serialized public key.\n */\nexport function toHex(publicKey, options = {}) {\n assert(publicKey);\n const { prefix, x, y } = publicKey;\n const { includePrefix = true } = options;\n const publicKey_ = Hex.concat(includePrefix ? Hex.fromNumber(prefix, { size: 1 }) : '0x', Hex.fromNumber(x, { size: 32 }), \n // If the public key is not compressed, add the y coordinate.\n typeof y === 'bigint' ? Hex.fromNumber(y, { size: 32 }) : '0x');\n return publicKey_;\n}\n/**\n * Validates a {@link ox#PublicKey.PublicKey}. Returns `true` if valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const valid = PublicKey.validate({\n * prefix: 4,\n * y: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * })\n * // @log: false\n * ```\n *\n * @param publicKey - The public key object to assert.\n */\nexport function validate(publicKey, options = {}) {\n try {\n assert(publicKey, options);\n return true;\n }\n catch (error) {\n return false;\n }\n}\n/**\n * Thrown when a public key is invalid.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * PublicKey.assert({ y: 1n })\n * // @error: PublicKey.InvalidError: Value `{\"y\":1n}` is not a valid public key.\n * // @error: Public key must contain:\n * // @error: - an `x` and `prefix` value (compressed)\n * // @error: - an `x`, `y`, and `prefix` value (uncompressed)\n * ```\n */\nexport class InvalidError extends Errors.BaseError {\n constructor({ publicKey }) {\n super(`Value \\`${Json.stringify(publicKey)}\\` is not a valid public key.`, {\n metaMessages: [\n 'Public key must contain:',\n '- an `x` and `prefix` value (compressed)',\n '- an `x`, `y`, and `prefix` value (uncompressed)',\n ],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'PublicKey.InvalidError'\n });\n }\n}\n/** Thrown when a public key has an invalid prefix. */\nexport class InvalidPrefixError extends Errors.BaseError {\n constructor({ prefix, cause }) {\n super(`Prefix \"${prefix}\" is invalid.`, {\n cause,\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'PublicKey.InvalidPrefixError'\n });\n }\n}\n/** Thrown when the public key has an invalid prefix for a compressed public key. */\nexport class InvalidCompressedPrefixError extends Errors.BaseError {\n constructor() {\n super('Prefix must be 2 or 3 for compressed public keys.');\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'PublicKey.InvalidCompressedPrefixError'\n });\n }\n}\n/** Thrown when the public key has an invalid prefix for an uncompressed public key. */\nexport class InvalidUncompressedPrefixError extends Errors.BaseError {\n constructor() {\n super('Prefix must be 4 for uncompressed public keys.');\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'PublicKey.InvalidUncompressedPrefixError'\n });\n }\n}\n/** Thrown when the public key has an invalid serialized size. */\nexport class InvalidSerializedSizeError extends Errors.BaseError {\n constructor({ publicKey }) {\n super(`Value \\`${publicKey}\\` is an invalid public key size.`, {\n metaMessages: [\n 'Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).',\n `Received ${Hex.size(Hex.from(publicKey))} bytes.`,\n ],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'PublicKey.InvalidSerializedSizeError'\n });\n }\n}\n//# sourceMappingURL=PublicKey.js.map","import * as Bytes from './Bytes.js';\nimport * as Caches from './Caches.js';\nimport * as Errors from './Errors.js';\nimport * as Hash from './Hash.js';\nimport * as PublicKey from './PublicKey.js';\nconst addressRegex = /*#__PURE__*/ /^0x[a-fA-F0-9]{40}$/;\n/**\n * Asserts that the given value is a valid {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.assert('0xA0Cf798816D4b9b9866b5330EEa46a18382f251e')\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.assert('0xdeadbeef')\n * // @error: InvalidAddressError: Address \"0xdeadbeef\" is invalid.\n * ```\n *\n * @param value - Value to assert if it is a valid address.\n * @param options - Assertion options.\n */\nexport function assert(value, options = {}) {\n const { strict = true } = options;\n if (!addressRegex.test(value))\n throw new InvalidAddressError({\n address: value,\n cause: new InvalidInputError(),\n });\n if (strict) {\n if (value.toLowerCase() === value)\n return;\n if (checksum(value) !== value)\n throw new InvalidAddressError({\n address: value,\n cause: new InvalidChecksumError(),\n });\n }\n}\n/**\n * Computes the checksum address for the given {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.checksum('0xa0cf798816d4b9b9866b5330eea46a18382f251e')\n * // @log: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'\n * ```\n *\n * @param address - The address to compute the checksum for.\n * @returns The checksummed address.\n */\nexport function checksum(address) {\n if (Caches.checksum.has(address))\n return Caches.checksum.get(address);\n assert(address, { strict: false });\n const hexAddress = address.substring(2).toLowerCase();\n const hash = Hash.keccak256(Bytes.fromString(hexAddress), { as: 'Bytes' });\n const characters = hexAddress.split('');\n for (let i = 0; i < 40; i += 2) {\n if (hash[i >> 1] >> 4 >= 8 && characters[i]) {\n characters[i] = characters[i].toUpperCase();\n }\n if ((hash[i >> 1] & 0x0f) >= 8 && characters[i + 1]) {\n characters[i + 1] = characters[i + 1].toUpperCase();\n }\n }\n const result = `0x${characters.join('')}`;\n Caches.checksum.set(address, result);\n return result;\n}\n/**\n * Converts a stringified address to a typed (checksummed) {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('0xa0cf798816d4b9b9866b5330eea46a18382f251e')\n * // @log: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('0xa0cf798816d4b9b9866b5330eea46a18382f251e', {\n * checksum: false\n * })\n * // @log: '0xa0cf798816d4b9b9866b5330eea46a18382f251e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('hello')\n * // @error: InvalidAddressError: Address \"0xa\" is invalid.\n * ```\n *\n * @param address - An address string to convert to a typed Address.\n * @param options - Conversion options.\n * @returns The typed Address.\n */\nexport function from(address, options = {}) {\n const { checksum: checksumVal = false } = options;\n assert(address);\n if (checksumVal)\n return checksum(address);\n return address;\n}\n/**\n * Converts an ECDSA public key to an {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address, PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from(\n * '0x048318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5',\n * )\n * const address = Address.fromPublicKey(publicKey)\n * // @log: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266'\n * ```\n *\n * @param publicKey - The ECDSA public key to convert to an {@link ox#Address.Address}.\n * @param options - Conversion options.\n * @returns The {@link ox#Address.Address} corresponding to the public key.\n */\nexport function fromPublicKey(publicKey, options = {}) {\n const address = Hash.keccak256(`0x${PublicKey.toHex(publicKey).slice(4)}`).substring(26);\n return from(`0x${address}`, options);\n}\n/**\n * Checks if two {@link ox#Address.Address} are equal.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.isEqual(\n * '0xa0cf798816d4b9b9866b5330eea46a18382f251e',\n * '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'\n * )\n * // @log: true\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.isEqual(\n * '0xa0cf798816d4b9b9866b5330eea46a18382f251e',\n * '0xA0Cf798816D4b9b9866b5330EEa46a18382f251f'\n * )\n * // @log: false\n * ```\n *\n * @param addressA - The first address to compare.\n * @param addressB - The second address to compare.\n * @returns Whether the addresses are equal.\n */\nexport function isEqual(addressA, addressB) {\n assert(addressA, { strict: false });\n assert(addressB, { strict: false });\n return addressA.toLowerCase() === addressB.toLowerCase();\n}\n/**\n * Checks if the given address is a valid {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.validate('0xA0Cf798816D4b9b9866b5330EEa46a18382f251e')\n * // @log: true\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.validate('0xdeadbeef')\n * // @log: false\n * ```\n *\n * @param address - Value to check if it is a valid address.\n * @param options - Check options.\n * @returns Whether the address is a valid address.\n */\nexport function validate(address, options = {}) {\n const { strict = true } = options ?? {};\n try {\n assert(address, { strict });\n return true;\n }\n catch {\n return false;\n }\n}\n/**\n * Thrown when an address is invalid.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('0x123')\n * // @error: Address.InvalidAddressError: Address `0x123` is invalid.\n * ```\n */\nexport class InvalidAddressError extends Errors.BaseError {\n constructor({ address, cause }) {\n super(`Address \"${address}\" is invalid.`, {\n cause,\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Address.InvalidAddressError'\n });\n }\n}\n/** Thrown when an address is not a 20 byte (40 hexadecimal character) value. */\nexport class InvalidInputError extends Errors.BaseError {\n constructor() {\n super('Address is not a 20 byte (40 hexadecimal character) value.');\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Address.InvalidInputError'\n });\n }\n}\n/** Thrown when an address does not match its checksum counterpart. */\nexport class InvalidChecksumError extends Errors.BaseError {\n constructor() {\n super('Address does not match its checksum counterpart.');\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Address.InvalidChecksumError'\n });\n }\n}\n//# sourceMappingURL=Address.js.map","function anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n// copied from utils\nfunction isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\nfunction abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\nfunction ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\nfunction aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\nexport { anumber, anumber as number, abytes, abytes as bytes, ahash, aexists, aoutput };\nconst assert = {\n number: anumber,\n bytes: abytes,\n hash: ahash,\n exists: aexists,\n output: aoutput,\n};\nexport default assert;\n//# sourceMappingURL=_assert.js.map","export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n//# sourceMappingURL=crypto.js.map","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n// The rotate left (circular left shift) operation for uint32\nexport const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0);\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n// The byte swap operation for uint32\nexport const byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nexport const byteSwapIfBE = isLE ? (n) => n : (n) => byteSwap(n);\n// In place byte swap for Uint32Array\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// 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 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\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)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('utf8ToBytes expected string, got ' + typeof str);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\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// For runtime check if class implements interface\nexport class Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nexport function wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return crypto.randomBytes(bytesLength);\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","import { aexists, aoutput } from './_assert.js';\nimport { Hash, createView, toBytes } from './utils.js';\n/**\n * Polyfill for Safari 14\n */\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/**\n * Choice: a ? b : c\n */\nexport const Chi = (a, b, c) => (a & b) ^ (~a & c);\n/**\n * Majority function, true if any two inputs is true\n */\nexport const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n 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) {\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 this.buffer.subarray(pos).fill(0);\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++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n}\n//# sourceMappingURL=_md.js.map","import { HashMD, Chi, Maj } from './_md.js';\nimport { rotr, wrapConstructor } from './utils.js';\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per late 2024.\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n// Initial state:\n// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor() {\n super(64, 32, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\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 set(A, B, C, D, E, F, G, H) {\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 process(view, offset) {\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)\n 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 roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n constructor() {\n super();\n this.A = 0xc1059ed8 | 0;\n this.B = 0x367cd507 | 0;\n this.C = 0x3070dd17 | 0;\n this.D = 0xf70e5939 | 0;\n this.E = 0xffc00b31 | 0;\n this.F = 0x68581511 | 0;\n this.G = 0x64f98fa7 | 0;\n this.H = 0xbefa4fa4 | 0;\n this.outputLen = 28;\n }\n}\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\n/**\n * SHA2-224 hash function\n */\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n//# sourceMappingURL=sha256.js.map","import { ahash, abytes, aexists } from './_assert.js';\nimport { Hash, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC extends Hash {\n constructor(hash, _key) {\n super();\n this.finished = false;\n this.destroyed = false;\n ahash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create();\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++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n abytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to || (to = Object.create(Object.getPrototypeOf(this), {}));\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport { bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, validateObject, } from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);\n// prettier-ignore\nconst _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);\n// Calculates a modulo b\nexport function mod(a, b) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num, power, modulo) {\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (modulo <= _0n)\n throw new Error('invalid modulus');\n if (modulo === _1n)\n return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n)\n res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x, power, modulo) {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n// Inverses number over modulo\nexport function invert(number, modulo) {\n if (number === _0n)\n throw new Error('invert: expected non-zero number');\n if (modulo <= _0n)\n throw new Error('invert: expected positive modulus, got ' + modulo);\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) ≡ 1 if a is a square (mod p)\n // (a | p) ≡ -1 if a is not a square (mod p)\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n let Q, S, Z;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++)\n ;\n // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++) {\n // Crash instead of infinity loop, we cannot reasonable count until P.\n if (Z > 1000)\n throw new Error('Cannot find square root: likely non-prime P');\n }\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast(Fp, n) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))\n throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO))\n return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE))\n break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\nexport function FpSqrt(P) {\n // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n // P ≡ 3 (mod 4)\n // √n = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4(Fp, n) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8(Fp, n) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // P ≡ 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\nexport function validateField(field) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(f, num, power) {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return f.ONE;\n if (power === _1n)\n return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch(f, nums) {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\nexport function FpDiv(f, lhs, rhs) {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\nexport function FpLegendre(order) {\n // (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n // (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreConst = (order - _1n) / _2n; // Integer arithmetic\n return (f, x) => f.pow(x, legendreConst);\n}\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(f) {\n const legendre = FpLegendre(f.ORDER);\n return (x) => {\n const p = legendre(f, x);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n// CURVE.n lengths\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * NOTE: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you doing.\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER, bitLen, isLE = false, redef = {}) {\n if (ORDER <= _0n)\n throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048)\n throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n let sqrtP; // cached sqrtP\n const f = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt ||\n ((n) => {\n if (!sqrtP)\n sqrtP = FpSqrt(ORDER);\n return sqrtP(f, n);\n }),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n });\n return Object.freeze(f);\n}\nexport function FpSqrtOdd(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nexport function FpSqrtEven(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(hash, groupOrder, isLE = false) {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { validateField, nLength } from './modular.js';\nimport { validateObject, bitLen } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nfunction constTimeNegate(condition, item) {\n const neg = item.negate();\n return condition ? neg : item;\n}\nfunction validateW(W, bits) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\nfunction calcWOpts(W, bits) {\n validateW(W, bits);\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n}\nfunction validateMSMPoints(points, c) {\n if (!Array.isArray(points))\n throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars, field) {\n if (!Array.isArray(scalars))\n throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s))\n throw new Error('invalid scalar at index ' + i);\n });\n}\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)\nfunction getW(P) {\n return pointWindowSizes.get(P) || 1;\n}\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF(c, bits) {\n return {\n constTimeNegate,\n hasPrecomputes(elm) {\n return getW(elm) !== 1;\n },\n // non-const time multiplication ladder\n unsafeLadder(elm, n, p = c.ZERO) {\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param elm Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm, W) {\n const { windows, windowSize } = calcWOpts(W, bits);\n const points = [];\n let p = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = calcWOpts(W, bits);\n let p = c.ZERO;\n let f = c.BASE;\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n // Shift number by W bits.\n n >>= shiftBy;\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n // 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 // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n }\n else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {\n const { windows, windowSize } = calcWOpts(W, bits);\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n if (n === _0n)\n break; // No need to go over empty scalar\n // Extract W bits.\n let wbits = Number(n & mask);\n // Shift number by W bits.\n n >>= shiftBy;\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n if (wbits === 0)\n continue;\n let curr = precomputes[offset + Math.abs(wbits) - 1]; // -1 because we skip zero\n if (wbits < 0)\n curr = curr.negate();\n // NOTE: by re-using acc, we can save a lot of additions in case of MSM\n acc = acc.add(curr);\n }\n return acc;\n },\n getPrecomputes(W, P, transform) {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W);\n if (W !== 1)\n pointPrecomputes.set(P, transform(comp));\n }\n return comp;\n },\n wNAFCached(P, n, transform) {\n const W = getW(P);\n return this.wNAF(W, this.getPrecomputes(W, P, transform), n);\n },\n wNAFCachedUnsafe(P, n, transform, prev) {\n const W = getW(P);\n if (W === 1)\n return this.unsafeLadder(P, n, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);\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 setWindowSize(P, W) {\n validateW(W, bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n },\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 with 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 fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka private keys / bigints)\n */\nexport function pippenger(c, fieldN, points, scalars) {\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 validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n if (points.length !== scalars.length)\n throw new Error('arrays of points and scalars must have equal length');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(points.length));\n const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits\n const MASK = (1 << windowSize) - 1;\n const buckets = new Array(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 < scalars.length; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & BigInt(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)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe(c, fieldN, points, windowSize) {\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 × 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 × 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 × 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 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 = BigInt((1 << windowSize) - 1);\n const tables = points.map((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) => {\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)\n for (let j = 0; j < windowSize; j++)\n 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)\n continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\nexport function validateBasic(curve) {\n validateField(curve.Fp);\n validateObject(curve, {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n }, {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n });\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n });\n}\n//# sourceMappingURL=curve.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Short Weierstrass curve. The formula is: y² = x³ + ax + b\nimport { validateBasic, wNAF, pippenger, } from './curve.js';\nimport * as mod from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes, memoized, abool } from './utils.js';\nfunction validateSigVerOpts(opts) {\n if (opts.lowS !== undefined)\n abool('lowS', opts.lowS);\n if (opts.prehash !== undefined)\n abool('prehash', opts.prehash);\n}\nfunction validatePointOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n a: 'field',\n b: 'field',\n }, {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n });\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('invalid endomorphism, can only be defined for Koblitz curves that have a=0');\n }\n if (typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function') {\n throw new Error('invalid endomorphism, expected beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts });\n}\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\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: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER = {\n // asn.1 DER encoding utils\n Err: class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n },\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag, data) => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length & 1)\n throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = ut.numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 128)\n throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? ut.numberToHexUnpadded((len.length / 2) | 128) : '';\n const t = ut.numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag, data) {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag)\n throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong)\n length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 127;\n if (!lenLen)\n throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4)\n throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen)\n throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0)\n throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes)\n length = (length << 8) | b;\n pos += lenLen;\n if (length < 128)\n throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length)\n throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\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) {\n const { Err: E } = DER;\n if (num < _0n)\n throw new E('integer: negative integers are not allowed');\n let hex = ut.numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000)\n hex = '00' + hex;\n if (hex.length & 1)\n throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data) {\n const { Err: E } = DER;\n if (data[0] & 128)\n throw new E('invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 128))\n throw new E('invalid signature integer: unnecessary leading zero');\n return b2n(data);\n },\n },\n toSig(hex) {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n ut.abytes(data);\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length)\n 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)\n throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig) {\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};\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\nexport function weierstrassPoints(opts) {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const Fn = mod.Field(CURVE.n, CURVE.nBitLength);\n const toBytes = CURVE.toBytes ||\n ((_c, point, _isCompressed) => {\n const a = point.toAffine();\n return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes = CURVE.fromBytes ||\n ((bytes) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula\n * @returns y²\n */\n function weierstrassEquation(x) {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num) {\n return ut.inRange(num, _1n, CURVE.n);\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key) {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (ut.isBytes(key))\n key = ut.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length))\n throw new Error('invalid private key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n }\n catch (error) {\n throw new Error('invalid private key, expected hex or ' + nByteLength + ' bytes, got ' + typeof key);\n }\n if (wrapPrivateKey)\n num = mod.mod(num, N); // disabled by default, enabled for BLS\n ut.aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n function assertPrjPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ProjectivePoint expected');\n }\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n const toAffineMemo = memoized((p, iz) => {\n const { px: x, py: y, pz: z } = p;\n // Fast-path for normalized points\n if (Fp.eql(z, Fp.ONE))\n return { x, 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)\n iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p) => {\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 // (0, 0, 0) is invalid representation of ZERO.\n if (CURVE.allowInfinityPoint && !Fp.is0(p.py))\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 // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n if (!Fp.eql(left, right))\n throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point {\n constructor(px, py, pz) {\n this.px = px;\n this.py = py;\n this.pz = pz;\n if (px == null || !Fp.isValid(px))\n throw new Error('x required');\n if (py == null || !Fp.isValid(py))\n throw new Error('y required');\n if (pz == null || !Fp.isValid(pz))\n throw new Error('z required');\n Object.freeze(this);\n }\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n const is0 = (i) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex) {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n // Multiscalar Multiplication\n static msm(points, scalars) {\n return pippenger(Point, Fn, points, scalars);\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n wnaf.setWindowSize(this, windowSize);\n }\n // A point on curve is valid if it conforms to equation.\n assertValidity() {\n assertValidMemo(this);\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (Fp.isOdd)\n return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n /**\n * Compare one point to another.\n */\n equals(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate() {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n // 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) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc) {\n const { endo, n: N } = CURVE;\n ut.aInRange('scalar', sc, _0n, N);\n const I = Point.ZERO;\n if (sc === _0n)\n return I;\n if (this.is0() || sc === _1n)\n return this;\n // Case a: no endomorphism. Case b: has precomputes.\n if (!endo || wnaf.hasPrecomputes(this))\n return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);\n // Case c: endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);\n let k1p = I;\n let k2p = I;\n let d = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n k1p = k1p.add(d);\n if (k2 & _1n)\n k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg)\n k1p = k1p.negate();\n if (k2neg)\n k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n /**\n * 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) {\n const { endo, n: N } = CURVE;\n ut.aInRange('scalar', scalar, _1n, N);\n let point, fake; // Fake point is used to const-time mult\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n }\n else {\n const { p, f } = this.wNAF(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q, a, b) {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (P, a // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n toAffine(iz) {\n return toAffineMemo(this, iz);\n }\n isTorsionFree() {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n)\n return true; // No subgroups, always torsion-free\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor() {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n return this.multiplyUnsafe(CURVE.h);\n }\n toRawBytes(isCompressed = true) {\n abool('isCompressed', isCompressed);\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n abool('isCompressed', isCompressed);\n return ut.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\nfunction validateOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n }, {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n });\n return Object.freeze({ lowS: true, ...opts });\n}\n/**\n * Creates short weierstrass curve and ECDSA signature methods for it.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, b, p, n, Gx, Gy\n * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })\n */\nexport function weierstrass(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n function modN(a) {\n return mod.mod(a, CURVE_ORDER);\n }\n function invN(a) {\n return mod.invert(a, CURVE_ORDER);\n }\n const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed) {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = ut.concatBytes;\n abool('isCompressed', isCompressed);\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n }\n else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = ut.bytesToNumberBE(tail);\n if (!ut.inRange(x, _1n, Fp.ORDER))\n throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n }\n catch (sqrtError) {\n const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('Point is not on curve' + suffix);\n }\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n }\n else {\n const cl = compressedLen;\n const ul = uncompressedLen;\n throw new Error('invalid Point, expected length of ' + cl + ', or uncompressed ' + ul + ', got ' + len);\n }\n },\n });\n const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function normalizeS(s) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to));\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature {\n constructor(r, s, recovery) {\n this.r = r;\n this.s = s;\n this.recovery = recovery;\n this.assertValidity();\n }\n // pair (bytes of r, bytes of s)\n static fromCompact(hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n assertValidity() {\n ut.aInRange('r', this.r, _1n, CURVE_ORDER); // r in [1..N]\n ut.aInRange('s', this.s, _1n, CURVE_ORDER); // s in [1..N]\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n recoverPublicKey(msgHash) {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec))\n throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER)\n throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q)\n throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n // DER-encoded\n toDERRawBytes() {\n return ut.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return ut.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n const utils = {\n isValidPrivateKey(privateKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n }\n catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: () => {\n const length = mod.getMinHashLength(CURVE.n);\n return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey, isCompressed = true) {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\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) {\n const arr = ut.isBytes(item);\n const str = typeof item === 'string';\n const len = (arr || str) && item.length;\n if (arr)\n return len === compressedLen || len === uncompressedLen;\n if (str)\n return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point)\n return true;\n return false;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA, publicB, isCompressed = true) {\n if (isProbPub(privateA))\n throw new Error('first arg must be private key');\n if (!isProbPub(publicB))\n throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n // 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 = CURVE.bits2int ||\n function (bytes) {\n // Our custom check \"just in case\"\n if (bytes.length > 8192)\n 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 = ut.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN = CURVE.bits2int_modN ||\n function (bytes) {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num) {\n ut.aInRange('num < 2^' + CURVE.nBitLength, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return ut.numberToBytesBE(num, CURVE.nByteLength);\n }\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order,\n // this will be invalid at least for P521. Also it can be bigger for P224 + SHA256\n function prepSig(msgHash, privateKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null)\n lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n validateSigVerOpts(opts);\n if (prehash)\n msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null && ent !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k))\n return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n)\n return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery); // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash, privKey, opts = defaultSigOpts) {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1⋅G - U2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n const { lowS, prehash, format } = opts;\n // Verify opts, deduce signature format\n validateSigVerOpts(opts);\n if ('strict' in opts)\n throw new Error('options.strict was renamed to lowS');\n if (format !== undefined && format !== 'compact' && format !== 'der')\n throw new Error('format must be compact or der');\n const isHex = typeof sg === 'string' || ut.isBytes(sg);\n const isObj = !isHex &&\n !format &&\n typeof sg === 'object' &&\n sg !== null &&\n typeof sg.r === 'bigint' &&\n typeof sg.s === 'bigint';\n if (!isHex && !isObj)\n throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');\n let _sig = undefined;\n let P;\n try {\n if (isObj)\n _sig = new Signature(sg.r, sg.s);\n if (isHex) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n if (format !== 'compact')\n _sig = Signature.fromDER(sg);\n }\n catch (derError) {\n if (!(derError instanceof DER.Err))\n throw derError;\n }\n if (!_sig && format !== 'der')\n _sig = Signature.fromCompact(sg);\n }\n P = Point.fromHex(publicKey);\n }\n catch (error) {\n return false;\n }\n if (!_sig)\n return false;\n if (lowS && _sig.hasHighS())\n return false;\n if (prehash)\n msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n if (!R)\n return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp, Z) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u, v) => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u, v) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(Fp, opts) {\n mod.validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd)\n throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u) => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n//# sourceMappingURL=weierstrass.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { weierstrass } from './abstract/weierstrass.js';\n// connects noble-curves to noble-hashes\nexport function getHash(hash) {\n return {\n hash,\n hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\nexport function createCurve(curveDef, defHash) {\n const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });\n return Object.freeze({ ...create(defHash), create });\n}\n//# sourceMappingURL=_shortw_utils.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher, isogenyMap } from './abstract/hash-to-curve.js';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport { inRange, aInRange, bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE, } from './abstract/utils.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a, b) => (a + b / _2n) / b;\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fpk1.eql(Fpk1.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fpk1 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n/**\n * secp256k1 short weierstrass curve and ECDSA signatures over it.\n */\nexport const secp256k1 = createCurve({\n a: BigInt(0), // equation params: a, b\n b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975\n Fp: Fpk1, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n\n n: secp256k1N, // Curve order, total count of valid points in the field\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1), // Cofactor\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n /**\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066\n */\n endo: {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg)\n k1 = n - k1;\n if (k2neg)\n k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n}, sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = {};\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n) => numberToBytesBE(n, 32);\nconst modP = (x) => mod(x, secp256k1P);\nconst modN = (x) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n aInRange('x', x, _1n, secp256k1P); // Fail if x ≥ p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n)\n y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args) {\n return modN(num(taggedHash('BIP0340/challenge', ...args)));\n}\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey) {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(message, privateKey, auxRand = randomBytes(32)) {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(num(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n)\n throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(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 ≥ p.\n if (!inRange(r, _1n, secp256k1P))\n return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!inRange(s, _1n, secp256k1N))\n return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r)\n return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n }\n catch (error) {\n return false;\n }\n}\n/**\n * Schnorr signatures over secp256k1.\n */\nexport const schnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\nconst isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [\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)))))();\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp256k1.ProjectivePoint, (scalars) => {\n const { x, y } = mapSWU(Fpk1.create(scalars[0]));\n return isoMap(x, y);\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}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=secp256k1.js.map","import { secp256k1 } from '@noble/curves/secp256k1';\nimport * as Bytes from './Bytes.js';\nimport * as Errors from './Errors.js';\nimport * as Hex from './Hex.js';\nimport * as Json from './Json.js';\nimport * as Solidity from './Solidity.js';\n/**\n * Asserts that a Signature is valid.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.assert({\n * r: -49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * })\n * // @error: InvalidSignatureRError:\n * // @error: Value `-549...n` is an invalid r value.\n * // @error: r must be a positive integer less than 2^256.\n * ```\n *\n * @param signature - The signature object to assert.\n */\nexport function assert(signature, options = {}) {\n const { recovered } = options;\n if (typeof signature.r === 'undefined')\n throw new MissingPropertiesError({ signature });\n if (typeof signature.s === 'undefined')\n throw new MissingPropertiesError({ signature });\n if (recovered && typeof signature.yParity === 'undefined')\n throw new MissingPropertiesError({ signature });\n if (signature.r < 0n || signature.r > Solidity.maxUint256)\n throw new InvalidRError({ value: signature.r });\n if (signature.s < 0n || signature.s > Solidity.maxUint256)\n throw new InvalidSError({ value: signature.s });\n if (typeof signature.yParity === 'number' &&\n signature.yParity !== 0 &&\n signature.yParity !== 1)\n throw new InvalidYParityError({ value: signature.yParity });\n}\n/**\n * Deserializes a {@link ox#Bytes.Bytes} signature into a structured {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Signature } from 'ox'\n *\n * Signature.fromBytes(new Uint8Array([128, 3, 131, ...]))\n * // @log: { r: 5231...n, s: 3522...n, yParity: 0 }\n * ```\n *\n * @param signature - The serialized signature.\n * @returns The deserialized {@link ox#Signature.Signature}.\n */\nexport function fromBytes(signature) {\n return fromHex(Hex.fromBytes(signature));\n}\n/**\n * Deserializes a {@link ox#Hex.Hex} signature into a structured {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.fromHex('0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db81c')\n * // @log: { r: 5231...n, s: 3522...n, yParity: 0 }\n * ```\n *\n * @param serialized - The serialized signature.\n * @returns The deserialized {@link ox#Signature.Signature}.\n */\nexport function fromHex(signature) {\n if (signature.length !== 130 && signature.length !== 132)\n throw new InvalidSerializedSizeError({ signature });\n const r = BigInt(Hex.slice(signature, 0, 32));\n const s = BigInt(Hex.slice(signature, 32, 64));\n const yParity = (() => {\n const yParity = Number(`0x${signature.slice(130)}`);\n if (Number.isNaN(yParity))\n return undefined;\n try {\n return vToYParity(yParity);\n }\n catch {\n throw new InvalidYParityError({ value: yParity });\n }\n })();\n if (typeof yParity === 'undefined')\n return {\n r,\n s,\n };\n return {\n r,\n s,\n yParity,\n };\n}\n/**\n * Extracts a {@link ox#Signature.Signature} from an arbitrary object that may include signature properties.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Signature } from 'ox'\n *\n * Signature.extract({\n * baz: 'barry',\n * foo: 'bar',\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * zebra: 'stripes',\n * })\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: yParity: 1\n * // @log: }\n * ```\n *\n * @param value - The arbitrary object to extract the signature from.\n * @returns The extracted {@link ox#Signature.Signature}.\n */\nexport function extract(value) {\n if (typeof value.r === 'undefined')\n return undefined;\n if (typeof value.s === 'undefined')\n return undefined;\n return from(value);\n}\n/**\n * Instantiates a typed {@link ox#Signature.Signature} object from a {@link ox#Signature.Signature}, {@link ox#Signature.Legacy}, {@link ox#Bytes.Bytes}, or {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.from({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * })\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: yParity: 1\n * // @log: }\n * ```\n *\n * @example\n * ### From Serialized\n *\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.from('0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db801')\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: yParity: 1,\n * // @log: }\n * ```\n *\n * @example\n * ### From Legacy\n *\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.from({\n * r: 47323457007453657207889730243826965761922296599680473886588287015755652701072n,\n * s: 57228803202727131502949358313456071280488184270258293674242124340113824882788n,\n * v: 27,\n * })\n * // @log: {\n * // @log: r: 47323457007453657207889730243826965761922296599680473886588287015755652701072n,\n * // @log: s: 57228803202727131502949358313456071280488184270258293674242124340113824882788n,\n * // @log: yParity: 0\n * // @log: }\n * ```\n *\n * @param signature - The signature value to instantiate.\n * @returns The instantiated {@link ox#Signature.Signature}.\n */\nexport function from(signature) {\n const signature_ = (() => {\n if (typeof signature === 'string')\n return fromHex(signature);\n if (signature instanceof Uint8Array)\n return fromBytes(signature);\n if (typeof signature.r === 'string')\n return fromRpc(signature);\n if (signature.v)\n return fromLegacy(signature);\n return {\n r: signature.r,\n s: signature.s,\n ...(typeof signature.yParity !== 'undefined'\n ? { yParity: signature.yParity }\n : {}),\n };\n })();\n assert(signature_);\n return signature_;\n}\n/**\n * Converts a DER-encoded signature to a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromDerBytes(new Uint8Array([132, 51, 23, ...]))\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: }\n * ```\n *\n * @param signature - The DER-encoded signature to convert.\n * @returns The {@link ox#Signature.Signature}.\n */\nexport function fromDerBytes(signature) {\n return fromDerHex(Hex.fromBytes(signature));\n}\n/**\n * Converts a DER-encoded signature to a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromDerHex('0x304402206e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf02204a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db8')\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: }\n * ```\n *\n * @param signature - The DER-encoded signature to convert.\n * @returns The {@link ox#Signature.Signature}.\n */\nexport function fromDerHex(signature) {\n const { r, s } = secp256k1.Signature.fromDER(Hex.from(signature).slice(2));\n return { r, s };\n}\n/**\n * Converts a {@link ox#Signature.Legacy} into a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const legacy = Signature.fromLegacy({ r: 1n, s: 2n, v: 28 })\n * // @log: { r: 1n, s: 2n, yParity: 1 }\n * ```\n *\n * @param signature - The {@link ox#Signature.Legacy} to convert.\n * @returns The converted {@link ox#Signature.Signature}.\n */\nexport function fromLegacy(signature) {\n return {\n r: signature.r,\n s: signature.s,\n yParity: vToYParity(signature.v),\n };\n}\n/**\n * Converts a {@link ox#Signature.Rpc} into a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromRpc({\n * r: '0x635dc2033e60185bb36709c29c75d64ea51dfbd91c32ef4be198e4ceb169fb4d',\n * s: '0x50c2667ac4c771072746acfdcf1f1483336dcca8bd2df47cd83175dbe60f0540',\n * yParity: '0x0',\n * })\n * ```\n *\n * @param signature - The {@link ox#Signature.Rpc} to convert.\n * @returns The converted {@link ox#Signature.Signature}.\n */\nexport function fromRpc(signature) {\n const yParity = (() => {\n const v = signature.v ? Number(signature.v) : undefined;\n let yParity = signature.yParity ? Number(signature.yParity) : undefined;\n if (typeof v === 'number' && typeof yParity !== 'number')\n yParity = vToYParity(v);\n if (typeof yParity !== 'number')\n throw new InvalidYParityError({ value: signature.yParity });\n return yParity;\n })();\n return {\n r: BigInt(signature.r),\n s: BigInt(signature.s),\n yParity,\n };\n}\n/**\n * Converts a {@link ox#Signature.Tuple} to a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromTuple(['0x01', '0x7b', '0x1c8'])\n * // @log: {\n * // @log: r: 123n,\n * // @log: s: 456n,\n * // @log: yParity: 1,\n * // @log: }\n * ```\n *\n * @param tuple - The {@link ox#Signature.Tuple} to convert.\n * @returns The {@link ox#Signature.Signature}.\n */\nexport function fromTuple(tuple) {\n const [yParity, r, s] = tuple;\n return from({\n r: r === '0x' ? 0n : BigInt(r),\n s: s === '0x' ? 0n : BigInt(s),\n yParity: yParity === '0x' ? 0 : Number(yParity),\n });\n}\n/**\n * Serializes a {@link ox#Signature.Signature} to {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.toBytes({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1\n * })\n * // @log: Uint8Array [102, 16, 10, ...]\n * ```\n *\n * @param signature - The signature to serialize.\n * @returns The serialized signature.\n */\nexport function toBytes(signature) {\n return Bytes.fromHex(toHex(signature));\n}\n/**\n * Serializes a {@link ox#Signature.Signature} to {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.toHex({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1\n * })\n * // @log: '0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db81c'\n * ```\n *\n * @param signature - The signature to serialize.\n * @returns The serialized signature.\n */\nexport function toHex(signature) {\n assert(signature);\n const r = signature.r;\n const s = signature.s;\n const signature_ = Hex.concat(Hex.fromNumber(r, { size: 32 }), Hex.fromNumber(s, { size: 32 }), \n // If the signature is recovered, add the recovery byte to the signature.\n typeof signature.yParity === 'number'\n ? Hex.fromNumber(signature.yParity, { size: 1 })\n : '0x');\n return signature_;\n}\n/**\n * Converts a {@link ox#Signature.Signature} to DER-encoded format.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.from({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * })\n *\n * const signature_der = Signature.toDerBytes(signature)\n * // @log: Uint8Array [132, 51, 23, ...]\n * ```\n *\n * @param signature - The signature to convert.\n * @returns The DER-encoded signature.\n */\nexport function toDerBytes(signature) {\n const sig = new secp256k1.Signature(signature.r, signature.s);\n return sig.toDERRawBytes();\n}\n/**\n * Converts a {@link ox#Signature.Signature} to DER-encoded format.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.from({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * })\n *\n * const signature_der = Signature.toDerHex(signature)\n * // @log: '0x304402206e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf02204a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db8'\n * ```\n *\n * @param signature - The signature to convert.\n * @returns The DER-encoded signature.\n */\nexport function toDerHex(signature) {\n const sig = new secp256k1.Signature(signature.r, signature.s);\n return `0x${sig.toDERHex()}`;\n}\n/**\n * Converts a {@link ox#Signature.Signature} into a {@link ox#Signature.Legacy}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const legacy = Signature.toLegacy({ r: 1n, s: 2n, yParity: 1 })\n * // @log: { r: 1n, s: 2n, v: 28 }\n * ```\n *\n * @param signature - The {@link ox#Signature.Signature} to convert.\n * @returns The converted {@link ox#Signature.Legacy}.\n */\nexport function toLegacy(signature) {\n return {\n r: signature.r,\n s: signature.s,\n v: yParityToV(signature.yParity),\n };\n}\n/**\n * Converts a {@link ox#Signature.Signature} into a {@link ox#Signature.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.toRpc({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1\n * })\n * ```\n *\n * @param signature - The {@link ox#Signature.Signature} to convert.\n * @returns The converted {@link ox#Signature.Rpc}.\n */\nexport function toRpc(signature) {\n const { r, s, yParity } = signature;\n return {\n r: Hex.fromNumber(r, { size: 32 }),\n s: Hex.fromNumber(s, { size: 32 }),\n yParity: yParity === 0 ? '0x0' : '0x1',\n };\n}\n/**\n * Converts a {@link ox#Signature.Signature} to a serialized {@link ox#Signature.Tuple} to be used for signatures in Transaction Envelopes, EIP-7702 Authorization Lists, etc.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signatureTuple = Signature.toTuple({\n * r: 123n,\n * s: 456n,\n * yParity: 1,\n * })\n * // @log: [yParity: '0x01', r: '0x7b', s: '0x1c8']\n * ```\n *\n * @param signature - The {@link ox#Signature.Signature} to convert.\n * @returns The {@link ox#Signature.Tuple}.\n */\nexport function toTuple(signature) {\n const { r, s, yParity } = signature;\n return [\n yParity ? '0x01' : '0x',\n r === 0n ? '0x' : Hex.trimLeft(Hex.fromNumber(r)),\n s === 0n ? '0x' : Hex.trimLeft(Hex.fromNumber(s)),\n ];\n}\n/**\n * Validates a Signature. Returns `true` if the signature is valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const valid = Signature.validate({\n * r: -49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * })\n * // @log: false\n * ```\n *\n * @param signature - The signature object to assert.\n */\nexport function validate(signature, options = {}) {\n try {\n assert(signature, options);\n return true;\n }\n catch {\n return false;\n }\n}\n/**\n * Converts a ECDSA `v` value to a `yParity` value.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const yParity = Signature.vToYParity(28)\n * // @log: 1\n * ```\n *\n * @param v - The ECDSA `v` value to convert.\n * @returns The `yParity` value.\n */\nexport function vToYParity(v) {\n if (v === 0 || v === 27)\n return 0;\n if (v === 1 || v === 28)\n return 1;\n if (v >= 35)\n return v % 2 === 0 ? 1 : 0;\n throw new InvalidVError({ value: v });\n}\n/**\n * Converts a ECDSA `v` value to a `yParity` value.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const v = Signature.yParityToV(1)\n * // @log: 28\n * ```\n *\n * @param yParity - The ECDSA `yParity` value to convert.\n * @returns The `v` value.\n */\nexport function yParityToV(yParity) {\n if (yParity === 0)\n return 27;\n if (yParity === 1)\n return 28;\n throw new InvalidYParityError({ value: yParity });\n}\n/** Thrown when the serialized signature is of an invalid size. */\nexport class InvalidSerializedSizeError extends Errors.BaseError {\n constructor({ signature }) {\n super(`Value \\`${signature}\\` is an invalid signature size.`, {\n metaMessages: [\n 'Expected: 64 bytes or 65 bytes.',\n `Received ${Hex.size(Hex.from(signature))} bytes.`,\n ],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Signature.InvalidSerializedSizeError'\n });\n }\n}\n/** Thrown when the signature is missing either an `r`, `s`, or `yParity` property. */\nexport class MissingPropertiesError extends Errors.BaseError {\n constructor({ signature }) {\n super(`Signature \\`${Json.stringify(signature)}\\` is missing either an \\`r\\`, \\`s\\`, or \\`yParity\\` property.`);\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Signature.MissingPropertiesError'\n });\n }\n}\n/** Thrown when the signature has an invalid `r` value. */\nexport class InvalidRError extends Errors.BaseError {\n constructor({ value }) {\n super(`Value \\`${value}\\` is an invalid r value. r must be a positive integer less than 2^256.`);\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Signature.InvalidRError'\n });\n }\n}\n/** Thrown when the signature has an invalid `s` value. */\nexport class InvalidSError extends Errors.BaseError {\n constructor({ value }) {\n super(`Value \\`${value}\\` is an invalid s value. s must be a positive integer less than 2^256.`);\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Signature.InvalidSError'\n });\n }\n}\n/** Thrown when the signature has an invalid `yParity` value. */\nexport class InvalidYParityError extends Errors.BaseError {\n constructor({ value }) {\n super(`Value \\`${value}\\` is an invalid y-parity value. Y-parity must be 0 or 1.`);\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Signature.InvalidYParityError'\n });\n }\n}\n/** Thrown when the signature has an invalid `v` value. */\nexport class InvalidVError extends Errors.BaseError {\n constructor({ value }) {\n super(`Value \\`${value}\\` is an invalid v value. v must be 27, 28 or >=35.`);\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Signature.InvalidVError'\n });\n }\n}\n//# sourceMappingURL=Signature.js.map","import {\n type OwnershipProof,\n SignatureProof,\n DeclarationProof,\n ScreenshotProof,\n ProofTypes,\n ProofStatus,\n} from \"@notabene/javascript-sdk\";\nimport { verifyBTCSignature } from \"./bitcoin\";\nimport { verifyPersonalSignEIP191 } from \"./eth\";\nimport { verifySolanaSignature } from \"./solana\";\n\nexport async function verifyProof(\n proof: OwnershipProof,\n): Promise<OwnershipProof> {\n switch (proof.type) {\n case ProofTypes.SelfDeclaration:\n return {\n ...proof,\n status: (proof as DeclarationProof).confirmed\n ? ProofStatus.VERIFIED\n : ProofStatus.FAILED,\n };\n case ProofTypes.Screenshot:\n return {\n ...proof,\n status: (proof as ScreenshotProof).url\n ? ProofStatus.FLAGGED\n : ProofStatus.FAILED,\n };\n case ProofTypes.EIP191:\n return verifyPersonalSignEIP191(proof as SignatureProof);\n case ProofTypes.ED25519:\n return verifySolanaSignature(proof as SignatureProof);\n case ProofTypes.EIP712:\n case ProofTypes.BIP137:\n return verifyBTCSignature(proof as SignatureProof);\n case ProofTypes.BIP137_XPUB:\n case ProofTypes.MicroTransfer:\n }\n return proof;\n}\n","import { ProofStatus, SignatureProof } from \"@notabene/javascript-sdk\";\n\nimport { Secp256k1, Hex, PersonalMessage, Signature, Address } from \"ox\";\n\nexport function verifyEIP191(\n address: Hex.Hex,\n message: string,\n proof: Hex.Hex,\n): boolean {\n try {\n const payload = PersonalMessage.getSignPayload(Hex.fromString(message));\n const signature = Signature.fromHex(proof);\n const publicKey = Secp256k1.recoverPublicKey({ payload, signature });\n const recovered = Address.fromPublicKey(publicKey);\n return recovered.toString() === address.toString();\n } catch (error) {\n return false;\n }\n}\n\nexport async function verifyPersonalSignEIP191(\n proof: SignatureProof,\n): Promise<SignatureProof> {\n const [ns, _, address] = proof.address.split(/:/);\n if (ns !== \"eip155\") return { ...proof, status: ProofStatus.FAILED };\n\n const verified = verifyEIP191(\n address as Hex.Hex,\n proof.attestation,\n proof.proof as Hex.Hex,\n );\n return {\n ...proof,\n status: verified ? ProofStatus.VERIFIED : ProofStatus.FAILED,\n };\n}\n","import { secp256k1 } from '@noble/curves/secp256k1';\nimport * as Address from './Address.js';\nimport * as Bytes from './Bytes.js';\nimport * as Hex from './Hex.js';\nimport * as PublicKey from './PublicKey.js';\n/** Re-export of noble/curves secp256k1 utilities. */\nexport const noble = secp256k1;\n/**\n * Computes the secp256k1 ECDSA public key from a provided private key.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const publicKey = Secp256k1.getPublicKey({ privateKey: '0x...' })\n * ```\n *\n * @param options - The options to compute the public key.\n * @returns The computed public key.\n */\nexport function getPublicKey(options) {\n const { privateKey } = options;\n const point = secp256k1.ProjectivePoint.fromPrivateKey(Hex.from(privateKey).slice(2));\n return PublicKey.from(point);\n}\n/**\n * Generates a random ECDSA private key on the secp256k1 curve.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const privateKey = Secp256k1.randomPrivateKey()\n * ```\n *\n * @param options - The options to generate the private key.\n * @returns The generated private key.\n */\nexport function randomPrivateKey(options = {}) {\n const { as = 'Hex' } = options;\n const bytes = secp256k1.utils.randomPrivateKey();\n if (as === 'Hex')\n return Hex.fromBytes(bytes);\n return bytes;\n}\n/**\n * Recovers the signing address from the signed payload and signature.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey: '0x...' })\n *\n * const address = Secp256k1.recoverAddress({ // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The recovery options.\n * @returns The recovered address.\n */\nexport function recoverAddress(options) {\n return Address.fromPublicKey(recoverPublicKey(options));\n}\n/**\n * Recovers the signing public key from the signed payload and signature.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey: '0x...' })\n *\n * const publicKey = Secp256k1.recoverPublicKey({ // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The recovery options.\n * @returns The recovered public key.\n */\nexport function recoverPublicKey(options) {\n const { payload, signature } = options;\n const { r, s, yParity } = signature;\n const signature_ = new secp256k1.Signature(BigInt(r), BigInt(s)).addRecoveryBit(yParity);\n const point = signature_.recoverPublicKey(Hex.from(payload).substring(2));\n return PublicKey.from(point);\n}\n/**\n * Signs the payload with the provided private key.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * privateKey: '0x...' // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The signing options.\n * @returns The ECDSA {@link ox#Signature.Signature}.\n */\nexport function sign(options) {\n const { hash, payload, privateKey } = options;\n const { r, s, recovery } = secp256k1.sign(Bytes.from(payload), Bytes.from(privateKey), ...(hash ? [{ prehash: true, lowS: true }] : []));\n return {\n r,\n s,\n yParity: recovery,\n };\n}\n/**\n * Verifies a payload was signed by the provided address.\n *\n * @example\n * ### Verify with Ethereum Address\n *\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey: '0x...' })\n *\n * const verified = Secp256k1.verify({ // [!code focus]\n * address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @example\n * ### Verify with Public Key\n *\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const privateKey = '0x...'\n * const publicKey = Secp256k1.getPublicKey({ privateKey })\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey })\n *\n * const verified = Secp256k1.verify({ // [!code focus]\n * publicKey, // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The verification options.\n * @returns Whether the payload was signed by the provided address.\n */\nexport function verify(options) {\n const { address, hash, payload, publicKey, signature } = options;\n if (address)\n return Address.isEqual(address, recoverAddress({ payload, signature }));\n return secp256k1.verify(signature, Bytes.from(payload), PublicKey.toBytes(publicKey), ...(hash ? [{ prehash: true, lowS: true }] : []));\n}\n//# sourceMappingURL=Secp256k1.js.map","import * as Hash from './Hash.js';\nimport * as Hex from './Hex.js';\n/**\n * Encodes a personal sign message in [ERC-191 format](https://eips.ethereum.org/EIPS/eip-191#version-0x45-e): `0x19 ‖ \"Ethereum Signed Message:\\n\" + message.length ‖ message`.\n *\n * @example\n * ```ts twoslash\n * import { Hex, PersonalMessage } from 'ox'\n *\n * const data = PersonalMessage.encode(Hex.fromString('hello world'))\n * // @log: '0x19457468657265756d205369676e6564204d6573736167653a0a313168656c6c6f20776f726c64'\n * // @log: (0x19 ‖ 'Ethereum Signed Message:\\n11' ‖ 'hello world')\n * ```\n *\n * @param data - The data to encode.\n * @returns The encoded personal sign message.\n */\nexport function encode(data) {\n const message = Hex.from(data);\n return Hex.concat(\n // Personal Sign Format: `0x19 ‖ \"Ethereum Signed Message:\\n\" ‖ message.length ‖ message`\n '0x19', Hex.fromString('Ethereum Signed Message:\\n' + Hex.size(message)), message);\n}\n/**\n * Gets the payload to use for signing an [ERC-191 formatted](https://eips.ethereum.org/EIPS/eip-191#version-0x45-e) personal message.\n *\n * @example\n * ```ts twoslash\n * import { Hex, PersonalMessage, Secp256k1 } from 'ox'\n *\n * const payload = PersonalMessage.getSignPayload(Hex.fromString('hello world')) // [!code focus]\n *\n * const signature = Secp256k1.sign({ payload, privateKey: '0x...' })\n * ```\n *\n * @param data - The data to get the sign payload for.\n * @returns The payload to use for signing.\n */\nexport function getSignPayload(data) {\n return Hash.keccak256(encode(data));\n}\n//# sourceMappingURL=PersonalMessage.js.map","import nacl from \"tweetnacl\";\nimport { ProofStatus, SignatureProof } from \"@notabene/javascript-sdk\";\nimport { decode as decodeBase64 } from \"@stablelib/base64\";\nimport bs58 from \"bs58\";\n\nexport async function verifySolanaSignature(\n proof: SignatureProof,\n): Promise<SignatureProof> {\n const [ns, _, address] = proof.address.split(/:/);\n if (ns !== \"solana\") return { ...proof, status: ProofStatus.FAILED };\n try {\n const publicKey = bs58.decode(address);\n const messageBytes = new TextEncoder().encode(proof.attestation);\n const signatureBytes = decodeBase64(proof.proof);\n const verified = nacl.sign.detached.verify(\n messageBytes,\n signatureBytes,\n publicKey,\n );\n\n return {\n ...proof,\n status: verified ? ProofStatus.VERIFIED : ProofStatus.FAILED,\n };\n } catch (error) {\n return { ...proof, status: ProofStatus.FAILED };\n }\n}\n"],"names":["SEGWIT_TYPES","DerivationMode","encodeBech32Address","publicKeyHash","bwords","bech32","toWords","unshift","encode","BaseError","Error","constructor","shortMessage","options","details","cause","message","docsPath","docs","super","metaMessages","undefined","filter","x","join","Object","defineProperty","this","enumerable","configurable","writable","value","walk","fn","err","anumber","n","Number","isSafeInteger","abytes","b","lengths","a","Uint8Array","ArrayBuffer","isView","name","length","includes","aexists","instance","checkFinished","destroyed","finished","isLE","Uint32Array","buffer","byteSwap32","arr","i","word","toBytes","data","str","TextEncoder","utf8ToBytes","Hash","clone","_cloneInto","U32_MASK64","BigInt","_32n","fromBig","le","h","l","split","lst","Ah","Al","SHA3_PI","SHA3_ROTL","_SHA3_IOTA","_0n","_1n","_2n","_7n","_256n","_0x71n","round","R","y","push","t","j","SHA3_IOTA_H","SHA3_IOTA_L","rotlH","s","rotlBH","rotlSH","rotlL","rotlBL","rotlSL","Keccak","blockLen","suffix","outputLen","enableXOF","rounds","pos","posOut","state","state32","byteOffset","Math","floor","byteLength","keccak","B","idx1","idx0","B0","B1","Th","Tl","curH","curL","shift","PI","fill","keccakP","update","len","take","min","finish","writeInto","out","bufferOut","set","subarray","xofInto","xof","bytes","digestInto","aoutput","destroy","digest","to","keccak_256","hashCons","hashC","msg","tmp","create","wrapConstructor","gen","isBytes","item","abool","title","hexes","Array","from","_","toString","padStart","bytesToHex","hex","numberToHexUnpadded","num","hexToNumber","asciiToBase16","ch","hexToBytes","hl","al","array","ai","hi","n1","charCodeAt","n2","bytesToNumberBE","bytesToNumberLE","reverse","numberToBytesBE","numberToBytesLE","ensureBytes","expectedLength","res","e","concatBytes","arrays","sum","pad","isPosBig","inRange","max","aInRange","bitLen","bitMask","u8n","u8fr","createHmacDrbg","hashLen","qByteLen","hmacFn","v","k","reset","reseed","seed","sl","slice","pred","validatorFns","bigint","val","function","boolean","string","stringOrUint8Array","isArray","field","object","Fp","isValid","hash","validateObject","validators","optValidators","checkField","fieldName","type","isOptional","checkVal","String","entries","memoized","map","WeakMap","arg","args","get","computed","diff","stringify","replacer","space","JSON","key","assertSize","size_","Bytes.size","Bytes.SizeOverflowError","givenSize","maxSize","charCodeToBase16","char","Hex.size","Hex.SizeOverflowError","hex_","dir","size","replace","Hex.SizeExceedsPaddingSizeError","ceil","targetSize","encoder","_v","concat","values","reduce","acc","fromBytes","internal.assertSize","padRight","fromNumber","signed","value_","maxValue","MAX_SAFE_INTEGER","minValue","IntegerOutOfRangeError","internal.pad","padLeft","fromString","start","end","strict","Hex.SliceOffsetOutOfBoundsError","offset","position","internal.assertStartOffset","internal.assertEndOffset","Errors.BaseError","InvalidHexTypeError","Json.stringify","InvalidHexValueError","SizeOverflowError","SliceOffsetOutOfBoundsError","SizeExceedsPaddingSizeError","charAt","toUpperCase","toLowerCase","InvalidBytesTypeError","keccak256","as","noble_keccak256","internal_hex.assertSize","Hex.padRight","hexString","index","nibbleLeft","internal.charCodeToBase16","nibbleRight","fromHex","fromArray","Bytes.from","Hex.fromBytes","LruMap","Map","has","delete","firstKey","keys","next","checksum","assert","publicKey","compressed","prefix","InvalidPrefixError","InvalidUncompressedPrefixError","InvalidError","InvalidCompressedPrefixError","InvalidSerializedSizeError","Hex.slice","Hex.from","addressRegex","test","InvalidAddressError","address","InvalidInputError","InvalidChecksumError","Caches.checksum","hexAddress","substring","Hash.keccak256","Bytes.SizeExceedsPaddingSizeError","paddedBytes","padEnd","Bytes.fromString","characters","result","crypto","globalThis","createView","DataView","rotr","randomBytes","bytesLength","getRandomValues","Maj","c","HashMD","padOffset","view","process","dataView","roundClean","setBigUint64","_u32_max","wh","wl","setUint32","oview","outLen","SHA256_K","SHA256_IV","SHA256_W","SHA256","A","C","D","E","F","G","H","getUint32","W15","W2","s0","s1","T1","T2","sha256","HMAC","_key","ahash","iHash","oHash","buf","getPrototypeOf","hmac","_3n","_4n","_5n","_8n","mod","pow","power","modulo","pow2","invert","number","u","r","m","FIELD_FIELDS","nLength","nBitLength","_nBitLength","nByteLength","Field","ORDER","redef","BITS","BYTES","sqrtP","f","freeze","MASK","ZERO","ONE","is0","isOdd","neg","eql","lhs","rhs","sqr","add","sub","mul","p","d","FpPow","div","sqrN","addN","subN","mulN","inv","sqrt","P","p1div4","root","c1","nv","legendreC","Q","S","Z","Q1div2","g","t2","ge","tonelliShanks","FpSqrt","invertBatch","nums","lastMultiplied","inverted","reduceRight","FpInvertBatch","cmov","getFieldBytesLength","fieldOrder","bitLength","getMinHashLength","constTimeNegate","condition","negate","validateW","W","bits","calcWOpts","windows","windowSize","pointPrecomputes","pointWindowSizes","getW","validateBasic","curve","Gx","Gy","validateSigVerOpts","opts","lowS","prehash","b2n","h2b","ut","DER","Err","_tlv","tag","dataLen","ut.numberToHexUnpadded","lenLen","decode","first","lengthBytes","_int","parseInt","toSig","int","tlv","ut.abytes","seqBytes","seqLeftBytes","rBytes","rLeftBytes","sBytes","sLeftBytes","hexFromSig","sig","rs","ss","getHash","msgs","secp256k1P","secp256k1N","divNearest","Fpk1","_6n","_11n","_22n","_23n","_44n","_88n","b2","b3","b6","b9","b11","b22","b44","b88","b176","b220","b223","t1","secp256k1","curveDef","CURVE","ut.validateObject","bits2int","bits2int_modN","validateOpts","CURVE_ORDER","compressedLen","uncompressedLen","modN","mod.mod","invN","mod.invert","ProjectivePoint","Point","normPrivateKeyToScalar","weierstrassEquation","isWithinCurveOrder","allowedPrivateKeyLengths","wrapPrivateKey","isTorsionFree","clearCofactor","allowInfinityPoint","endo","beta","splitScalar","validatePointOpts","Fn","mod.Field","_c","point","_isCompressed","toAffine","ut.concatBytes","tail","x2","x3","N","ut.isBytes","ut.bytesToHex","ut.bytesToNumberBE","error","ut.aInRange","assertPrjPoint","other","toAffineMemo","iz","px","py","pz","z","ax","ay","zz","assertValidMemo","left","right","fromAffine","normalizeZ","points","toInv","assertValidity","fromPrivateKey","privateKey","BASE","multiply","msm","scalars","fieldN","forEach","validateMSMPoints","validateMSMScalars","zero","wbits","buckets","resI","sumI","double","pippenger","_setWindowSize","wnaf","setWindowSize","hasEvenY","equals","X1","Y1","Z1","X2","Y2","Z2","U1","U2","X3","Y3","Z3","t0","t3","t4","t5","subtract","wNAF","wNAFCached","multiplyUnsafe","sc","I","hasPrecomputes","wNAFCachedUnsafe","k1neg","k1","k2neg","k2","k1p","k2p","scalar","fake","f1p","f2p","multiplyAndAddUnsafe","cofactor","toRawBytes","isCompressed","toHex","_bits","elm","unsafeLadder","precomputeWindow","base","window","precomputes","mask","maxNumber","shiftBy","offset1","offset2","abs","cond2","wNAFUnsafe","curr","getPrecomputes","transform","comp","prev","ut.inRange","weierstrassPoints","cat","head","y2","sqrtError","numToNByteStr","ut.numberToBytesBE","isBiggerThanHalfOrder","slcNum","Signature","recovery","fromCompact","fromDER","addRecoveryBit","recoverPublicKey","msgHash","rec","radj","ir","u1","u2","hasHighS","normalizeS","toDERRawBytes","ut.hexToBytes","toDERHex","toCompactRawBytes","toCompactHex","utils","isValidPrivateKey","randomPrivateKey","mod.getMinHashLength","fieldLen","minLen","reduced","mod.mapHashToField","precompute","isProbPub","delta","ORDER_MASK","ut.bitMask","int2octets","defaultSigOpts","defaultVerOpts","getPublicKey","getSharedSecret","privateA","publicB","sign","privKey","k2sig","some","extraEntropy","ent","h1int","seedArgs","kBytes","ik","q","normS","prepSig","ut.createHmacDrbg","drbg","verify","signature","sg","format","isHex","isObj","_sig","derError","is","weierstrass","createCurve","a1","b1","a2","POW_2_128","c2","yParity","isNaN","InvalidVError","vToYParity","InvalidYParityError","proof","ProofTypes","SelfDeclaration","Promise","resolve","_extends","status","confirmed","ProofStatus","VERIFIED","FAILED","Screenshot","url","FLAGGED","EIP191","_proof$address$split","verified","payload","startsWith","Hex.validate","BYTES_PER_ELEMENT","Bytes.validate","PublicKey.from","Secp256k1","Hex","Hex.concat","Hex.fromString","includePrefix","Hex.fromNumber","PublicKey.toHex","checksumVal","Address","verifyEIP191","attestation","reject","verifyPersonalSignEIP191","ED25519","bs58","messageBytes","signatureBytes","decodeBase64","nacl","detached","verifySolanaSignature","EIP712","BIP137","segwit","SEGWIT","NATIVE","match","LEGACY","DOGECOIN","getDerivationMode","checkSegwitAlways","_decodeSignature","flagByte","segwitType","P2WPKH","P2SH_P2WPKH","decodeSignature","encodeLength","hash256","magicHash","recoverPublicKeyCompressed","recoverPublicKeyUncompressed","hash160","actual","encodeBase58AddressFormat","verifyBTCSignature"],"mappings":"6QAaKA,EAOAC,kQA2IL,SAASC,EAAoBC,GAC3B,IAAMC,EAASC,EAAAA,OAAOC,QAAQH,GAE9B,OADAC,EAAOG,QAAQ,GACRF,EAAMA,OAACG,OAAO,KAAMJ,EAC7B,EAtJA,SAAKJ,GACHA,EAAA,OAAA,SACAA,EAAA,YAAA,cACD,CAHD,CAAKA,IAAAA,EAGJ,CAAA,IAID,SAAKC,GACHA,EAAA,OAAA,SACAA,EAAA,OAAA,gBACAA,EAAA,OAAA,SACAA,EAAA,YAAA,OACAA,EAAA,IAAA,eACAA,EAAA,SAAA,WACAA,EAAA,SAAA,WACAA,EAAA,QAAA,SACD,CATD,CAAKA,IAAAA,EASJ,CAAA,ICnBM,MAAMQ,UAAkBC,MAC3B,WAAAC,CAAYC,EAAcC,EAAU,IAChC,MAAMC,EAAU,MACZ,GAAID,EAAQE,iBAAiBN,EAAW,CACpC,GAAII,EAAQE,MAAMD,QACd,OAAOD,EAAQE,MAAMD,QACzB,GAAID,EAAQE,MAAMH,aACd,OAAOC,EAAQE,MAAMH,YAC5B,CACD,OAAIC,EAAQE,OAAOC,QACRH,EAAQE,MAAMC,QAClBH,EAAQC,OAClB,EAVe,GAWVG,EACEJ,EAAQE,iBAAiBN,GAClBI,EAAQE,MAAME,UAClBJ,EAAQI,SAGbC,EAAO,mBAAiBD,GAAY,KAc1CE,MAbgB,CACZP,GAAgB,wBACZC,EAAQO,aAAe,CA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BAA6BpF,EAAWtD,EAAUje,GAChE,GAAyB,iBAAdsG,EAAwB,UAAUjU,MAAMiU,GACnD,IAAMxU,EAAgB80B,EAAAA,QAAQtgB,GAC1BugB,EAAiB,GAErB,GAAIV,EAEAU,EAASh1B,EAAoBC,QAQ/B,GAAIk0B,EACF,IACEa,EAASh1B,EAAoBC,EAE/B,CAAE,MAAO6L,GACPkpB,EAASh1B,EAAoBC,EAE/B,MAEA+0B,EAASC,EAAAA,0BAA0B,EAAGh1B,GAI1C,OAAO+0B,IAAW1f,CACpB,CAvGqBma,CAAOqB,EAAMiC,YAAazd,EAASwb,EAAMA,MAAO8C,GAEjE,OAAA3C,QAAAC,QAAAC,EAAA,GACKL,EAAK,CACRM,OAAQU,EAAWR,EAAAA,YAAYC,SAAWD,cAAYE,SAE1D,CAAE,MAAOpM,GACP,OAAA6L,QAAAC,QAAAC,EAAYL,CAAAA,EAAAA,EAAOM,CAAAA,OAAQE,cAAYE,SACzC,CACF,CAAC,MAAA1lB,UAAAmlB,QAAA+B,OAAAlnB,EAAA,CAAA,C6BdYopB,CAAmBpE,IAI9B,OAAAG,QAAAC,QAAOJ,EACT,CAAC,MAAAhlB,GAAA,OAAAmlB,QAAA+B,OAAAlnB,EAAA,CAAA"}
1
+ {"version":3,"file":"index.cjs","sources":["../src/bitcoin.ts","../src/index.ts","../src/eth.ts","../src/solana.ts"],"sourcesContent":["import { ProofStatus, SignatureProof } from \"@notabene/javascript-sdk\";\nimport { bech32 } from \"bech32\";\n\nimport {\n secp256k1,\n hash160,\n hash256,\n RecoveryId,\n encodeBase58AddressFormat,\n} from \"@bitauth/libauth\";\nimport { encode as encodeLength } from \"varuint-bitcoin\";\nimport { decode as decodeBase64 } from \"@stablelib/base64\";\n\nenum SEGWIT_TYPES {\n P2WPKH = \"p2wpkh\",\n P2SH_P2WPKH = \"p2sh(p2wpkh)\",\n}\n\nconst messagePrefix = \"\\u0018Bitcoin Signed Message:\\n\";\n\nenum DerivationMode {\n LEGACY = \"Legacy\",\n NATIVE = \"Native SegWit\",\n SEGWIT = \"SegWit\",\n P2SH_SEGWIT = \"p2sh\",\n BCH = \"Bitcoin Cash\",\n ETHEREUM = \"Ethereum\",\n DOGECOIN = \"Dogecoin\",\n UNKNOWN = \"Unknown\",\n}\n\nexport async function verifyBTCSignature(\n proof: SignatureProof,\n): Promise<SignatureProof> {\n const [ns, _, address] = proof.address.split(/:/);\n if (ns !== \"bip122\") return { ...proof, status: ProofStatus.FAILED };\n try {\n // const messageToBeSigned = message.replace(/\\s+/g, \" \").trim();\n const segwit = [DerivationMode.SEGWIT, DerivationMode.NATIVE].includes(\n getDerivationMode(address),\n );\n const verified = verify(proof.attestation, address, proof.proof, segwit);\n\n return {\n ...proof,\n status: verified ? ProofStatus.VERIFIED : ProofStatus.FAILED,\n };\n } catch (error) {\n return { ...proof, status: ProofStatus.FAILED };\n }\n}\n\nfunction getDerivationMode(address: string) {\n if (address.match(\"^(bc1|tb1|ltc1).*\")) {\n return DerivationMode.NATIVE;\n } else if (address.match(\"^[32M].*\")) {\n return DerivationMode.SEGWIT;\n } else if (address.match(\"^[1nmL].*\")) {\n return DerivationMode.LEGACY;\n } else if (address.match(\"^(D).*\")) {\n return DerivationMode.DOGECOIN;\n } else {\n throw new Error(\n \"INVALID ADDRESS: \"\n .concat(address)\n .concat(\" is not a valid or a supported address\"),\n );\n }\n}\n\ntype DecodedSignature = {\n compressed: boolean;\n segwitType?: SEGWIT_TYPES;\n recovery: RecoveryId;\n signature: Uint8Array;\n};\n\nfunction decodeSignature(proof: string): DecodedSignature {\n const signature = decodeBase64(proof);\n if (signature.length !== 65) throw new Error(\"Invalid signature length\");\n\n const flagByte = signature[0] - 27;\n if (flagByte > 15 || flagByte < 0) {\n throw new Error(\"Invalid signature parameter\");\n }\n\n return {\n compressed: !!(flagByte & 12),\n segwitType: !(flagByte & 8)\n ? undefined\n : !(flagByte & 4)\n ? SEGWIT_TYPES.P2SH_P2WPKH\n : SEGWIT_TYPES.P2WPKH,\n recovery: (flagByte & 3) as RecoveryId,\n signature: signature.slice(1),\n };\n}\n\nfunction verify(\n attestation: string,\n address: string,\n proof: string,\n checkSegwitAlways: boolean,\n) {\n const { compressed, segwitType, recovery, signature } =\n decodeSignature(proof);\n if (checkSegwitAlways && !compressed) {\n throw new Error(\n \"checkSegwitAlways can only be used with a compressed pubkey signature flagbyte\",\n );\n }\n\n const hash = magicHash(attestation);\n const publicKey: Uint8Array | string = compressed\n ? secp256k1.recoverPublicKeyCompressed(signature, recovery, hash)\n : secp256k1.recoverPublicKeyUncompressed(signature, recovery, hash);\n if (typeof publicKey === \"string\") throw new Error(publicKey);\n const publicKeyHash = hash160(publicKey);\n let actual: string = \"\";\n\n if (segwitType) {\n if (segwitType === SEGWIT_TYPES.P2SH_P2WPKH) {\n actual = encodeBech32Address(publicKeyHash);\n } else {\n // parsed.segwitType === SEGWIT_TYPES.P2WPKH\n // must be true since we only return null, P2SH_P2WPKH, or P2WPKH\n // from the decodeSignature function.\n actual = encodeBech32Address(publicKeyHash);\n }\n } else {\n if (checkSegwitAlways) {\n try {\n actual = encodeBech32Address(publicKeyHash);\n // if address is bech32 it is not p2sh\n } catch (e) {\n actual = encodeBech32Address(publicKeyHash);\n // base58 can be p2pkh or p2sh-p2wpkh\n }\n } else {\n actual = encodeBase58AddressFormat(0, publicKeyHash);\n }\n }\n\n return actual === address;\n}\n\nfunction magicHash(attestation: string) {\n const prefix = new TextEncoder().encode(messagePrefix);\n const message = new TextEncoder().encode(attestation);\n const length = encodeLength(message.length).buffer;\n const buffer = new Uint8Array(\n prefix.length + length.byteLength + message.length,\n );\n buffer.set(prefix);\n buffer.set(new Uint8Array(length), prefix.length);\n buffer.set(message, prefix.length + length.byteLength);\n return hash256(buffer);\n}\n\nfunction encodeBech32Address(publicKeyHash: Uint8Array): string {\n const bwords = bech32.toWords(publicKeyHash);\n bwords.unshift(0);\n return bech32.encode(\"bc\", bwords);\n}\n","import {\n type OwnershipProof,\n SignatureProof,\n DeclarationProof,\n ScreenshotProof,\n ProofTypes,\n ProofStatus,\n} from \"@notabene/javascript-sdk\";\nimport { verifyBTCSignature } from \"./bitcoin\";\nimport { verifyPersonalSignEIP191 } from \"./eth\";\nimport { verifySolanaSignature } from \"./solana\";\n\nexport async function verifyProof(\n proof: OwnershipProof,\n): Promise<OwnershipProof> {\n switch (proof.type) {\n case ProofTypes.SelfDeclaration:\n return {\n ...proof,\n status: (proof as DeclarationProof).confirmed\n ? ProofStatus.VERIFIED\n : ProofStatus.FAILED,\n };\n case ProofTypes.Screenshot:\n return {\n ...proof,\n status: (proof as ScreenshotProof).url\n ? ProofStatus.FLAGGED\n : ProofStatus.FAILED,\n };\n case ProofTypes.EIP191:\n return verifyPersonalSignEIP191(proof as SignatureProof);\n case ProofTypes.ED25519:\n return verifySolanaSignature(proof as SignatureProof);\n case ProofTypes.EIP712:\n case ProofTypes.BIP137:\n return verifyBTCSignature(proof as SignatureProof);\n case ProofTypes.BIP137_XPUB:\n case ProofTypes.MicroTransfer:\n }\n return proof;\n}\n","import { ProofStatus, SignatureProof } from \"@notabene/javascript-sdk\";\n\nimport { Secp256k1, Hex, PersonalMessage, Signature, Address } from \"ox\";\n\nexport function verifyEIP191(\n address: Hex.Hex,\n message: string,\n proof: Hex.Hex,\n): boolean {\n try {\n const payload = PersonalMessage.getSignPayload(Hex.fromString(message));\n const signature = Signature.fromHex(proof);\n const publicKey = Secp256k1.recoverPublicKey({ payload, signature });\n const recovered = Address.fromPublicKey(publicKey);\n return recovered.toString() === address.toString();\n } catch (error) {\n return false;\n }\n}\n\nexport async function verifyPersonalSignEIP191(\n proof: SignatureProof,\n): Promise<SignatureProof> {\n const [ns, _, address] = proof.address.split(/:/);\n if (ns !== \"eip155\") return { ...proof, status: ProofStatus.FAILED };\n\n const verified = verifyEIP191(\n address as Hex.Hex,\n proof.attestation,\n proof.proof as Hex.Hex,\n );\n return {\n ...proof,\n status: verified ? ProofStatus.VERIFIED : ProofStatus.FAILED,\n };\n}\n","import nacl from \"tweetnacl\";\nimport { ProofStatus, SignatureProof } from \"@notabene/javascript-sdk\";\nimport { decode as decodeBase64 } from \"@stablelib/base64\";\nimport bs58 from \"bs58\";\n\nexport async function verifySolanaSignature(\n proof: SignatureProof,\n): Promise<SignatureProof> {\n const [ns, _, address] = proof.address.split(/:/);\n if (ns !== \"solana\") return { ...proof, status: ProofStatus.FAILED };\n try {\n const publicKey = bs58.decode(address);\n const messageBytes = new TextEncoder().encode(proof.attestation);\n const signatureBytes = decodeBase64(proof.proof);\n const verified = nacl.sign.detached.verify(\n messageBytes,\n signatureBytes,\n publicKey,\n );\n\n return {\n ...proof,\n status: verified ? ProofStatus.VERIFIED : ProofStatus.FAILED,\n };\n } catch (error) {\n return { ...proof, status: ProofStatus.FAILED };\n }\n}\n"],"names":["SEGWIT_TYPES","DerivationMode","encodeBech32Address","publicKeyHash","bwords","bech32","toWords","unshift","encode","proof","type","ProofTypes","SelfDeclaration","Promise","resolve","_extends","status","confirmed","ProofStatus","VERIFIED","FAILED","Screenshot","url","FLAGGED","EIP191","_proof$address$split","address","split","_","verified","message","payload","PersonalMessage","getSignPayload","Hex","fromString","signature","Signature","fromHex","publicKey","Secp256k1","recoverPublicKey","Address","fromPublicKey","toString","error","verifyEIP191","attestation","e","reject","verifyPersonalSignEIP191","ED25519","bs58","decode","messageBytes","TextEncoder","signatureBytes","decodeBase64","nacl","sign","detached","verify","verifySolanaSignature","EIP712","BIP137","segwit","SEGWIT","NATIVE","includes","match","LEGACY","DOGECOIN","Error","concat","getDerivationMode","checkSegwitAlways","_decodeSignature","length","flagByte","compressed","segwitType","P2WPKH","P2SH_P2WPKH","undefined","recovery","slice","decodeSignature","hash","prefix","encodeLength","buffer","Uint8Array","byteLength","set","hash256","magicHash","secp256k1","recoverPublicKeyCompressed","recoverPublicKeyUncompressed","hash160","actual","encodeBase58AddressFormat","verifyBTCSignature"],"mappings":"6RAaKA,EAOAC,kQA2IL,SAASC,EAAoBC,GAC3B,IAAMC,EAASC,EAAA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