zattera-js 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +694 -0
- package/dist/browser/index.js +2466 -0
- package/dist/browser/index.js.map +1 -0
- package/dist/node/auth/index.js +188 -0
- package/dist/node/auth/index.js.map +1 -0
- package/dist/node/auth/keys.js +264 -0
- package/dist/node/auth/keys.js.map +1 -0
- package/dist/node/auth/memo.js +79 -0
- package/dist/node/auth/memo.js.map +1 -0
- package/dist/node/auth/serializer.js +162 -0
- package/dist/node/auth/serializer.js.map +1 -0
- package/dist/node/client/index.js +838 -0
- package/dist/node/client/index.js.map +1 -0
- package/dist/node/index.js +30 -0
- package/dist/node/index.js.map +1 -0
- package/dist/node/node_modules/@noble/ciphers/aes.js +254 -0
- package/dist/node/node_modules/@noble/ciphers/aes.js.map +1 -0
- package/dist/node/node_modules/@noble/ciphers/utils.js +113 -0
- package/dist/node/node_modules/@noble/ciphers/utils.js.map +1 -0
- package/dist/node/node_modules/@noble/hashes/esm/_md.js +146 -0
- package/dist/node/node_modules/@noble/hashes/esm/_md.js.map +1 -0
- package/dist/node/node_modules/@noble/hashes/esm/_u64.js +51 -0
- package/dist/node/node_modules/@noble/hashes/esm/_u64.js.map +1 -0
- package/dist/node/node_modules/@noble/hashes/esm/legacy.js +123 -0
- package/dist/node/node_modules/@noble/hashes/esm/legacy.js.map +1 -0
- package/dist/node/node_modules/@noble/hashes/esm/sha2.js +346 -0
- package/dist/node/node_modules/@noble/hashes/esm/sha2.js.map +1 -0
- package/dist/node/node_modules/@noble/hashes/esm/utils.js +73 -0
- package/dist/node/node_modules/@noble/hashes/esm/utils.js.map +1 -0
- package/dist/node/node_modules/@noble/secp256k1/index.js +578 -0
- package/dist/node/node_modules/@noble/secp256k1/index.js.map +1 -0
- package/dist/node/node_modules/bs58/node_modules/base-x/src/esm/index.js +132 -0
- package/dist/node/node_modules/bs58/node_modules/base-x/src/esm/index.js.map +1 -0
- package/dist/node/node_modules/bs58/src/esm/index.js +7 -0
- package/dist/node/node_modules/bs58/src/esm/index.js.map +1 -0
- package/dist/node/types/index.js +48 -0
- package/dist/node/types/index.js.map +1 -0
- package/dist/node/utils/chain-id.js +9 -0
- package/dist/node/utils/chain-id.js.map +1 -0
- package/dist/types/auth/index.d.ts +134 -0
- package/dist/types/auth/index.d.ts.map +1 -0
- package/dist/types/auth/keys.d.ts +112 -0
- package/dist/types/auth/keys.d.ts.map +1 -0
- package/dist/types/auth/memo.d.ts +51 -0
- package/dist/types/auth/memo.d.ts.map +1 -0
- package/dist/types/auth/serializer.d.ts +57 -0
- package/dist/types/auth/serializer.d.ts.map +1 -0
- package/dist/types/client/index.d.ts +360 -0
- package/dist/types/client/index.d.ts.map +1 -0
- package/dist/types/index.d.ts +16 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/types/index.d.ts +593 -0
- package/dist/types/types/index.d.ts.map +1 -0
- package/dist/types/utils/chain-id.d.ts +10 -0
- package/dist/types/utils/chain-id.d.ts.map +1 -0
- package/package.json +63 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../node_modules/@noble/hashes/esm/utils.js","../../node_modules/@noble/hashes/esm/_md.js","../../node_modules/@noble/hashes/esm/_u64.js","../../node_modules/@noble/hashes/esm/sha2.js","../../src/utils/chain-id.ts","../../src/client/index.ts","../../node_modules/@noble/secp256k1/index.js","../../node_modules/@noble/hashes/esm/legacy.js","../../node_modules/bs58/node_modules/base-x/src/esm/index.js","../../node_modules/bs58/src/esm/index.js","../../src/auth/keys.ts","../../src/auth/serializer.ts","../../node_modules/@noble/ciphers/utils.js","../../node_modules/@noble/ciphers/aes.js","../../src/auth/memo.ts","../../src/auth/index.ts","../../src/types/index.ts"],"sourcesContent":["/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! 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';\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n/** Asserts something is Uint8Array. */\nexport function 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}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function 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}\n/** Asserts output is properly-sized byte array */\nexport function 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}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\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 return arr;\n}\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\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 * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// 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 * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(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/**\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.\n */\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 * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([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/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\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 * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/** Copies several Uint8Arrays into one. */\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}\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}\n/** For runtime check if class implements interface */\nexport class Hash {\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher(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 createOptHasher(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 createXOFer(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 const wrapConstructor = createHasher;\nexport const wrapConstructorWithOpts = createOptHasher;\nexport const wrapXOFConstructorWithOpts = createXOFer;\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\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 Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from \"./utils.js\";\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function 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/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\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.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: 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 clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\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.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\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 const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\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 { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\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","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor(outputLen = 32) {\n super(64, outputLen, 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 clean(SHA256_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\nexport class SHA224 extends SHA256 {\n constructor() {\n super(28);\n this.A = SHA224_IV[0] | 0;\n this.B = SHA224_IV[1] | 0;\n this.C = SHA224_IV[2] | 0;\n this.D = SHA224_IV[3] | 0;\n this.E = SHA224_IV[4] | 0;\n this.F = SHA224_IV[5] | 0;\n this.G = SHA224_IV[6] | 0;\n this.H = SHA224_IV[7] | 0;\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor(outputLen = 64) {\n super(128, outputLen, 16, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = SHA512_IV[0] | 0;\n this.Al = SHA512_IV[1] | 0;\n this.Bh = SHA512_IV[2] | 0;\n this.Bl = SHA512_IV[3] | 0;\n this.Ch = SHA512_IV[4] | 0;\n this.Cl = SHA512_IV[5] | 0;\n this.Dh = SHA512_IV[6] | 0;\n this.Dl = SHA512_IV[7] | 0;\n this.Eh = SHA512_IV[8] | 0;\n this.El = SHA512_IV[9] | 0;\n this.Fh = SHA512_IV[10] | 0;\n this.Fl = SHA512_IV[11] | 0;\n this.Gh = SHA512_IV[12] | 0;\n this.Gl = SHA512_IV[13] | 0;\n this.Hh = SHA512_IV[14] | 0;\n this.Hl = SHA512_IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super(48);\n this.Ah = SHA384_IV[0] | 0;\n this.Al = SHA384_IV[1] | 0;\n this.Bh = SHA384_IV[2] | 0;\n this.Bl = SHA384_IV[3] | 0;\n this.Ch = SHA384_IV[4] | 0;\n this.Cl = SHA384_IV[5] | 0;\n this.Dh = SHA384_IV[6] | 0;\n this.Dl = SHA384_IV[7] | 0;\n this.Eh = SHA384_IV[8] | 0;\n this.El = SHA384_IV[9] | 0;\n this.Fh = SHA384_IV[10] | 0;\n this.Fl = SHA384_IV[11] | 0;\n this.Gh = SHA384_IV[12] | 0;\n this.Gl = SHA384_IV[13] | 0;\n this.Hh = SHA384_IV[14] | 0;\n this.Hl = SHA384_IV[15] | 0;\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super(28);\n this.Ah = T224_IV[0] | 0;\n this.Al = T224_IV[1] | 0;\n this.Bh = T224_IV[2] | 0;\n this.Bl = T224_IV[3] | 0;\n this.Ch = T224_IV[4] | 0;\n this.Cl = T224_IV[5] | 0;\n this.Dh = T224_IV[6] | 0;\n this.Dl = T224_IV[7] | 0;\n this.Eh = T224_IV[8] | 0;\n this.El = T224_IV[9] | 0;\n this.Fh = T224_IV[10] | 0;\n this.Fl = T224_IV[11] | 0;\n this.Gh = T224_IV[12] | 0;\n this.Gl = T224_IV[13] | 0;\n this.Hh = T224_IV[14] | 0;\n this.Hl = T224_IV[15] | 0;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super(32);\n this.Ah = T256_IV[0] | 0;\n this.Al = T256_IV[1] | 0;\n this.Bh = T256_IV[2] | 0;\n this.Bl = T256_IV[3] | 0;\n this.Ch = T256_IV[4] | 0;\n this.Cl = T256_IV[5] | 0;\n this.Dh = T256_IV[6] | 0;\n this.Dl = T256_IV[7] | 0;\n this.Eh = T256_IV[8] | 0;\n this.El = T256_IV[9] | 0;\n this.Fh = T256_IV[10] | 0;\n this.Fl = T256_IV[11] | 0;\n this.Gh = T256_IV[12] | 0;\n this.Gl = T256_IV[13] | 0;\n this.Hh = T256_IV[14] | 0;\n this.Hl = T256_IV[15] | 0;\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());\n//# sourceMappingURL=sha2.js.map","import { sha256 } from '@noble/hashes/sha2';\nimport type { NetworkName } from '../types/index.js';\n\n/**\n * Generate chain ID from network name using SHA256 hash\n * Follows the formula: fc::sha256::hash(chain_id_name)\n *\n * @param networkName - Network name to hash\n * @returns Hex string of the chain ID (without 0x prefix)\n */\nexport function generateChainId(networkName: NetworkName): string {\n const hash = sha256(new TextEncoder().encode(networkName));\n return Array.from(hash)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('');\n}\n","import type {\n ZatteraClientConfig,\n JsonRpcRequest,\n JsonRpcResponse,\n DynamicGlobalProperties,\n ChainConfig,\n WitnessSchedule,\n HardforkProperties,\n RewardFund,\n PriceFeed,\n FeedHistory,\n Account,\n Witness,\n Comment,\n SignedBlock,\n SignedTransaction,\n ListAccountsParams,\n FindAccountsParams,\n ListWitnessesParams,\n GetAccountHistoryParams,\n GetOpsInBlockParams,\n DiscussionQuery,\n GetFollowersParams,\n GetFollowingParams,\n BroadcastTransactionResult,\n VerifyAuthorityResult,\n GetTransactionResult,\n AccountHistoryEntry,\n Ticker,\n Volume,\n TradeHistory,\n MarketHistory,\n OrderBook,\n LimitOrder,\n ActiveVote,\n AccountName,\n PublicKey,\n TransactionId,\n OwnerHistory,\n AccountRecoveryRequest,\n Escrow,\n VestingDelegation,\n ConversionRequest,\n Vote,\n WitnessVote,\n} from '../types/index.js';\nimport { generateChainId } from '../utils/chain-id.js';\n\n/**\n * Zattera RPC Client\n *\n * Provides type-safe access to all Zattera blockchain RPC APIs\n * following JSON-RPC 2.0 specification\n */\nexport class ZatteraClient {\n private endpoint: string;\n private chainId: string;\n private timeout: number;\n private retries: number;\n private requestId: number;\n\n constructor(config: ZatteraClientConfig) {\n this.endpoint = config.endpoint;\n this.chainId = generateChainId(config.networkName || 'zattera');\n this.timeout = config.timeout ?? 30000;\n this.retries = config.retries ?? 3;\n this.requestId = 0;\n }\n\n private getNextId(): number {\n return ++this.requestId;\n }\n\n /**\n * Get the configured chain ID\n */\n getChainId(): string {\n return this.chainId;\n }\n\n /**\n * Internal method to make JSON-RPC 2.0 requests with retry logic\n */\n private async request<T>(\n method: string,\n params: unknown[] | Record<string, unknown> = {}\n ): Promise<T> {\n const request: JsonRpcRequest = {\n jsonrpc: '2.0',\n method,\n params,\n id: this.getNextId(),\n };\n\n let lastError: Error | null = null;\n\n for (let attempt = 0; attempt <= this.retries; attempt++) {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n const response = await fetch(this.endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(request),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n const data = (await response.json()) as JsonRpcResponse<T>;\n\n if (data.error) {\n throw new Error(\n `RPC error ${data.error.code}: ${data.error.message}`\n );\n }\n\n if (data.result === undefined) {\n throw new Error('No result in RPC response');\n }\n\n return data.result;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n\n if (attempt < this.retries) {\n // Exponential backoff: 1s, 2s, 4s, etc.\n await new Promise((resolve) =>\n setTimeout(resolve, 1000 * Math.pow(2, attempt))\n );\n }\n }\n }\n\n throw lastError ?? new Error('Request failed');\n }\n\n /**\n * Make batch JSON-RPC requests\n */\n async batch<T = unknown>(\n requests: Array<{ method: string; params?: unknown[] | Record<string, unknown> }>\n ): Promise<T[]> {\n const batchRequest = requests.map((req) => ({\n jsonrpc: '2.0' as const,\n method: req.method,\n params: req.params ?? {},\n id: this.getNextId(),\n }));\n\n let lastError: Error | null = null;\n\n for (let attempt = 0; attempt <= this.retries; attempt++) {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n const response = await fetch(this.endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(batchRequest),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n const data = (await response.json()) as JsonRpcResponse<T>[];\n\n return data.map((item) => {\n if (item.error) {\n throw new Error(\n `RPC error ${item.error.code}: ${item.error.message}`\n );\n }\n if (item.result === undefined) {\n throw new Error('No result in RPC response');\n }\n return item.result;\n });\n } catch (error) {\n lastError =\n error instanceof Error ? error : new Error(String(error));\n\n if (attempt < this.retries) {\n await new Promise((resolve) =>\n setTimeout(resolve, 1000 * Math.pow(2, attempt))\n );\n }\n }\n }\n\n throw lastError ?? new Error('Batch request failed');\n }\n\n // ============================================================================\n // Generic RPC Call\n // ============================================================================\n\n /**\n * Generic RPC call method for custom or new API methods\n */\n async call<T>(method: string, params: unknown[] | Record<string, unknown> = {}): Promise<T> {\n return this.request<T>(method, params);\n }\n\n // ============================================================================\n // Database API - Global Properties\n // ============================================================================\n\n /**\n * Get compile-time chain configuration constants\n */\n async getConfig(): Promise<ChainConfig> {\n return this.request<ChainConfig>('database_api.get_config', {});\n }\n\n /**\n * Get current dynamic global properties (head block, supply, etc.)\n */\n async getDynamicGlobalProperties(): Promise<DynamicGlobalProperties> {\n return this.request<DynamicGlobalProperties>(\n 'database_api.get_dynamic_global_properties',\n {}\n );\n }\n\n /**\n * Get active witness schedule\n */\n async getWitnessSchedule(): Promise<WitnessSchedule> {\n return this.request<WitnessSchedule>(\n 'database_api.get_witness_schedule',\n {}\n );\n }\n\n /**\n * Get hardfork properties and version information\n */\n async getHardforkProperties(): Promise<HardforkProperties> {\n return this.request<HardforkProperties>(\n 'database_api.get_hardfork_properties',\n {}\n );\n }\n\n /**\n * Get reward fund details\n */\n async getRewardFunds(): Promise<RewardFund[]> {\n const result = await this.request<{ funds: RewardFund[] }>('database_api.get_reward_funds', {});\n return result.funds;\n }\n\n /**\n * Get current median price feed\n */\n async getCurrentPriceFeed(): Promise<PriceFeed> {\n return this.request<PriceFeed>(\n 'database_api.get_current_price_feed',\n {}\n );\n }\n\n /**\n * Get price feed history\n */\n async getFeedHistory(): Promise<FeedHistory> {\n return this.request<FeedHistory>('database_api.get_feed_history', {});\n }\n\n // ============================================================================\n // Database API - Witnesses\n // ============================================================================\n\n /**\n * List witnesses by specified order\n */\n async listWitnesses(params: ListWitnessesParams): Promise<Witness[]> {\n const result = await this.request<{ witnesses: Witness[] }>('database_api.list_witnesses', params);\n return result.witnesses;\n }\n\n /**\n * Find specific witnesses by account names\n */\n async findWitnesses(owners: AccountName[]): Promise<Witness[]> {\n const result = await this.request<{ witnesses: Witness[] }>('database_api.find_witnesses', {\n owners,\n });\n return result.witnesses;\n }\n\n /**\n * List witness votes\n */\n async listWitnessVotes(\n start: [AccountName, AccountName] | null,\n limit: number,\n order: string\n ): Promise<WitnessVote[]> {\n return this.request<WitnessVote[]>('database_api.list_witness_votes', {\n start,\n limit,\n order,\n });\n }\n\n /**\n * Get currently active witnesses\n */\n async getActiveWitnesses(): Promise<AccountName[]> {\n const result = await this.request<{ witnesses: AccountName[] }>(\n 'database_api.get_active_witnesses',\n {}\n );\n return result.witnesses;\n }\n\n // ============================================================================\n // Database API - Accounts\n // ============================================================================\n\n /**\n * List accounts by specified order\n */\n async listAccounts(params: ListAccountsParams): Promise<Account[]> {\n const result = await this.request<{ accounts: Account[] }>('database_api.list_accounts', params);\n return result.accounts;\n }\n\n /**\n * Find specific accounts by names\n */\n async findAccounts(params: FindAccountsParams): Promise<Account[]> {\n const result = await this.request<{ accounts: Account[] }>('database_api.find_accounts', params);\n return result.accounts;\n }\n\n /**\n * List account owner authority change history\n */\n async listOwnerHistories(\n start: [AccountName, string] | null,\n limit: number\n ): Promise<OwnerHistory[]> {\n return this.request<OwnerHistory[]>(\n 'database_api.list_owner_histories',\n { start, limit }\n );\n }\n\n /**\n * Find owner history for specific account\n */\n async findOwnerHistories(owner: AccountName): Promise<OwnerHistory[]> {\n return this.request<OwnerHistory[]>(\n 'database_api.find_owner_histories',\n { owner }\n );\n }\n\n /**\n * List account recovery requests\n */\n async listAccountRecoveryRequests(\n start: AccountName | null,\n limit: number,\n order: string\n ): Promise<AccountRecoveryRequest[]> {\n return this.request<AccountRecoveryRequest[]>(\n 'database_api.list_account_recovery_requests',\n { start, limit, order }\n );\n }\n\n /**\n * Find account recovery requests\n */\n async findAccountRecoveryRequests(\n accounts: AccountName[]\n ): Promise<AccountRecoveryRequest[]> {\n return this.request<AccountRecoveryRequest[]>(\n 'database_api.find_account_recovery_requests',\n { accounts }\n );\n }\n\n /**\n * List escrows\n */\n async listEscrows(\n start: [AccountName, number] | null,\n limit: number,\n order: string\n ): Promise<Escrow[]> {\n return this.request<Escrow[]>('database_api.list_escrows', {\n start,\n limit,\n order,\n });\n }\n\n /**\n * Find escrows\n */\n async findEscrows(from: AccountName): Promise<Escrow[]> {\n return this.request<Escrow[]>('database_api.find_escrows', { from });\n }\n\n /**\n * List vesting delegations\n */\n async listVestingDelegations(\n start: [AccountName, AccountName] | null,\n limit: number,\n order: string\n ): Promise<VestingDelegation[]> {\n return this.request<VestingDelegation[]>(\n 'database_api.list_vesting_delegations',\n { start, limit, order }\n );\n }\n\n /**\n * Find vesting delegations\n */\n async findVestingDelegations(\n account: AccountName\n ): Promise<VestingDelegation[]> {\n return this.request<VestingDelegation[]>(\n 'database_api.find_vesting_delegations',\n { account }\n );\n }\n\n /**\n * List SBD conversion requests\n */\n async listDollarConversionRequests(\n start: [AccountName, number] | null,\n limit: number,\n order: string\n ): Promise<ConversionRequest[]> {\n return this.request<ConversionRequest[]>(\n 'database_api.list_dollar_conversion_requests',\n { start, limit, order }\n );\n }\n\n /**\n * Find SBD conversion requests\n */\n async findDollarConversionRequests(\n account: AccountName\n ): Promise<ConversionRequest[]> {\n return this.request<ConversionRequest[]>(\n 'database_api.find_dollar_conversion_requests',\n { account }\n );\n }\n\n // ============================================================================\n // Database API - Comments\n // ============================================================================\n\n /**\n * List comments by specified order\n */\n async listComments(\n start: [AccountName, string] | null,\n limit: number,\n order: string\n ): Promise<Comment[]> {\n return this.request<Comment[]>('database_api.list_comments', {\n start,\n limit,\n order,\n });\n }\n\n /**\n * Find specific comments\n */\n async findComments(\n comments: Array<[AccountName, string]>\n ): Promise<Comment[]> {\n return this.request<Comment[]>('database_api.find_comments', {\n comments,\n });\n }\n\n /**\n * List votes\n */\n async listVotes(\n start: [AccountName, AccountName, string] | null,\n limit: number,\n order: string\n ): Promise<Vote[]> {\n return this.request<Vote[]>('database_api.list_votes', {\n start,\n limit,\n order,\n });\n }\n\n /**\n * Find specific votes\n */\n async findVotes(\n author: AccountName,\n permlink: string\n ): Promise<Vote[]> {\n return this.request<Vote[]>('database_api.find_votes', {\n author,\n permlink,\n });\n }\n\n // ============================================================================\n // Database API - Market\n // ============================================================================\n\n /**\n * List limit orders\n */\n async listLimitOrders(\n start: [AccountName, number] | null,\n limit: number,\n order: string\n ): Promise<LimitOrder[]> {\n return this.request<LimitOrder[]>('database_api.list_limit_orders', {\n start,\n limit,\n order,\n });\n }\n\n /**\n * Find limit orders\n */\n async findLimitOrders(account: AccountName): Promise<LimitOrder[]> {\n return this.request<LimitOrder[]>('database_api.find_limit_orders', {\n account,\n });\n }\n\n /**\n * Get current order book\n */\n async getOrderBook(limit: number = 50): Promise<OrderBook> {\n return this.request<OrderBook>('database_api.get_order_book', {\n limit,\n });\n }\n\n // ============================================================================\n // Database API - Authority & Validation\n // ============================================================================\n\n /**\n * Get transaction as hex string\n */\n async getTransactionHex(trx: SignedTransaction): Promise<string> {\n return this.request<string>('database_api.get_transaction_hex', { trx });\n }\n\n /**\n * Get required signatures for transaction\n */\n async getRequiredSignatures(\n trx: SignedTransaction,\n availableKeys: PublicKey[]\n ): Promise<PublicKey[]> {\n return this.request<PublicKey[]>(\n 'database_api.get_required_signatures',\n { trx, available_keys: availableKeys }\n );\n }\n\n /**\n * Get all potential signatures for transaction\n */\n async getPotentialSignatures(\n trx: SignedTransaction\n ): Promise<PublicKey[]> {\n return this.request<PublicKey[]>(\n 'database_api.get_potential_signatures',\n { trx }\n );\n }\n\n /**\n * Verify transaction has required authority\n */\n async verifyAuthority(trx: SignedTransaction): Promise<VerifyAuthorityResult> {\n return this.request<VerifyAuthorityResult>(\n 'database_api.verify_authority',\n { trx }\n );\n }\n\n /**\n * Verify account has authority from signers\n */\n async verifyAccountAuthority(\n account: AccountName,\n signers: PublicKey[]\n ): Promise<VerifyAuthorityResult> {\n return this.request<VerifyAuthorityResult>(\n 'database_api.verify_account_authority',\n { account, signers }\n );\n }\n\n /**\n * Verify arbitrary signatures\n */\n async verifySignatures(\n hash: string,\n signatures: string[],\n requiredOwner: AccountName[],\n requiredActive: AccountName[],\n requiredPosting: AccountName[],\n requiredOther: PublicKey[]\n ): Promise<VerifyAuthorityResult> {\n return this.request<VerifyAuthorityResult>(\n 'database_api.verify_signatures',\n {\n hash,\n signatures,\n required_owner: requiredOwner,\n required_active: requiredActive,\n required_posting: requiredPosting,\n required_other: requiredOther,\n }\n );\n }\n\n // ============================================================================\n // Network Broadcast API\n // ============================================================================\n\n /**\n * Broadcast transaction to the network\n */\n async broadcastTransaction(\n trx: SignedTransaction,\n maxBlockAge: number = -1\n ): Promise<BroadcastTransactionResult> {\n return this.request<BroadcastTransactionResult>(\n 'network_broadcast_api.broadcast_transaction',\n { trx, max_block_age: maxBlockAge }\n );\n }\n\n /**\n * Broadcast block to the network\n */\n async broadcastBlock(block: SignedBlock): Promise<void> {\n return this.request<void>('network_broadcast_api.broadcast_block', {\n block,\n });\n }\n\n // ============================================================================\n // Block API\n // ============================================================================\n\n /**\n * Get block header by block number\n */\n async getBlockHeader(blockNum: number): Promise<SignedBlock> {\n const result = await this.request<{ header: SignedBlock }>('block_api.get_block_header', {\n block_num: blockNum,\n });\n return result.header;\n }\n\n /**\n * Get full block by block number\n */\n async getBlock(blockNum: number): Promise<SignedBlock> {\n const result = await this.request<{ block: SignedBlock }>('block_api.get_block', {\n block_num: blockNum,\n });\n return result.block;\n }\n\n // ============================================================================\n // Account History API\n // ============================================================================\n\n /**\n * Get operations in a specific block\n */\n async getOpsInBlock(params: GetOpsInBlockParams): Promise<unknown[]> {\n return this.request<unknown[]>('account_history_api.get_ops_in_block', params);\n }\n\n /**\n * Get transaction by ID\n */\n async getTransaction(id: TransactionId): Promise<GetTransactionResult> {\n return this.request<GetTransactionResult>(\n 'account_history.get_transaction',\n { id }\n );\n }\n\n /**\n * Get account operation history\n */\n async getAccountHistory(\n params: GetAccountHistoryParams\n ): Promise<Record<number, AccountHistoryEntry>> {\n return this.request<Record<number, AccountHistoryEntry>>(\n 'account_history.get_account_history',\n params\n );\n }\n\n /**\n * Enumerate virtual operations in block range\n */\n async enumVirtualOps(\n blockRangeBegin: number,\n blockRangeEnd: number\n ): Promise<unknown[]> {\n return this.request<unknown[]>('account_history_api.enum_virtual_ops', {\n block_range_begin: blockRangeBegin,\n block_range_end: blockRangeEnd,\n });\n }\n\n // ============================================================================\n // Tags/Discussion API\n // ============================================================================\n\n /**\n * Get trending tags\n */\n async getTrendingTags(\n startTag: string = '',\n limit: number = 100\n ): Promise<unknown[]> {\n const result = await this.request<{ tags: unknown[] }>('tags_api.get_trending_tags', {\n start_tag: startTag,\n limit,\n });\n return result.tags;\n }\n\n /**\n * Get tags used by author\n */\n async getTagsUsedByAuthor(author: AccountName): Promise<unknown[]> {\n return this.request<unknown[]>('tags_api.get_tags_used_by_author', {\n author,\n });\n }\n\n /**\n * Get single discussion/post\n */\n async getDiscussion(\n author: AccountName,\n permlink: string\n ): Promise<Comment> {\n return this.request<Comment>('tags_api.get_discussion', {\n author,\n permlink,\n });\n }\n\n /**\n * Get replies to a post\n */\n async getContentReplies(\n author: AccountName,\n permlink: string\n ): Promise<Comment[]> {\n const result = await this.request<{ discussions: Comment[] }>('tags_api.get_content_replies', {\n author,\n permlink,\n });\n return result.discussions;\n }\n\n /**\n * Get discussions by trending\n */\n async getDiscussionsByTrending(\n query: DiscussionQuery\n ): Promise<Comment[]> {\n return this.request<Comment[]>('tags_api.get_discussions_by_trending', query);\n }\n\n /**\n * Get discussions by creation time\n */\n async getDiscussionsByCreated(query: DiscussionQuery): Promise<Comment[]> {\n return this.request<Comment[]>('tags_api.get_discussions_by_created', query);\n }\n\n /**\n * Get discussions by activity\n */\n async getDiscussionsByActive(query: DiscussionQuery): Promise<Comment[]> {\n return this.request<Comment[]>('tags_api.get_discussions_by_active', query);\n }\n\n /**\n * Get discussions by cashout time\n */\n async getDiscussionsByCashout(query: DiscussionQuery): Promise<Comment[]> {\n return this.request<Comment[]>('tags_api.get_discussions_by_cashout', query);\n }\n\n /**\n * Get discussions by votes\n */\n async getDiscussionsByVotes(query: DiscussionQuery): Promise<Comment[]> {\n return this.request<Comment[]>('tags_api.get_discussions_by_votes', query);\n }\n\n /**\n * Get discussions by children count\n */\n async getDiscussionsByChildren(query: DiscussionQuery): Promise<Comment[]> {\n return this.request<Comment[]>('tags_api.get_discussions_by_children', query);\n }\n\n /**\n * Get hot discussions\n */\n async getDiscussionsByHot(query: DiscussionQuery): Promise<Comment[]> {\n return this.request<Comment[]>('tags_api.get_discussions_by_hot', query);\n }\n\n /**\n * Get discussions from follower feed\n */\n async getDiscussionsByFeed(query: DiscussionQuery): Promise<Comment[]> {\n return this.request<Comment[]>('tags_api.get_discussions_by_feed', query);\n }\n\n /**\n * Get discussions from blog\n */\n async getDiscussionsByBlog(query: DiscussionQuery): Promise<Comment[]> {\n return this.request<Comment[]>('tags_api.get_discussions_by_blog', query);\n }\n\n /**\n * Get discussions by comment count\n */\n async getDiscussionsByComments(query: DiscussionQuery): Promise<Comment[]> {\n return this.request<Comment[]>('tags_api.get_discussions_by_comments', query);\n }\n\n /**\n * Get promoted discussions\n */\n async getDiscussionsByPromoted(query: DiscussionQuery): Promise<Comment[]> {\n return this.request<Comment[]>('tags_api.get_discussions_by_promoted', query);\n }\n\n /**\n * Get active votes on a post\n */\n async getActiveVotes(\n author: AccountName,\n permlink: string\n ): Promise<ActiveVote[]> {\n return this.request<ActiveVote[]>('tags_api.get_active_votes', {\n author,\n permlink,\n });\n }\n\n // ============================================================================\n // Follow API\n // ============================================================================\n\n /**\n * Get followers of an account\n */\n async getFollowers(params: GetFollowersParams): Promise<unknown[]> {\n const result = await this.request<{ followers: unknown[] }>('follow_api.get_followers', params);\n return result.followers;\n }\n\n /**\n * Get accounts that an account is following\n */\n async getFollowing(params: GetFollowingParams): Promise<unknown[]> {\n const result = await this.request<{ following: unknown[] }>('follow_api.get_following', params);\n return result.following;\n }\n\n /**\n * Get follower and following counts\n */\n async getFollowCount(account: AccountName): Promise<{\n account: AccountName;\n follower_count: number;\n following_count: number;\n }> {\n return this.request('follow_api.get_follow_count', { account });\n }\n\n /**\n * Get feed entries\n */\n async getFeedEntries(\n account: AccountName,\n startEntryId: number = 0,\n limit: number = 100\n ): Promise<unknown[]> {\n return this.request<unknown[]>('follow_api.get_feed_entries', {\n account,\n start_entry_id: startEntryId,\n limit,\n });\n }\n\n /**\n * Get feed with full comments\n */\n async getFeed(\n account: AccountName,\n startEntryId: number = 0,\n limit: number = 100\n ): Promise<Comment[]> {\n return this.request<Comment[]>('follow_api.get_feed', {\n account,\n start_entry_id: startEntryId,\n limit,\n });\n }\n\n /**\n * Get blog entries\n */\n async getBlogEntries(\n account: AccountName,\n startEntryId: number = 0,\n limit: number = 100\n ): Promise<unknown[]> {\n return this.request<unknown[]>('follow_api.get_blog_entries', {\n account,\n start_entry_id: startEntryId,\n limit,\n });\n }\n\n /**\n * Get blog with full comments\n */\n async getBlog(\n account: AccountName,\n startEntryId: number = 0,\n limit: number = 100\n ): Promise<Comment[]> {\n return this.request<Comment[]>('follow_api.get_blog', {\n account,\n start_entry_id: startEntryId,\n limit,\n });\n }\n\n /**\n * Get account reputation scores\n */\n async getAccountReputations(\n accountLowerBound: AccountName = '',\n limit: number = 100\n ): Promise<unknown[]> {\n return this.request<unknown[]>('follow_api.get_account_reputations', {\n account_lower_bound: accountLowerBound,\n limit,\n });\n }\n\n /**\n * Get accounts that reblogged a post\n */\n async getRebloggedBy(\n author: AccountName,\n permlink: string\n ): Promise<AccountName[]> {\n return this.request<AccountName[]>('follow_api.get_reblogged_by', {\n author,\n permlink,\n });\n }\n\n /**\n * Get blog author statistics\n */\n async getBlogAuthors(blogAccount: AccountName): Promise<unknown[]> {\n return this.request<unknown[]>('follow_api.get_blog_authors', {\n blog_account: blogAccount,\n });\n }\n\n // ============================================================================\n // Market History API\n // ============================================================================\n\n /**\n * Get market ticker\n */\n async getTicker(): Promise<Ticker> {\n return this.request<Ticker>('market_history_api.get_ticker', {});\n }\n\n /**\n * Get market volume\n */\n async getVolume(): Promise<Volume> {\n return this.request<Volume>('market_history_api.get_volume', {});\n }\n\n /**\n * Get market order book\n */\n async getMarketOrderBook(limit: number = 50): Promise<OrderBook> {\n return this.request<OrderBook>('market_history_api.get_order_book', {\n limit,\n });\n }\n\n /**\n * Get trade history\n */\n async getTradeHistory(\n start: string,\n end: string,\n limit: number = 100\n ): Promise<TradeHistory[]> {\n return this.request<TradeHistory[]>('market_history_api.get_trade_history', {\n start,\n end,\n limit,\n });\n }\n\n /**\n * Get recent trades\n */\n async getRecentTrades(limit: number = 100): Promise<TradeHistory[]> {\n return this.request<TradeHistory[]>('market_history_api.get_recent_trades', {\n limit,\n });\n }\n\n /**\n * Get market history buckets\n */\n async getMarketHistory(\n bucketSeconds: number,\n start: string,\n end: string\n ): Promise<MarketHistory[]> {\n return this.request<MarketHistory[]>(\n 'market_history_api.get_market_history',\n {\n bucket_seconds: bucketSeconds,\n start,\n end,\n }\n );\n }\n\n /**\n * Get available bucket sizes\n */\n async getMarketHistoryBuckets(): Promise<number[]> {\n const result = await this.request<{ bucket_sizes: number[] }>(\n 'market_history_api.get_market_history_buckets',\n {}\n );\n return result.bucket_sizes;\n }\n\n // ============================================================================\n // Account By Key API\n // ============================================================================\n\n /**\n * Get accounts that can sign with given public keys\n */\n async getKeyReferences(keys: PublicKey[]): Promise<AccountName[][]> {\n return this.request<AccountName[][]>('account_by_key_api.get_key_references', {\n keys,\n });\n }\n\n // ============================================================================\n // JSON-RPC Meta API\n // ============================================================================\n\n /**\n * Get list of all available RPC methods\n */\n async getMethods(): Promise<string[]> {\n return this.request<string[]>('jsonrpc.get_methods', {});\n }\n\n /**\n * Get signature (parameters and return type) for an RPC method\n */\n async getSignature(method: string): Promise<unknown> {\n return this.request<unknown>('jsonrpc.get_signature', { method });\n }\n}\n","/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */\n/**\n * 4KB JS implementation of secp256k1 ECDSA / Schnorr signatures & ECDH.\n * Compliant with RFC6979 & BIP340.\n * @module\n */\n/**\n * Curve params. secp256k1 is short weierstrass / koblitz curve. Equation is y² == x³ + ax + b.\n * * P = `2n**256n-2n**32n-2n**977n` // field over which calculations are done\n * * N = `2n**256n - 0x14551231950b75fc4402da1732fc9bebfn` // group order, amount of curve points\n * * h = `1n` // cofactor\n * * a = `0n` // equation param\n * * b = `7n` // equation param\n * * Gx, Gy are coordinates of Generator / base point\n */\nconst secp256k1_CURVE = {\n p: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,\n n: 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,\n h: 1n,\n a: 0n,\n b: 7n,\n Gx: 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,\n Gy: 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n,\n};\nconst { p: P, n: N, Gx, Gy, b: _b } = secp256k1_CURVE;\nconst L = 32; // field / group byte length\nconst L2 = 64;\n// Helpers and Precomputes sections are reused between libraries\n// ## Helpers\n// ----------\n// error helper, messes-up stack trace\nconst err = (m = '') => {\n throw new Error(m);\n};\nconst isBig = (n) => typeof n === 'bigint'; // is big integer\nconst isStr = (s) => typeof s === 'string'; // is string\nconst isBytes = (a) => a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n/** assert is Uint8Array (of specific length) */\nconst abytes = (a, l) => !isBytes(a) || (typeof l === 'number' && l > 0 && a.length !== l)\n ? err('Uint8Array expected')\n : a;\n/** create Uint8Array */\nconst u8n = (len) => new Uint8Array(len);\nconst u8fr = (buf) => Uint8Array.from(buf);\nconst padh = (n, pad) => n.toString(16).padStart(pad, '0');\nconst bytesToHex = (b) => Array.from(abytes(b))\n .map((e) => padh(e, 2))\n .join('');\nconst C = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; // ASCII characters\nconst _ch = (ch) => {\n if (ch >= C._0 && ch <= C._9)\n return ch - C._0; // '2' => 50-48\n if (ch >= C.A && ch <= C.F)\n return ch - (C.A - 10); // 'B' => 66-(65-10)\n if (ch >= C.a && ch <= C.f)\n return ch - (C.a - 10); // 'b' => 98-(97-10)\n return;\n};\nconst hexToBytes = (hex) => {\n const e = 'hex invalid';\n if (!isStr(hex))\n return err(e);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n return err(e);\n const array = u8n(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n // treat each char as ASCII\n const n1 = _ch(hex.charCodeAt(hi)); // parse first char, multiply it by 16\n const n2 = _ch(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined)\n return err(e);\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\n};\n/** normalize hex or ui8a to ui8a */\nconst toU8 = (a, len) => abytes(isStr(a) ? hexToBytes(a) : u8fr(abytes(a)), len);\nconst cr = () => globalThis?.crypto; // WebCrypto is available in all modern environments\nconst subtle = () => cr()?.subtle ?? err('crypto.subtle must be defined');\n// prettier-ignore\nconst concatBytes = (...arrs) => {\n const r = u8n(arrs.reduce((sum, a) => sum + abytes(a).length, 0)); // create u8a of summed length\n let pad = 0; // walk through each array,\n arrs.forEach(a => { r.set(a, pad); pad += a.length; }); // ensure they have proper type\n return r;\n};\n/** WebCrypto OS-level CSPRNG (random number generator). Will throw when not available. */\nconst randomBytes = (len = L) => {\n const c = cr();\n return c.getRandomValues(u8n(len));\n};\nconst big = BigInt;\nconst arange = (n, min, max, msg = 'bad number: out of range') => isBig(n) && min <= n && n < max ? n : err(msg);\n/** modular division */\nconst M = (a, b = P) => {\n const r = a % b;\n return r >= 0n ? r : b + r;\n};\nconst modN = (a) => M(a, N);\n/** Modular inversion using eucledian GCD (non-CT). No negative exponent for now. */\n// prettier-ignore\nconst invert = (num, md) => {\n if (num === 0n || md <= 0n)\n err('no inverse n=' + num + ' mod=' + md);\n let a = M(num, md), b = md, x = 0n, y = 1n, u = 1n, v = 0n;\n while (a !== 0n) {\n const q = b / a, r = b % a;\n const m = x - u * q, n = y - v * q;\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n return b === 1n ? M(x, md) : err('no inverse'); // b is gcd at this point\n};\nconst callHash = (name) => {\n // @ts-ignore\n const fn = etc[name];\n if (typeof fn !== 'function')\n err('hashes.' + name + ' not set');\n return fn;\n};\nconst apoint = (p) => (p instanceof Point ? p : err('Point expected'));\n// ## End of Helpers\n// -----------------\n/** secp256k1 formula. Koblitz curves are subclass of weierstrass curves with a=0, making it x³+b */\nconst koblitz = (x) => M(M(x * x) * x + _b);\n/** assert is field element or 0 */\nconst afield0 = (n) => arange(n, 0n, P);\n/** assert is field element */\nconst afield = (n) => arange(n, 1n, P);\n/** assert is group elem */\nconst agroup = (n) => arange(n, 1n, N);\nconst isEven = (y) => (y & 1n) === 0n;\n/** create Uint8Array of byte n */\nconst u8of = (n) => Uint8Array.of(n);\nconst getPrefix = (y) => u8of(isEven(y) ? 0x02 : 0x03);\n/** lift_x from BIP340 calculates square root. Validates x, then validates root*root. */\nconst lift_x = (x) => {\n // Let c = x³ + 7 mod p. Fail if x ≥ p. (also fail if x < 1)\n const c = koblitz(afield(x));\n // c = √y\n // y = c^((p+1)/4) mod p\n // This formula works for fields p = 3 mod 4 -- a special, fast case.\n // Paper: \"Square Roots from 1;24,51,10 to Dan Shanks\".\n let r = 1n;\n for (let num = c, e = (P + 1n) / 4n; e > 0n; e >>= 1n) {\n // powMod: modular exponentiation.\n if (e & 1n)\n r = (r * num) % P; // Uses exponentiation by squaring.\n num = (num * num) % P; // Not constant-time.\n }\n return M(r * r) === c ? r : err('sqrt invalid'); // check if result is valid\n};\n/** Point in 3d xyz projective coordinates. 3d takes less inversions than 2d. */\nclass Point {\n static BASE;\n static ZERO;\n px;\n py;\n pz;\n constructor(px, py, pz) {\n this.px = afield0(px);\n this.py = afield(py); // y can't be 0 in Projective\n this.pz = afield0(pz);\n Object.freeze(this);\n }\n /** Convert Uint8Array or hex string to Point. */\n static fromBytes(bytes) {\n abytes(bytes);\n let p = undefined;\n // First byte is prefix, rest is data. There are 2 kinds: compressed & uncompressed:\n // * [0x02 or 0x03][32-byte x coordinate]\n // * [0x04] [32-byte x coordinate][32-byte y coordinate]\n const head = bytes[0];\n const tail = bytes.subarray(1);\n const x = sliceBytesNumBE(tail, 0, L);\n const len = bytes.length;\n // Compressed 33-byte point, 0x02 or 0x03 prefix\n if (len === L + 1 && [0x02, 0x03].includes(head)) {\n // Equation is y² == x³ + ax + b. We calculate y from x.\n // y = √y²; there are two solutions: y, -y. Determine proper solution based on prefix\n let y = lift_x(x);\n const evenY = isEven(y);\n const evenH = isEven(big(head));\n if (evenH !== evenY)\n y = M(-y);\n p = new Point(x, y, 1n);\n }\n // Uncompressed 65-byte point, 0x04 prefix\n if (len === L2 + 1 && head === 0x04)\n p = new Point(x, sliceBytesNumBE(tail, L, L2), 1n);\n // Validate point\n return p ? p.assertValidity() : err('bad point: not on curve');\n }\n /** Equality check: compare points P&Q. */\n equals(other) {\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = apoint(other); // checks class equality\n const X1Z2 = M(X1 * Z2);\n const X2Z1 = M(X2 * Z1);\n const Y1Z2 = M(Y1 * Z2);\n const Y2Z1 = M(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() {\n return this.equals(I);\n }\n /** Flip point over y coordinate. */\n negate() {\n return new Point(this.px, M(-this.py), this.pz);\n }\n /** Point doubling: P+P, complete formula. */\n double() {\n return this.add(this);\n }\n /**\n * Point addition: P+Q, complete, exception-free formula\n * (Renes-Costello-Batina, algo 1 of [2015/1060](https://eprint.iacr.org/2015/1060)).\n * Cost: `12M + 0S + 3*a + 3*b3 + 23add`.\n */\n // prettier-ignore\n add(other) {\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = apoint(other);\n const a = 0n;\n const b = _b;\n let X3 = 0n, Y3 = 0n, Z3 = 0n;\n const b3 = M(b * 3n);\n let t0 = M(X1 * X2), t1 = M(Y1 * Y2), t2 = M(Z1 * Z2), t3 = M(X1 + Y1); // step 1\n let t4 = M(X2 + Y2); // step 5\n t3 = M(t3 * t4);\n t4 = M(t0 + t1);\n t3 = M(t3 - t4);\n t4 = M(X1 + Z1);\n let t5 = M(X2 + Z2); // step 10\n t4 = M(t4 * t5);\n t5 = M(t0 + t2);\n t4 = M(t4 - t5);\n t5 = M(Y1 + Z1);\n X3 = M(Y2 + Z2); // step 15\n t5 = M(t5 * X3);\n X3 = M(t1 + t2);\n t5 = M(t5 - X3);\n Z3 = M(a * t4);\n X3 = M(b3 * t2); // step 20\n Z3 = M(X3 + Z3);\n X3 = M(t1 - Z3);\n Z3 = M(t1 + Z3);\n Y3 = M(X3 * Z3);\n t1 = M(t0 + t0); // step 25\n t1 = M(t1 + t0);\n t2 = M(a * t2);\n t4 = M(b3 * t4);\n t1 = M(t1 + t2);\n t2 = M(t0 - t2); // step 30\n t2 = M(a * t2);\n t4 = M(t4 + t2);\n t0 = M(t1 * t4);\n Y3 = M(Y3 + t0);\n t0 = M(t5 * t4); // step 35\n X3 = M(t3 * X3);\n X3 = M(X3 - t0);\n t0 = M(t3 * t1);\n Z3 = M(t5 * Z3);\n Z3 = M(Z3 + t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n /**\n * Point-by-scalar multiplication. Scalar must be in range 1 <= n < CURVE.n.\n * Uses {@link wNAF} for base point.\n * Uses fake point to mitigate side-channel leakage.\n * @param n scalar by which point is multiplied\n * @param safe safe mode guards against timing attacks; unsafe mode is faster\n */\n multiply(n, safe = true) {\n if (!safe && n === 0n)\n return I;\n agroup(n);\n if (n === 1n)\n return this;\n if (this.equals(G))\n return wNAF(n).p;\n // init result point & fake point\n let p = I;\n let f = G;\n for (let d = this; n > 0n; d = d.double(), n >>= 1n) {\n // if bit is present, add to point\n // if not present, add to fake, for timing safety\n if (n & 1n)\n p = p.add(d);\n else if (safe)\n f = f.add(d);\n }\n return p;\n }\n /** Convert point to 2d xy affine point. (X, Y, Z) ∋ (x=X/Z, y=Y/Z) */\n toAffine() {\n const { px: x, py: y, pz: z } = this;\n // fast-paths for ZERO point OR Z=1\n if (this.equals(I))\n return { x: 0n, y: 0n };\n if (z === 1n)\n return { x, y };\n const iz = invert(z, P);\n // (Z * Z^-1) must be 1, otherwise bad math\n if (M(z * iz) !== 1n)\n err('inverse invalid');\n // x = X*Z^-1; y = Y*Z^-1\n return { x: M(x * iz), y: M(y * iz) };\n }\n /** Checks if the point is valid and on-curve. */\n assertValidity() {\n const { x, y } = this.toAffine(); // convert to 2d xy affine point.\n afield(x); // must be in range 1 <= x,y < P\n afield(y);\n // y² == x³ + ax + b, equation sides must be equal\n return M(y * y) === koblitz(x) ? this : err('bad point: not on curve');\n }\n /** Converts point to 33/65-byte Uint8Array. */\n toBytes(isCompressed = true) {\n const { x, y } = this.assertValidity().toAffine();\n const x32b = numTo32b(x);\n if (isCompressed)\n return concatBytes(getPrefix(y), x32b);\n return concatBytes(u8of(0x04), x32b, numTo32b(y));\n }\n /** Create 3d xyz point from 2d xy. (0, 0) => (0, 1, 0), not (0, 0, 1) */\n static fromAffine(ap) {\n const { x, y } = ap;\n return x === 0n && y === 0n ? I : new Point(x, y, 1n);\n }\n toHex(isCompressed) {\n return bytesToHex(this.toBytes(isCompressed));\n }\n static fromPrivateKey(k) {\n return G.multiply(toPrivScalar(k));\n }\n static fromHex(hex) {\n return Point.fromBytes(toU8(hex));\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n toRawBytes(isCompressed) {\n return this.toBytes(isCompressed);\n }\n}\n/** Generator / base point */\nconst G = new Point(Gx, Gy, 1n);\n/** Identity / zero point */\nconst I = new Point(0n, 1n, 0n);\n// Static aliases\nPoint.BASE = G;\nPoint.ZERO = I;\n/** `Q = u1⋅G + u2⋅R`. Verifies Q is not ZERO. Unsafe: non-CT. */\nconst doubleScalarMulUns = (R, u1, u2) => {\n return G.multiply(u1, false).add(R.multiply(u2, false)).assertValidity();\n};\nconst bytesToNumBE = (b) => big('0x' + (bytesToHex(b) || '0'));\nconst sliceBytesNumBE = (b, from, to) => bytesToNumBE(b.subarray(from, to));\nconst B256 = 2n ** 256n; // secp256k1 is weierstrass curve. Equation is x³ + ax + b.\n/** Number to 32b. Must be 0 <= num < B256. validate, pad, to bytes. */\nconst numTo32b = (num) => hexToBytes(padh(arange(num, 0n, B256), L2));\n/** Normalize private key to scalar (bigint). Verifies scalar is in range 1<s<N */\nconst toPrivScalar = (pr) => {\n const num = isBig(pr) ? pr : bytesToNumBE(toU8(pr, L));\n return arange(num, 1n, N, 'private key invalid 3');\n};\n/** For Signature malleability, validates sig.s is bigger than N/2. */\nconst highS = (n) => n > N >> 1n;\n/** Creates 33/65-byte public key from 32-byte private key. */\nconst getPublicKey = (privKey, isCompressed = true) => {\n return G.multiply(toPrivScalar(privKey)).toBytes(isCompressed);\n};\n/** ECDSA Signature class. Supports only compact 64-byte representation, not DER. */\nclass Signature {\n r;\n s;\n recovery;\n constructor(r, s, recovery) {\n this.r = agroup(r); // 1 <= r < N\n this.s = agroup(s); // 1 <= s < N\n if (recovery != null)\n this.recovery = recovery;\n Object.freeze(this);\n }\n /** Create signature from 64b compact (r || s) representation. */\n static fromBytes(b) {\n abytes(b, L2);\n const r = sliceBytesNumBE(b, 0, L);\n const s = sliceBytesNumBE(b, L, L2);\n return new Signature(r, s);\n }\n toBytes() {\n const { r, s } = this;\n return concatBytes(numTo32b(r), numTo32b(s));\n }\n /** Copy signature, with newly added recovery bit. */\n addRecoveryBit(bit) {\n return new Signature(this.r, this.s, bit);\n }\n hasHighS() {\n return highS(this.s);\n }\n toCompactRawBytes() {\n return this.toBytes();\n }\n toCompactHex() {\n return bytesToHex(this.toBytes());\n }\n recoverPublicKey(msg) {\n return recoverPublicKey(this, msg);\n }\n static fromCompact(hex) {\n return Signature.fromBytes(toU8(hex, L2));\n }\n assertValidity() {\n return this;\n }\n normalizeS() {\n const { r, s, recovery } = this;\n return highS(s) ? new Signature(r, modN(-s), recovery) : this;\n }\n}\n/**\n * RFC6979: ensure ECDSA msg is X bytes, convert to BigInt.\n * RFC suggests optional truncating via bits2octets.\n * FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits,\n * which matches bits2int. bits2int can produce res>N.\n */\nconst bits2int = (bytes) => {\n const delta = bytes.length * 8 - 256;\n if (delta > 1024)\n err('msg invalid'); // our CUSTOM check, \"just-in-case\": prohibit long inputs\n const num = bytesToNumBE(bytes);\n return delta > 0 ? num >> big(delta) : num;\n};\n/** int2octets can't be used; pads small msgs with 0: BAD for truncation as per RFC vectors */\nconst bits2int_modN = (bytes) => modN(bits2int(abytes(bytes)));\nconst signOpts = { lowS: true };\nconst veriOpts = { lowS: true };\n// RFC6979 signature generation, preparation step.\nconst prepSig = (msgh, priv, opts = signOpts) => {\n if (['der', 'recovered', 'canonical'].some((k) => k in opts))\n // legacy opts\n err('option not supported');\n let { lowS, extraEntropy } = opts; // generates low-s sigs by default\n if (lowS == null)\n lowS = true; // RFC6979 3.2: we skip step A\n const i2o = numTo32b; // int to octets\n const h1i = bits2int_modN(toU8(msgh)); // msg bigint\n const h1o = i2o(h1i); // msg octets\n const d = toPrivScalar(priv); // validate private key, convert to bigint\n const seed = [i2o(d), h1o]; // Step D of RFC6979 3.2\n /** RFC6979 3.6: additional k' (optional). See {@link ExtraEntropy}. */\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n if (extraEntropy)\n seed.push(extraEntropy === true ? randomBytes(L) : toU8(extraEntropy));\n const m = h1i; // convert msg to bigint\n // Converts signature params into point w r/s, checks result for validity.\n // To transform k => Signature:\n // q = k⋅G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\n const k2sig = (kBytes) => {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n // Important: all mod() calls here must be done over N\n const k = bits2int(kBytes);\n if (!(1n <= k && k < N))\n return; // Check 0 < k < CURVE.n\n const q = G.multiply(k).toAffine(); // q = k⋅G\n const r = modN(q.x); // r = q.x mod n\n if (r === 0n)\n return;\n const ik = invert(k, N); // k^-1 mod n, NOT mod P\n const s = modN(ik * modN(m + modN(d * r))); // s = k^-1(m + rd) mod n\n if (s === 0n)\n return;\n let normS = s; // normalized S\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & 1n); // recovery bit (2 or 3, when q.x > n)\n if (lowS && highS(s)) {\n // if lowS was passed, ensure s is always\n normS = modN(-s); // in the bottom half of CURVE.n\n recovery ^= 1;\n }\n return new Signature(r, normS, recovery); // use normS, not s\n };\n return { seed: concatBytes(...seed), k2sig };\n};\n// HMAC-DRBG from NIST 800-90. Minimal, non-full-spec - used for RFC6979 signatures.\nconst hmacDrbg = (asynchronous) => {\n let v = u8n(L); // Steps B, C of RFC6979 3.2: set hashLen\n let k = u8n(L); // In our case, it's always equal to L\n let i = 0; // Iterations counter, will throw when over max\n const NULL = u8n(0);\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const max = 1000;\n const _e = 'drbg: tried 1000 values';\n if (asynchronous) {\n // asynchronous=true\n // h = hmac(K || V || ...)\n const h = (...b) => etc.hmacSha256Async(k, v, ...b);\n const reseed = async (seed = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = await h(u8of(0x00), seed); // k = hmac(K || V || 0x00 || seed)\n v = await h(); // v = hmac(K || V)\n if (seed.length === 0)\n return;\n k = await h(u8of(0x01), seed); // k = hmac(K || V || 0x01 || seed)\n v = await h(); // v = hmac(K || V)\n };\n // HMAC-DRBG generate() function\n const gen = async () => {\n if (i++ >= max)\n err(_e);\n v = await h(); // v = hmac(K || V)\n return v; // this diverges from noble-curves: we don't allow arbitrary output len!\n };\n // Do not reuse returned fn for more than 1 sig:\n // 1) it's slower (JIT screws up). 2. unsafe (async race conditions)\n return async (seed, pred) => {\n reset();\n await reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(await gen())))\n await reseed(); // test predicate until it returns ok\n reset();\n return res;\n };\n }\n else {\n // asynchronous=false; same as above, but synchronous\n // h = hmac(K || V || ...)\n const h = (...b) => callHash('hmacSha256Sync')(k, v, ...b);\n const reseed = (seed = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8of(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(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n // HMAC-DRBG generate() function\n const gen = () => {\n if (i++ >= max)\n err(_e);\n v = h(); // v = hmac(k || v)\n return v; // this diverges from noble-curves: we don't allow arbitrary output len!\n };\n // Do not reuse returned fn for more than 1 sig:\n // 1) it's slower (JIT screws up). 2. unsafe (async race conditions)\n return (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(); // test predicate until it returns ok\n reset();\n return res;\n };\n }\n};\n/**\n * Sign a msg hash using secp256k1. Async.\n * Follows [SEC1](https://secg.org/sec1-v2.pdf) 4.1.2 & RFC6979.\n * It's suggested to enable hedging ({@link ExtraEntropy}) to prevent fault attacks.\n * @param msgh - message HASH, not message itself e.g. sha256(message)\n * @param priv - private key\n * @param opts - `lowS: true` prevents malleability, `extraEntropy: true` enables hedging\n */\nconst signAsync = async (msgh, priv, opts = signOpts) => {\n // Re-run drbg until k2sig returns ok\n const { seed, k2sig } = prepSig(msgh, priv, opts);\n const sig = await hmacDrbg(true)(seed, k2sig);\n return sig;\n};\n/**\n * Sign a msg hash using secp256k1.\n * Follows [SEC1](https://secg.org/sec1-v2.pdf) 4.1.2 & RFC6979.\n * It's suggested to enable hedging ({@link ExtraEntropy}) to prevent fault attacks.\n * @param msgh - message HASH, not message itself e.g. sha256(message)\n * @param priv - private key\n * @param opts - `lowS: true` prevents malleability, `extraEntropy: true` enables hedging\n * @example\n * const sig = sign(sha256('hello'), privKey, { extraEntropy: true }).toBytes();\n */\nconst sign = (msgh, priv, opts = signOpts) => {\n // Re-run drbg until k2sig returns ok\n const { seed, k2sig } = prepSig(msgh, priv, opts);\n const sig = hmacDrbg(false)(seed, k2sig);\n return sig;\n};\n/**\n * Verify a signature using secp256k1.\n * Follows [SEC1](https://secg.org/sec1-v2.pdf) 4.1.4.\n * Default lowS=true, prevents malleability.\n * @param sig - signature, 64-byte or Signature instance\n * @param msgh - message HASH, not message itself e.g. sha256(message)\n * @param pub - public key\n * @param opts - { lowS: true } is default, prohibits s >= CURVE.n/2 to prevent malleability\n */\nconst verify = (sig, msgh, pub, opts = veriOpts) => {\n let { lowS } = opts;\n if (lowS == null)\n lowS = true;\n if ('strict' in opts)\n err('option not supported');\n let sigg;\n // Previous ver supported DER sigs.\n // We throw error when DER is suspected now.\n const rs = sig && typeof sig === 'object' && 'r' in sig;\n if (!rs && toU8(sig).length !== L2)\n err('signature must be 64 bytes');\n try {\n sigg = rs ? new Signature(sig.r, sig.s) : Signature.fromCompact(sig);\n const h = bits2int_modN(toU8(msgh)); // Truncate hash\n const P = Point.fromBytes(toU8(pub)); // Validate public key\n const { r, s } = sigg;\n if (lowS && highS(s))\n return false; // lowS bans sig.s >= CURVE.n/2\n const is = invert(s, N); // 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 = doubleScalarMulUns(P, u1, u2).toAffine(); // R = u1⋅G + u2⋅P\n // Stop if R is identity / zero point. Check is done inside `doubleScalarMulUns`\n const v = modN(R.x); // R.x must be in N's field, not P's\n return v === r; // mod(R.x, n) == r\n }\n catch (error) {\n return false;\n }\n};\n/**\n * ECDSA public key recovery. Requires msg hash and recovery id.\n * Follows [SEC1](https://secg.org/sec1-v2.pdf) 4.1.6.\n */\nconst recoverPublicKey = (sig, msgh) => {\n const { r, s, recovery } = sig;\n // 0 or 1 recovery id determines sign of \"y\" coordinate.\n // 2 or 3 means q.x was >N.\n if (![0, 1, 2, 3].includes(recovery))\n err('recovery id invalid');\n const h = bits2int_modN(toU8(msgh, L)); // Truncate hash\n const radj = recovery === 2 || recovery === 3 ? r + N : r;\n afield(radj); // ensure q.x is still a field element\n const head = getPrefix(big(recovery)); // head is 0x02 or 0x03\n const Rb = concatBytes(head, numTo32b(radj)); // concat head + r\n const R = Point.fromBytes(Rb);\n const ir = invert(radj, N); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n return doubleScalarMulUns(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n};\n/**\n * Elliptic Curve Diffie-Hellman (ECDH) on secp256k1.\n * Result is **NOT hashed**. Use hash or KDF on it if you need.\n * @param privA private key A\n * @param pubB public key B\n * @param isCompressed 33-byte (true) or 65-byte (false) output\n * @returns public key C\n */\nconst getSharedSecret = (privA, pubB, isCompressed = true) => {\n return Point.fromBytes(toU8(pubB)).multiply(toPrivScalar(privA)).toBytes(isCompressed);\n};\n// FIPS 186 B.4.1 compliant key generation produces private keys with modulo bias being neglible.\n// takes >N+8 bytes, returns (hash mod n-1)+1\nconst hashToPrivateKey = (hash) => {\n hash = toU8(hash);\n if (hash.length < L + 8 || hash.length > 1024)\n err('expected 40-1024b');\n const num = M(bytesToNumBE(hash), N - 1n);\n return numTo32b(num + 1n);\n};\nconst randomPrivateKey = () => hashToPrivateKey(randomBytes(L + 16)); // FIPS 186 B.4.1.\nconst _sha = 'SHA-256';\n/** Math, hex, byte helpers. Not in `utils` because utils share API with noble-curves. */\nconst etc = {\n hexToBytes: hexToBytes,\n bytesToHex: bytesToHex,\n concatBytes: concatBytes,\n bytesToNumberBE: bytesToNumBE,\n numberToBytesBE: numTo32b,\n mod: M,\n invert: invert, // math utilities\n hmacSha256Async: async (key, ...msgs) => {\n const s = subtle();\n const name = 'HMAC';\n const k = await s.importKey('raw', key, { name, hash: { name: _sha } }, false, ['sign']);\n return u8n(await s.sign(name, k, concatBytes(...msgs)));\n },\n hmacSha256Sync: undefined, // For TypeScript. Actual logic is below\n hashToPrivateKey: hashToPrivateKey,\n randomBytes: randomBytes,\n};\n/** Curve-specific utilities for private keys. */\nconst utils = {\n normPrivateKeyToScalar: toPrivScalar,\n isValidPrivateKey: (key) => {\n try {\n return !!toPrivScalar(key);\n }\n catch (e) {\n return false;\n }\n },\n randomPrivateKey: randomPrivateKey,\n precompute: (w = 8, p = G) => {\n p.multiply(3n);\n w;\n return p;\n },\n};\n// ## Precomputes\n// --------------\nconst W = 8; // W is window size\nconst scalarBits = 256;\nconst pwindows = Math.ceil(scalarBits / W) + 1; // 33 for W=8\nconst pwindowSize = 2 ** (W - 1); // 128 for W=8\nconst precompute = () => {\n const points = [];\n let p = G;\n let b = p;\n for (let w = 0; w < pwindows; w++) {\n b = p;\n points.push(b);\n for (let i = 1; i < pwindowSize; i++) {\n b = b.add(p);\n points.push(b);\n } // i=1, bc we skip 0\n p = b.double();\n }\n return points;\n};\nlet Gpows = undefined; // precomputes for base point G\n// const-time negate\nconst ctneg = (cnd, p) => {\n const n = p.negate();\n return cnd ? n : p;\n};\n/**\n * Precomputes give 12x faster getPublicKey(), 10x sign(), 2x verify() by\n * caching multiples of G (base point). Cache is stored in 32MB of RAM.\n * Any time `G.multiply` is done, precomputes are used.\n * Not used for getSharedSecret, which instead multiplies random pubkey `P.multiply`.\n *\n * w-ary non-adjacent form (wNAF) precomputation method is 10% slower than windowed method,\n * but takes 2x less RAM. RAM reduction is possible by utilizing `.subtract`.\n *\n * !! Precomputes can be disabled by commenting-out call of the wNAF() inside Point#multiply().\n */\nconst wNAF = (n) => {\n const comp = Gpows || (Gpows = precompute());\n let p = I;\n let f = G; // f must be G, or could become I in the end\n const pow_2_w = 2 ** W; // 256 for W=8\n const maxNum = pow_2_w; // 256 for W=8\n const mask = big(pow_2_w - 1); // 255 for W=8 == mask 0b11111111\n const shiftBy = big(W); // 8 for W=8\n for (let w = 0; w < pwindows; w++) {\n let wbits = Number(n & mask); // extract W bits.\n n >>= shiftBy; // shift number by W bits.\n if (wbits > pwindowSize) {\n wbits -= maxNum;\n n += 1n;\n } // split if bits > max: +224 => 256-32\n const off = w * pwindowSize;\n const offF = off; // offsets, evaluate both\n const offP = off + Math.abs(wbits) - 1;\n const isEven = w % 2 !== 0; // conditions, evaluate both\n const isNeg = wbits < 0;\n if (wbits === 0) {\n // off == I: can't add it. Adding random offF instead.\n f = f.add(ctneg(isEven, comp[offF])); // bits are 0: add garbage to fake point\n }\n else {\n p = p.add(ctneg(isNeg, comp[offP])); // bits are 1: add to result point\n }\n }\n return { p, f }; // return both real and fake points for JIT\n};\n// !! Remove the export below to easily use in REPL / browser console\nexport { secp256k1_CURVE as CURVE, etc, getPublicKey, getSharedSecret, Point, Point as ProjectivePoint, sign, signAsync, Signature, utils, verify, };\n","/**\n\nSHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.\nDon't use them in a new protocol. What \"weak\" means:\n\n- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.\n- No practical pre-image attacks (only theoretical, 2^123.4)\n- HMAC seems kinda ok: https://datatracker.ietf.org/doc/html/rfc6151\n * @module\n */\nimport { Chi, HashMD, Maj } from \"./_md.js\";\nimport { clean, createHasher, rotl } from \"./utils.js\";\n/** Initial SHA1 state */\nconst SHA1_IV = /* @__PURE__ */ Uint32Array.from([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n// Reusable temporary buffer\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\n/** SHA1 legacy hash class. */\nexport class SHA1 extends HashMD {\n constructor() {\n super(64, 20, 8, false);\n this.A = SHA1_IV[0] | 0;\n this.B = SHA1_IV[1] | 0;\n this.C = SHA1_IV[2] | 0;\n this.D = SHA1_IV[3] | 0;\n this.E = SHA1_IV[4] | 0;\n }\n get() {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n set(A, B, C, D, E) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n }\n else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n }\n else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n }\n else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n this.set(A, B, C, D, E);\n }\n roundClean() {\n clean(SHA1_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */\nexport const sha1 = /* @__PURE__ */ createHasher(() => new SHA1());\n/** Per-round constants */\nconst p32 = /* @__PURE__ */ Math.pow(2, 32);\nconst K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1))));\n/** md5 initial state: same as sha1, but 4 u32 instead of 5. */\nconst MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);\n// Reusable temporary buffer\nconst MD5_W = /* @__PURE__ */ new Uint32Array(16);\n/** MD5 legacy hash class. */\nexport class MD5 extends HashMD {\n constructor() {\n super(64, 16, 8, true);\n this.A = MD5_IV[0] | 0;\n this.B = MD5_IV[1] | 0;\n this.C = MD5_IV[2] | 0;\n this.D = MD5_IV[3] | 0;\n }\n get() {\n const { A, B, C, D } = this;\n return [A, B, C, D];\n }\n set(A, B, C, D) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n MD5_W[i] = view.getUint32(offset, true);\n // Compression function main loop, 64 rounds\n let { A, B, C, D } = this;\n for (let i = 0; i < 64; i++) {\n let F, g, s;\n if (i < 16) {\n F = Chi(B, C, D);\n g = i;\n s = [7, 12, 17, 22];\n }\n else if (i < 32) {\n F = Chi(D, B, C);\n g = (5 * i + 1) % 16;\n s = [5, 9, 14, 20];\n }\n else if (i < 48) {\n F = B ^ C ^ D;\n g = (3 * i + 5) % 16;\n s = [4, 11, 16, 23];\n }\n else {\n F = C ^ (B | ~D);\n g = (7 * i) % 16;\n s = [6, 10, 15, 21];\n }\n F = F + A + K[i] + MD5_W[g];\n A = D;\n D = C;\n C = B;\n B = B + rotl(F, s[i % 4]);\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n this.set(A, B, C, D);\n }\n roundClean() {\n clean(MD5_W);\n }\n destroy() {\n this.set(0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/**\n * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.\n * MD5 architecture is similar to SHA1, with some differences:\n * - Reduced output length: 16 bytes (128 bit) instead of 20\n * - 64 rounds, instead of 80\n * - Little-endian: could be faster, but will require more code\n * - Non-linear index selection: huge speed-up for unroll\n * - Per round constants: more memory accesses, additional speed-up for unroll\n */\nexport const md5 = /* @__PURE__ */ createHasher(() => new MD5());\n// RIPEMD-160\nconst Rho160 = /* @__PURE__ */ Uint8Array.from([\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n]);\nconst Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();\nconst Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();\nconst idxLR = /* @__PURE__ */ (() => {\n const L = [Id160];\n const R = [Pi160];\n const res = [L, R];\n for (let i = 0; i < 4; i++)\n for (let j of res)\n j.push(j[i].map((k) => Rho160[k]));\n return res;\n})();\nconst idxL = /* @__PURE__ */ (() => idxLR[0])();\nconst idxR = /* @__PURE__ */ (() => idxLR[1])();\n// const [idxL, idxR] = idxLR;\nconst shifts160 = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => Uint8Array.from(i));\nconst shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst Kl160 = /* @__PURE__ */ Uint32Array.from([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\nconst Kr160 = /* @__PURE__ */ Uint32Array.from([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// It's called f() in spec.\nfunction ripemd_f(group, x, y, z) {\n if (group === 0)\n return x ^ y ^ z;\n if (group === 1)\n return (x & y) | (~x & z);\n if (group === 2)\n return (x | ~y) ^ z;\n if (group === 3)\n return (x & z) | (y & ~z);\n return x ^ (y | ~z);\n}\n// Reusable temporary buffer\nconst BUF_160 = /* @__PURE__ */ new Uint32Array(16);\nexport class RIPEMD160 extends HashMD {\n constructor() {\n super(64, 20, 8, true);\n this.h0 = 0x67452301 | 0;\n this.h1 = 0xefcdab89 | 0;\n this.h2 = 0x98badcfe | 0;\n this.h3 = 0x10325476 | 0;\n this.h4 = 0xc3d2e1f0 | 0;\n }\n get() {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n set(h0, h1, h2, h3, h4) {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n BUF_160[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);\n }\n roundClean() {\n clean(BUF_160);\n }\n destroy() {\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0);\n }\n}\n/**\n * RIPEMD-160 - a legacy hash function from 1990s.\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\n */\nexport const ripemd160 = /* @__PURE__ */ createHasher(() => new RIPEMD160());\n//# sourceMappingURL=legacy.js.map","// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\nfunction base (ALPHABET) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n const BASE_MAP = new Uint8Array(256)\n for (let j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255\n }\n for (let i = 0; i < ALPHABET.length; i++) {\n const x = ALPHABET.charAt(i)\n const xc = x.charCodeAt(0)\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i\n }\n const BASE = ALPHABET.length\n const LEADER = ALPHABET.charAt(0)\n const FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up\n const iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up\n function encode (source) {\n // eslint-disable-next-line no-empty\n if (source instanceof Uint8Array) { } else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength)\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source)\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n let zeroes = 0\n let length = 0\n let pbegin = 0\n const pend = source.length\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++\n zeroes++\n }\n // Allocate enough space in big-endian base58 representation.\n const size = ((pend - pbegin) * iFACTOR + 1) >>> 0\n const b58 = new Uint8Array(size)\n // Process the bytes.\n while (pbegin !== pend) {\n let carry = source[pbegin]\n // Apply \"b58 = b58 * 256 + ch\".\n let i = 0\n for (let it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0\n b58[it1] = (carry % BASE) >>> 0\n carry = (carry / BASE) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n pbegin++\n }\n // Skip leading zeroes in base58 result.\n let it2 = size - length\n while (it2 !== size && b58[it2] === 0) {\n it2++\n }\n // Translate the result into a string.\n let str = LEADER.repeat(zeroes)\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n let psz = 0\n // Skip and count leading '1's.\n let zeroes = 0\n let length = 0\n while (source[psz] === LEADER) {\n zeroes++\n psz++\n }\n // Allocate enough space in big-endian base256 representation.\n const size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.\n const b256 = new Uint8Array(size)\n // Process the characters.\n while (psz < source.length) {\n // Find code of next character\n const charCode = source.charCodeAt(psz)\n // Base map can not be indexed using char code\n if (charCode > 255) { return }\n // Decode character\n let carry = BASE_MAP[charCode]\n // Invalid character\n if (carry === 255) { return }\n let i = 0\n for (let it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0\n b256[it3] = (carry % 256) >>> 0\n carry = (carry / 256) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n psz++\n }\n // Skip leading zeroes in b256.\n let it4 = size - length\n while (it4 !== size && b256[it4] === 0) {\n it4++\n }\n const vch = new Uint8Array(zeroes + (size - it4))\n let j = zeroes\n while (it4 !== size) {\n vch[j++] = b256[it4++]\n }\n return vch\n }\n function decode (string) {\n const buffer = decodeUnsafe(string)\n if (buffer) { return buffer }\n throw new Error('Non-base' + BASE + ' character')\n }\n return {\n encode,\n decodeUnsafe,\n decode\n }\n}\nexport default base\n","import basex from 'base-x';\nvar ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\nexport default basex(ALPHABET);\n","/**\n * Cryptographic key utilities for Zattera blockchain\n */\n\nimport * as secp256k1 from '@noble/secp256k1';\nimport { sha256 } from '@noble/hashes/sha2';\nimport { ripemd160 } from '@noble/hashes/legacy';\nimport bs58 from 'bs58';\n\nexport class PrivateKey {\n private key: Uint8Array;\n\n constructor(key: Uint8Array) {\n if (key.length !== 32) {\n throw new Error('Private key must be 32 bytes');\n }\n this.key = key;\n }\n\n /**\n * Create PrivateKey from WIF (Wallet Import Format) string\n */\n static fromWif(wif: string): PrivateKey {\n const decoded = bs58.decode(wif);\n\n // Check version byte (0x80)\n if (decoded[0] !== 0x80) {\n throw new Error('Invalid WIF version byte');\n }\n\n // Extract private key (remove version byte and checksum)\n const privateKey = decoded.slice(1, 33);\n const checksum = decoded.slice(33, 37);\n\n // Verify checksum\n const hash1 = sha256(decoded.slice(0, 33));\n const hash2 = sha256(hash1);\n const expectedChecksum = hash2.slice(0, 4);\n\n if (!arraysEqual(checksum, expectedChecksum)) {\n throw new Error('Invalid WIF checksum');\n }\n\n return new PrivateKey(privateKey);\n }\n\n /**\n * Create PrivateKey from seed string\n */\n static fromSeed(seed: string): PrivateKey {\n const hash = sha256(new TextEncoder().encode(seed));\n return new PrivateKey(hash);\n }\n\n /**\n * Generate PrivateKey from account name, password and role\n */\n static fromLogin(\n accountName: string,\n password: string,\n role: string = 'active'\n ): PrivateKey {\n const seed = accountName + role + password;\n const normalized = seed.trim().replace(/\\s+/g, ' ');\n return PrivateKey.fromSeed(normalized);\n }\n\n /**\n * Convert to WIF format\n */\n toWif(): string {\n // Add version byte (0x80)\n const versioned = new Uint8Array(33);\n versioned[0] = 0x80;\n versioned.set(this.key, 1);\n\n // Calculate checksum\n const hash1 = sha256(versioned);\n const hash2 = sha256(hash1);\n const checksum = hash2.slice(0, 4);\n\n // Concatenate and encode\n const result = new Uint8Array(37);\n result.set(versioned);\n result.set(checksum, 33);\n\n return bs58.encode(result);\n }\n\n /**\n * Get the public key\n */\n toPublic(): PublicKey {\n const publicKeyBytes = secp256k1.getPublicKey(this.key, true);\n return new PublicKey(publicKeyBytes);\n }\n\n /**\n * Get raw bytes\n */\n toBytes(): Uint8Array {\n return this.key;\n }\n\n /**\n * Sign a message hash\n * @param messageHash The message hash to sign\n * @returns Signature with recovery parameter\n */\n async sign(messageHash: Uint8Array): Promise<Signature> {\n // signAsync returns RecoveredSignature which has r, s, and recovery properties\n const sig = await secp256k1.signAsync(messageHash, this.key, {\n lowS: true, // Enforce canonical signatures (prevents malleability)\n });\n\n return new Signature({ signature: sig.toCompactRawBytes(), recovery: sig.recovery ?? 0 });\n }\n\n /**\n * Get shared secret with a public key (for ECIES encryption)\n * @param publicKey The public key to generate shared secret with\n * @returns Shared secret as Uint8Array\n */\n getSharedSecret(publicKey: PublicKey): Uint8Array {\n const sharedPoint = secp256k1.getSharedSecret(this.key, publicKey.toBytes(), true);\n // Remove the prefix byte (0x02 or 0x03) to get the 32-byte shared secret\n return sharedPoint.slice(1);\n }\n\n /**\n * Derive child key from offset (hierarchical key derivation)\n * @param offset Offset string for derivation\n * @returns New derived PrivateKey\n */\n child(offset: string): PrivateKey {\n const offsetHash = sha256(new TextEncoder().encode(offset));\n const offsetBigInt = BigInt('0x' + Array.from(offsetHash).map(b => b.toString(16).padStart(2, '0')).join(''));\n const keyBigInt = BigInt('0x' + Array.from(this.key).map(b => b.toString(16).padStart(2, '0')).join(''));\n\n // secp256k1 curve order\n const n = BigInt('0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141');\n const childKeyBigInt = (keyBigInt + offsetBigInt) % n;\n\n // Convert back to 32-byte array\n const childKeyHex = childKeyBigInt.toString(16).padStart(64, '0');\n const childKeyBytes = new Uint8Array(32);\n for (let i = 0; i < 32; i++) {\n childKeyBytes[i] = parseInt(childKeyHex.slice(i * 2, i * 2 + 2), 16);\n }\n\n return new PrivateKey(childKeyBytes);\n }\n}\n\nexport class PublicKey {\n private key: Uint8Array;\n\n constructor(key: Uint8Array) {\n if (key.length !== 33) {\n throw new Error('Compressed public key must be 33 bytes');\n }\n this.key = key;\n }\n\n /**\n * Create PublicKey from string (e.g., \"ZTR...\")\n */\n static fromString(publicKeyString: string, prefix: string = 'ZTR'): PublicKey {\n if (!publicKeyString.startsWith(prefix)) {\n throw new Error(`Public key must start with ${prefix}`);\n }\n\n const keyString = publicKeyString.substring(prefix.length);\n const decoded = bs58.decode(keyString);\n\n // Extract public key (remove checksum)\n const publicKey = decoded.slice(0, 33);\n const checksum = decoded.slice(33);\n\n // Verify checksum\n const hash = ripemd160(publicKey);\n const expectedChecksum = hash.slice(0, 4);\n\n if (!arraysEqual(checksum, expectedChecksum)) {\n throw new Error('Invalid public key checksum');\n }\n\n return new PublicKey(publicKey);\n }\n\n /**\n * Convert to string format (e.g., \"ZTR...\")\n */\n toString(prefix: string = 'ZTR'): string {\n const checksum = ripemd160(this.key).slice(0, 4);\n const result = new Uint8Array(37);\n result.set(this.key);\n result.set(checksum, 33);\n\n return prefix + bs58.encode(result);\n }\n\n /**\n * Get raw bytes\n */\n toBytes(): Uint8Array {\n return this.key;\n }\n\n /**\n * Verify a signature\n */\n async verify(messageHash: Uint8Array, signature: Signature): Promise<boolean> {\n try {\n return secp256k1.verify(signature.toCompact(), messageHash, this.key);\n } catch {\n return false;\n }\n }\n\n /**\n * Derive child key from offset (hierarchical key derivation)\n * Note: This is not implemented for public keys alone, derive from private key instead\n * @param _offset Offset string for derivation (unused)\n * @returns Never - throws error\n */\n child(_offset: string): PublicKey {\n // This would require point addition which is complex\n // For now, we'll derive from private key if available\n throw new Error('PublicKey.child() requires private key derivation');\n }\n}\n\nexport class Signature {\n private sig: Uint8Array;\n private recovery: number;\n\n constructor(sig: Uint8Array | { signature: Uint8Array; recovery: number }) {\n if (sig instanceof Uint8Array) {\n // Compact format: 65 bytes (recovery + r + s)\n if (sig.length !== 65) {\n throw new Error('Signature must be 65 bytes');\n }\n const recoveryByte = sig[0];\n if (recoveryByte === undefined) {\n throw new Error('Invalid signature: missing recovery byte');\n }\n this.recovery = recoveryByte - 27;\n this.sig = sig.slice(1);\n } else {\n // From secp256k1.signAsync result\n this.sig = sig.signature;\n this.recovery = sig.recovery ?? 0;\n }\n }\n\n /**\n * Get compact signature (65 bytes: recovery + r + s)\n */\n toCompact(): Uint8Array {\n return this.sig;\n }\n\n /**\n * Get full signature with recovery parameter (65 bytes)\n */\n toBuffer(): Uint8Array {\n const result = new Uint8Array(65);\n result[0] = this.recovery + 27;\n result.set(this.sig, 1);\n return result;\n }\n\n /**\n * Recover public key from signature and message hash\n */\n async recoverPublicKey(messageHash: Uint8Array): Promise<PublicKey> {\n // Create a Signature instance from the compact bytes\n const sig = secp256k1.Signature.fromCompact(this.sig);\n\n // Add recovery bit\n const recoveredSig = sig.addRecoveryBit(this.recovery);\n\n // Recover the public key point\n const point = recoveredSig.recoverPublicKey(messageHash);\n\n // Convert to compressed bytes\n const publicKeyBytes = point.toRawBytes(true);\n\n return new PublicKey(publicKeyBytes);\n }\n}\n\n/**\n * Helper function to compare two Uint8Arrays\n */\nfunction arraysEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\n/**\n * Generate all account keys from account name and password\n */\nexport function generateKeys(\n accountName: string,\n password: string,\n roles: string[] = ['owner', 'active', 'posting', 'memo']\n): Record<string, { private: string; public: string }> {\n const keys: Record<string, { private: string; public: string }> = {};\n\n for (const role of roles) {\n const privateKey = PrivateKey.fromLogin(accountName, password, role);\n const publicKey = privateKey.toPublic();\n\n keys[role] = {\n private: privateKey.toWif(),\n public: publicKey.toString(),\n };\n }\n\n return keys;\n}\n\n/**\n * Check if a string is a valid WIF private key\n */\nexport function isWif(wif: string): boolean {\n try {\n PrivateKey.fromWif(wif);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a string is a valid public key\n */\nexport function isPublicKey(publicKey: string, prefix: string = 'ZTR'): boolean {\n try {\n PublicKey.fromString(publicKey, prefix);\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * Transaction serialization for Zattera blockchain\n */\n\nimport type { Transaction, Operation } from '../types/index.js';\n\n/**\n * Simple binary serializer for transactions\n */\nexport class TransactionSerializer {\n private buffer: number[] = [];\n\n /**\n * Write a uint8 (1 byte)\n */\n writeUInt8(value: number): void {\n this.buffer.push(value & 0xff);\n }\n\n /**\n * Write a uint16 (2 bytes, little-endian)\n */\n writeUInt16(value: number): void {\n this.buffer.push(value & 0xff);\n this.buffer.push((value >> 8) & 0xff);\n }\n\n /**\n * Write a uint32 (4 bytes, little-endian)\n */\n writeUInt32(value: number): void {\n this.buffer.push(value & 0xff);\n this.buffer.push((value >> 8) & 0xff);\n this.buffer.push((value >> 16) & 0xff);\n this.buffer.push((value >> 24) & 0xff);\n }\n\n /**\n * Write a uint64 (8 bytes, little-endian)\n */\n writeUInt64(value: number | bigint): void {\n const bigValue = typeof value === 'number' ? BigInt(value) : value;\n for (let i = 0; i < 8; i++) {\n this.buffer.push(Number((bigValue >> BigInt(i * 8)) & BigInt(0xff)));\n }\n }\n\n /**\n * Write variable-length integer\n */\n writeVarint32(value: number): void {\n while (value >= 0x80) {\n this.buffer.push((value & 0x7f) | 0x80);\n value >>= 7;\n }\n this.buffer.push(value & 0x7f);\n }\n\n /**\n * Write a string\n */\n writeString(value: string): void {\n const bytes = new TextEncoder().encode(value);\n this.writeVarint32(bytes.length);\n for (const byte of bytes) {\n this.buffer.push(byte);\n }\n }\n\n /**\n * Write bytes\n */\n writeBytes(bytes: Uint8Array): void {\n for (const byte of bytes) {\n this.buffer.push(byte);\n }\n }\n\n /**\n * Write array with length prefix\n */\n writeArray<T>(arr: T[], writeItem: (item: T) => void): void {\n this.writeVarint32(arr.length);\n for (const item of arr) {\n writeItem(item);\n }\n }\n\n /**\n * Get the serialized buffer\n */\n toBuffer(): Uint8Array {\n return new Uint8Array(this.buffer);\n }\n}\n\n/**\n * Serialize a transaction (without signatures)\n */\nexport function serializeTransaction(tx: Transaction): Uint8Array {\n const serializer = new TransactionSerializer();\n\n // ref_block_num (uint16)\n serializer.writeUInt16(tx.ref_block_num);\n\n // ref_block_prefix (uint32)\n serializer.writeUInt32(tx.ref_block_prefix);\n\n // expiration (uint32 - seconds since epoch)\n const expirationDate = new Date(tx.expiration);\n const expirationSeconds = Math.floor(expirationDate.getTime() / 1000);\n serializer.writeUInt32(expirationSeconds);\n\n // operations array\n serializer.writeArray(tx.operations, (op: Operation) => {\n serializeOperation(serializer, op);\n });\n\n // extensions array (usually empty)\n serializer.writeArray(tx.extensions, (ext: unknown) => {\n // For now, we'll serialize extensions as opaque data\n // In practice, this is usually an empty array\n if (typeof ext === 'object' && ext !== null) {\n serializer.writeString(JSON.stringify(ext));\n }\n });\n\n return serializer.toBuffer();\n}\n\n/**\n * Serialize an operation\n * Operations are in format: [operation_type_id, operation_data]\n */\nfunction serializeOperation(serializer: TransactionSerializer, operation: Operation): void {\n if (!Array.isArray(operation) || operation.length !== 2) {\n throw new Error('Invalid operation format');\n }\n\n const [opType, opData] = operation;\n\n // Write operation type (assuming it's a string or number)\n if (typeof opType === 'number') {\n serializer.writeVarint32(opType);\n } else if (typeof opType === 'string') {\n // Map operation names to IDs (this would need to be complete)\n const opId = getOperationId(opType);\n serializer.writeVarint32(opId);\n }\n\n // Serialize operation data\n // This is a simplified version - full implementation would need\n // specific serialization logic for each operation type\n serializeOperationData(serializer, opData);\n}\n\n/**\n * Get operation ID from operation name\n * This is a simplified mapping - would need to be complete\n */\nfunction getOperationId(opName: string): number {\n const operationIds: Record<string, number> = {\n vote: 0,\n comment: 1,\n transfer: 2,\n transfer_to_vesting: 3,\n withdraw_vesting: 4,\n limit_order_create: 5,\n limit_order_cancel: 6,\n feed_publish: 7,\n convert: 8,\n account_create: 9,\n account_update: 10,\n witness_update: 11,\n account_witness_vote: 12,\n account_witness_proxy: 13,\n // ... more operations\n };\n\n return operationIds[opName] ?? -1;\n}\n\n/**\n * Serialize operation data\n * This is a simplified version that handles basic types\n */\nfunction serializeOperationData(serializer: TransactionSerializer, data: unknown): void {\n if (data === null || data === undefined) {\n return;\n }\n\n if (typeof data === 'string') {\n serializer.writeString(data);\n } else if (typeof data === 'number') {\n serializer.writeUInt32(data);\n } else if (typeof data === 'boolean') {\n serializer.writeUInt8(data ? 1 : 0);\n } else if (typeof data === 'object') {\n // For objects, serialize each field\n // This would need proper field ordering based on operation type\n for (const value of Object.values(data)) {\n serializeOperationData(serializer, value);\n }\n }\n}\n\n/**\n * Serialize a signed transaction (with signatures)\n */\nexport function serializeSignedTransaction(tx: Transaction & { signatures?: Uint8Array[] }): Uint8Array {\n const serializer = new TransactionSerializer();\n\n // Serialize the transaction part\n const txBytes = serializeTransaction(tx);\n serializer.writeBytes(txBytes);\n\n // Serialize signatures\n if (tx.signatures) {\n serializer.writeArray(tx.signatures, (sig: Uint8Array) => {\n serializer.writeBytes(sig);\n });\n } else {\n serializer.writeVarint32(0); // Empty signatures array\n }\n\n return serializer.toBuffer();\n}\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is boolean. */\nexport function abool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\n/** Asserts something is positive integer. */\nexport function anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(value, length, title = '') {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function 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}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\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 * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// 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 * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(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// Used in micro\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n return BigInt(hex === '' ? '0' : '0x' + hex); // Big Endian\n}\n// Used in ff1\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\n// Used in micro, ff1\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n/**\n * Converts string to bytes using UTF8 encoding.\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/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Checks if two U8A use same underlying buffer and overlaps.\n * This is invalid and can corrupt data.\n */\nexport function overlapBytes(a, b) {\n return (a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy\n a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end\n b.byteOffset < a.byteOffset + a.byteLength // b starts before a end\n );\n}\n/**\n * If input and output overlap and input starts before output, we will overwrite end of input before\n * we start processing it, so this is not supported for most ciphers (except chacha/salse, which designed with this)\n */\nexport function complexOverlapBytes(input, output) {\n // This is very cursed. It works somehow, but I'm completely unsure,\n // reasoning about overlapping aligned windows is very hard.\n if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)\n throw new Error('complex overlap of input and output is not supported');\n}\n/**\n * 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}\nexport function checkOpts(defaults, opts) {\n if (opts == null || typeof opts !== 'object')\n throw new Error('options must be defined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** Compares 2 uint8array-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 * Wraps a cipher: validates args, ensures encrypt() can only be called once.\n * @__NO_SIDE_EFFECTS__\n */\nexport const wrapCipher = (params, constructor) => {\n function wrappedCipher(key, ...args) {\n // Validate key\n abytes(key, undefined, 'key');\n // Big-Endian hardware is rare. Just in case someone still decides to run ciphers:\n if (!isLE)\n throw new Error('Non little-endian hardware is not yet supported');\n // Validate nonce if nonceLength is present\n if (params.nonceLength !== undefined) {\n const nonce = args[0];\n abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, 'nonce');\n }\n // Validate AAD if tagLength present\n const tagl = params.tagLength;\n if (tagl && args[1] !== undefined)\n abytes(args[1], undefined, 'AAD');\n const cipher = constructor(key, ...args);\n const checkOutput = (fnLength, output) => {\n if (output !== undefined) {\n if (fnLength !== 2)\n throw new Error('cipher output not supported');\n abytes(output, undefined, 'output');\n }\n };\n // Create wrapped cipher with validation and single-use encryption\n let called = false;\n const wrCipher = {\n encrypt(data, output) {\n if (called)\n throw new Error('cannot encrypt() twice with same key + nonce');\n called = true;\n abytes(data);\n checkOutput(cipher.encrypt.length, output);\n return cipher.encrypt(data, output);\n },\n decrypt(data, output) {\n abytes(data);\n if (tagl && data.length < tagl)\n throw new Error('\"ciphertext\" expected length bigger than tagLength=' + tagl);\n checkOutput(cipher.decrypt.length, output);\n return cipher.decrypt(data, output);\n },\n };\n return wrCipher;\n }\n Object.assign(wrappedCipher, params);\n return wrappedCipher;\n};\n/**\n * By default, returns u8a of length.\n * When out is available, it checks it for validity and uses it.\n */\nexport function getOutput(expectedLength, out, onlyAligned = true) {\n if (out === undefined)\n return new Uint8Array(expectedLength);\n if (out.length !== expectedLength)\n throw new Error('\"output\" expected Uint8Array of length ' + expectedLength + ', got: ' + out.length);\n if (onlyAligned && !isAligned32(out))\n throw new Error('invalid output, must be aligned');\n return out;\n}\nexport function u64Lengths(dataLength, aadLength, isLE) {\n abool(isLE);\n const num = new Uint8Array(16);\n const view = createView(num);\n view.setBigUint64(0, BigInt(aadLength), isLE);\n view.setBigUint64(8, BigInt(dataLength), isLE);\n return num;\n}\n// Is byte array aligned to 4 byte offset (u32)?\nexport function isAligned32(bytes) {\n return bytes.byteOffset % 4 === 0;\n}\n// copy bytes to new u8a (aligned). Because Buffer.slice is broken.\nexport function copyBytes(bytes) {\n return Uint8Array.from(bytes);\n}\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Uses CSPRG for nonce, nonce injected in ciphertext.\n * For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and\n * prepended to encrypted ciphertext. For `decrypt`, first `nonceBytes` of ciphertext\n * are treated as nonce.\n *\n * NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha\n * should be limited to `2**23` (8M) messages to get a collision chance of `2**-50`. Stretching to * `2**32` (4B) messages, chance would become `2**-33` - still negligible, but creeping up.\n * @example\n * const gcm = managedNonce(aes.gcm);\n * const ciphr = gcm(key).encrypt(data);\n * const plain = gcm(key).decrypt(ciph);\n */\nexport function managedNonce(fn, randomBytes_ = randomBytes) {\n const { nonceLength } = fn;\n anumber(nonceLength);\n const addNonce = (nonce, ciphertext) => {\n const out = concatBytes(nonce, ciphertext);\n ciphertext.fill(0);\n return out;\n };\n // NOTE: we cannot support DST here, it would be mistake:\n // - we don't know how much dst length cipher requires\n // - nonce may unalign dst and break everything\n // - we create new u8a anyway (concatBytes)\n // - previously we passed all args to cipher, but that was mistake!\n return ((key, ...args) => ({\n encrypt(plaintext) {\n abytes(plaintext);\n const nonce = randomBytes_(nonceLength);\n const encrypted = fn(key, nonce, ...args).encrypt(plaintext);\n // @ts-ignore\n if (encrypted instanceof Promise)\n return encrypted.then((ct) => addNonce(nonce, ct));\n return addNonce(nonce, encrypted);\n },\n decrypt(ciphertext) {\n abytes(ciphertext);\n const nonce = ciphertext.subarray(0, nonceLength);\n const decrypted = ciphertext.subarray(nonceLength);\n return fn(key, nonce, ...args).decrypt(decrypted);\n },\n }));\n}\n//# sourceMappingURL=utils.js.map","/**\n * [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard)\n * a.k.a. Advanced Encryption Standard\n * is a variant of Rijndael block cipher, standardized by NIST in 2001.\n * We provide the fastest available pure JS implementation.\n *\n * `cipher = encrypt(block, key)`\n *\n * Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:\n * 1. **S-box**, table substitution\n * 2. **Shift rows**, cyclic shift left of all rows of data array\n * 3. **Mix columns**, multiplying every column by fixed polynomial\n * 4. **Add round key**, round_key xor i-th column of array\n *\n * Check out [FIPS-197](https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf),\n * [NIST 800-38G](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf)\n * and [original proposal](https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf)\n * @module\n */\nimport { ghash, polyval } from \"./_polyval.js\";\n// prettier-ignore\nimport { abytes, anumber, clean, complexOverlapBytes, concatBytes, copyBytes, createView, equalBytes, getOutput, isAligned32, overlapBytes, u32, u64Lengths, u8, wrapCipher } from \"./utils.js\";\nconst BLOCK_SIZE = 16;\nconst BLOCK_SIZE32 = 4;\nconst EMPTY_BLOCK = /* @__PURE__ */ new Uint8Array(BLOCK_SIZE);\nconst ONE_BLOCK = /* @__PURE__ */ Uint8Array.from([\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,\n]);\nconst POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8\nfunction validateKeyLength(key) {\n if (![16, 24, 32].includes(key.length))\n throw new Error('\"aes key\" expected Uint8Array of length 16/24/32, got length=' + key.length);\n}\n// TODO: remove multiplication, binary ops only\nfunction mul2(n) {\n return (n << 1) ^ (POLY & -(n >> 7));\n}\nfunction mul(a, b) {\n let res = 0;\n for (; b > 0; b >>= 1) {\n // Montgomery ladder\n res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).\n a = mul2(a); // a = 2*a\n }\n return res;\n}\n// Increments bigint with wrap around\n// NOTE: we cannot use u32 here since it may overflow on carry!\nconst incBytes = (data, isLE, carry = 1) => {\n if (!Number.isSafeInteger(carry))\n throw new Error('incBytes: wrong carry ' + carry);\n abytes(data);\n for (let i = 0; i < data.length; i++) {\n const pos = !isLE ? data.length - 1 - i : i;\n carry = (carry + (data[pos] & 0xff)) | 0;\n data[pos] = carry & 0xff;\n carry >>>= 8;\n }\n};\n// AES S-box is generated using finite field inversion,\n// an affine transform, and xor of a constant 0x63.\nconst sbox = /* @__PURE__ */ (() => {\n const t = new Uint8Array(256);\n for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))\n t[i] = x;\n const box = new Uint8Array(256);\n box[0] = 0x63; // first elm\n for (let i = 0; i < 255; i++) {\n let x = t[255 - i];\n x |= x << 8;\n box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;\n }\n clean(t);\n return box;\n})();\n// Inverted S-box\nconst invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));\n// Rotate u32 by 8\nconst rotr32_8 = (n) => (n << 24) | (n >>> 8);\nconst rotl32_8 = (n) => (n << 8) | (n >>> 24);\n// The byte swap operation for uint32 (LE<->BE)\nconst byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:\n// - LE instead of BE\n// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;\n// so index is u16, instead of u8. This speeds up things, unexpectedly\nfunction genTtable(sbox, fn) {\n if (sbox.length !== 256)\n throw new Error('Wrong sbox length');\n const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));\n const T1 = T0.map(rotl32_8);\n const T2 = T1.map(rotl32_8);\n const T3 = T2.map(rotl32_8);\n const T01 = new Uint32Array(256 * 256);\n const T23 = new Uint32Array(256 * 256);\n const sbox2 = new Uint16Array(256 * 256);\n for (let i = 0; i < 256; i++) {\n for (let j = 0; j < 256; j++) {\n const idx = i * 256 + j;\n T01[idx] = T0[i] ^ T1[j];\n T23[idx] = T2[i] ^ T3[j];\n sbox2[idx] = (sbox[i] << 8) | sbox[j];\n }\n }\n return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };\n}\nconst tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2));\nconst tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14));\nconst xPowers = /* @__PURE__ */ (() => {\n const p = new Uint8Array(16);\n for (let i = 0, x = 1; i < 16; i++, x = mul2(x))\n p[i] = x;\n return p;\n})();\n/** Key expansion used in CTR. */\nfunction expandKeyLE(key) {\n abytes(key);\n const len = key.length;\n validateKeyLength(key);\n const { sbox2 } = tableEncoding;\n const toClean = [];\n if (!isAligned32(key))\n toClean.push((key = copyBytes(key)));\n const k32 = u32(key);\n const Nk = k32.length;\n const subByte = (n) => applySbox(sbox2, n, n, n, n);\n const xk = new Uint32Array(len + 28); // expanded key\n xk.set(k32);\n // 4.3.1 Key expansion\n for (let i = Nk; i < xk.length; i++) {\n let t = xk[i - 1];\n if (i % Nk === 0)\n t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];\n else if (Nk > 6 && i % Nk === 4)\n t = subByte(t);\n xk[i] = xk[i - Nk] ^ t;\n }\n clean(...toClean);\n return xk;\n}\nfunction expandKeyDecLE(key) {\n const encKey = expandKeyLE(key);\n const xk = encKey.slice();\n const Nk = encKey.length;\n const { sbox2 } = tableEncoding;\n const { T0, T1, T2, T3 } = tableDecoding;\n // Inverse key by chunks of 4 (rounds)\n for (let i = 0; i < Nk; i += 4) {\n for (let j = 0; j < 4; j++)\n xk[i + j] = encKey[Nk - i - 4 + j];\n }\n clean(encKey);\n // apply InvMixColumn except first & last round\n for (let i = 4; i < Nk - 4; i++) {\n const x = xk[i];\n const w = applySbox(sbox2, x, x, x, x);\n xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];\n }\n return xk;\n}\n// Apply tables\nfunction apply0123(T01, T23, s0, s1, s2, s3) {\n return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^\n T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]);\n}\nfunction applySbox(sbox2, s0, s1, s2, s3) {\n return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] |\n (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16));\n}\nfunction encrypt(xk, s0, s1, s2, s3) {\n const { sbox2, T01, T23 } = tableEncoding;\n let k = 0;\n ((s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]));\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);\n ((s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3));\n }\n // last round (without mixcolumns, so using SBOX2 table)\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different\nfunction decrypt(xk, s0, s1, s2, s3) {\n const { sbox2, T01, T23 } = tableDecoding;\n let k = 0;\n ((s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]));\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);\n ((s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3));\n }\n // Last round\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n// TODO: investigate merging with ctr32\nfunction ctrCounter(xk, nonce, src, dst) {\n abytes(nonce, BLOCK_SIZE, 'nonce');\n abytes(src);\n const srcLen = src.length;\n dst = getOutput(srcLen, dst);\n complexOverlapBytes(src, dst);\n const ctr = nonce;\n const c32 = u32(ctr);\n // Fill block (empty, ctr=0)\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n const src32 = u32(src);\n const dst32 = u32(dst);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n incBytes(ctr, false, 1); // Full 128 bit counter with wrap around\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than block)\n // It's possible to handle > u32 fast, but is it worth it?\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(b32);\n }\n return dst;\n}\n// AES CTR with overflowing 32 bit counter\n// It's possible to do 32le significantly simpler (and probably faster) by using u32.\n// But, we need both, and perf bottleneck is in ghash anyway.\nfunction ctr32(xk, isLE, nonce, src, dst) {\n abytes(nonce, BLOCK_SIZE, 'nonce');\n abytes(src);\n dst = getOutput(src.length, dst);\n const ctr = nonce; // write new value to nonce, so it can be re-used\n const c32 = u32(ctr);\n const view = createView(ctr);\n const src32 = u32(src);\n const dst32 = u32(dst);\n const ctrPos = isLE ? 0 : 12;\n const srcLen = src.length;\n // Fill block (empty, ctr=0)\n let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n ctrNum = (ctrNum + 1) >>> 0; // u32 wrap\n view.setUint32(ctrPos, ctrNum, isLE);\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than a block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(b32);\n }\n return dst;\n}\n/**\n * **CTR** (Counter Mode): Turns a block cipher into a stream cipher using a counter and IV (nonce).\n * Efficient and parallelizable. Requires a unique nonce per encryption. Unauthenticated: needs MAC.\n */\nexport const ctr = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aesctr(key, nonce) {\n function processCtr(buf, dst) {\n abytes(buf);\n if (dst !== undefined) {\n abytes(dst);\n if (!isAligned32(dst))\n throw new Error('unaligned destination');\n }\n const xk = expandKeyLE(key);\n const n = copyBytes(nonce); // align + avoid changing\n const toClean = [xk, n];\n if (!isAligned32(buf))\n toClean.push((buf = copyBytes(buf)));\n const out = ctrCounter(xk, n, buf, dst);\n clean(...toClean);\n return out;\n }\n return {\n encrypt: (plaintext, dst) => processCtr(plaintext, dst),\n decrypt: (ciphertext, dst) => processCtr(ciphertext, dst),\n };\n});\nfunction validateBlockDecrypt(data) {\n abytes(data);\n if (data.length % BLOCK_SIZE !== 0) {\n throw new Error('aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size ' + BLOCK_SIZE);\n }\n}\nfunction validateBlockEncrypt(plaintext, pcks5, dst) {\n abytes(plaintext);\n let outLen = plaintext.length;\n const remaining = outLen % BLOCK_SIZE;\n if (!pcks5 && remaining !== 0)\n throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');\n if (!isAligned32(plaintext))\n plaintext = copyBytes(plaintext);\n const b = u32(plaintext);\n if (pcks5) {\n let left = BLOCK_SIZE - remaining;\n if (!left)\n left = BLOCK_SIZE; // if no bytes left, create empty padding block\n outLen = outLen + left;\n }\n dst = getOutput(outLen, dst);\n complexOverlapBytes(plaintext, dst);\n const o = u32(dst);\n return { b, o, out: dst };\n}\nfunction validatePCKS(data, pcks5) {\n if (!pcks5)\n return data;\n const len = data.length;\n if (!len)\n throw new Error('aes/pcks5: empty ciphertext not allowed');\n const lastByte = data[len - 1];\n if (lastByte <= 0 || lastByte > 16)\n throw new Error('aes/pcks5: wrong padding');\n const out = data.subarray(0, -lastByte);\n for (let i = 0; i < lastByte; i++)\n if (data[len - i - 1] !== lastByte)\n throw new Error('aes/pcks5: wrong padding');\n return out;\n}\nfunction padPCKS(left) {\n const tmp = new Uint8Array(16);\n const tmp32 = u32(tmp);\n tmp.set(left);\n const paddingByte = BLOCK_SIZE - left.length;\n for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++)\n tmp[i] = paddingByte;\n return tmp32;\n}\n/**\n * **ECB** (Electronic Codebook): Deterministic encryption; identical plaintext blocks yield\n * identical ciphertexts. Not secure due to pattern leakage.\n * See [AES Penguin](https://words.filippo.io/the-ecb-penguin/).\n */\nexport const ecb = /* @__PURE__ */ wrapCipher({ blockSize: 16 }, function aesecb(key, opts = {}) {\n const pcks5 = !opts.disablePadding;\n return {\n encrypt(plaintext, dst) {\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n const xk = expandKeyLE(key);\n let i = 0;\n for (; i + 4 <= b.length;) {\n const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);\n ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));\n }\n clean(xk);\n return _out;\n },\n decrypt(ciphertext, dst) {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n dst = getOutput(ciphertext.length, dst);\n const toClean = [xk];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n complexOverlapBytes(ciphertext, dst);\n const b = u32(ciphertext);\n const o = u32(dst);\n for (let i = 0; i + 4 <= b.length;) {\n const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));\n }\n clean(...toClean);\n return validatePCKS(dst, pcks5);\n },\n };\n});\n/**\n * **CBC** (Cipher Block Chaining): Each plaintext block is XORed with the\n * previous block of ciphertext before encryption.\n * Hard to use: requires proper padding and an IV. Unauthenticated: needs MAC.\n */\nexport const cbc = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescbc(key, iv, opts = {}) {\n const pcks5 = !opts.disablePadding;\n return {\n encrypt(plaintext, dst) {\n const xk = expandKeyLE(key);\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n let _iv = iv;\n const toClean = [xk];\n if (!isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n const n32 = u32(_iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n let i = 0;\n for (; i + 4 <= b.length;) {\n ((s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]));\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n ((s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]));\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));\n }\n clean(...toClean);\n return _out;\n },\n decrypt(ciphertext, dst) {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n let _iv = iv;\n const toClean = [xk];\n if (!isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n const n32 = u32(_iv);\n dst = getOutput(ciphertext.length, dst);\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n complexOverlapBytes(ciphertext, dst);\n const b = u32(ciphertext);\n const o = u32(dst);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= b.length;) {\n // prettier-ignore\n const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;\n ((s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]));\n const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);\n ((o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3));\n }\n clean(...toClean);\n return validatePCKS(dst, pcks5);\n },\n };\n});\n/**\n * CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output.\n * Unauthenticated: needs MAC.\n */\nexport const cfb = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescfb(key, iv) {\n function processCfb(src, isEncrypt, dst) {\n abytes(src);\n const srcLen = src.length;\n dst = getOutput(srcLen, dst);\n if (overlapBytes(src, dst))\n throw new Error('overlapping src and dst not supported.');\n const xk = expandKeyLE(key);\n let _iv = iv;\n const toClean = [xk];\n if (!isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n if (!isAligned32(src))\n toClean.push((src = copyBytes(src)));\n const src32 = u32(src);\n const dst32 = u32(dst);\n const next32 = isEncrypt ? dst32 : src32;\n const n32 = u32(_iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= src32.length;) {\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3);\n dst32[i + 0] = src32[i + 0] ^ e0;\n dst32[i + 1] = src32[i + 1] ^ e1;\n dst32[i + 2] = src32[i + 2] ^ e2;\n dst32[i + 3] = src32[i + 3] ^ e3;\n ((s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]));\n }\n // leftovers (less than block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n const buf = u8(new Uint32Array([s0, s1, s2, s3]));\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(buf);\n }\n clean(...toClean);\n return dst;\n }\n return {\n encrypt: (plaintext, dst) => processCfb(plaintext, true, dst),\n decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst),\n };\n});\n// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen\nfunction computeTag(fn, isLE, key, data, AAD) {\n const aadLength = AAD ? AAD.length : 0;\n const h = fn.create(key, data.length + aadLength);\n if (AAD)\n h.update(AAD);\n const num = u64Lengths(8 * data.length, 8 * aadLength, isLE);\n h.update(data);\n h.update(num);\n const res = h.digest();\n clean(num);\n return res;\n}\n/**\n * **GCM** (Galois/Counter Mode): Combines CTR mode with polynomial MAC. Efficient and widely used.\n * Not perfect:\n * a) conservative key wear-out is `2**32` (4B) msgs.\n * b) key wear-out under random nonces is even smaller: `2**23` (8M) messages for `2**-50` chance.\n * c) MAC can be forged: see Poly1305 documentation.\n */\nexport const gcm = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16, varSizeNonce: true }, function aesgcm(key, nonce, AAD) {\n // NIST 800-38d doesn't enforce minimum nonce length.\n // We enforce 8 bytes for compat with openssl.\n // 12 bytes are recommended. More than 12 bytes would be converted into 12.\n if (nonce.length < 8)\n throw new Error('aes/gcm: invalid nonce length');\n const tagLength = 16;\n function _computeTag(authKey, tagMask, data) {\n const tag = computeTag(ghash, false, authKey, data, AAD);\n for (let i = 0; i < tagMask.length; i++)\n tag[i] ^= tagMask[i];\n return tag;\n }\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const authKey = EMPTY_BLOCK.slice();\n const counter = EMPTY_BLOCK.slice();\n ctr32(xk, false, counter, counter, authKey);\n // NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces\n if (nonce.length === 12) {\n counter.set(nonce);\n }\n else {\n const nonceLen = EMPTY_BLOCK.slice();\n const view = createView(nonceLen);\n view.setBigUint64(8, BigInt(nonce.length * 8), false);\n // ghash(nonce || u64be(0) || u64be(nonceLen*8))\n const g = ghash.create(authKey).update(nonce).update(nonceLen);\n g.digestInto(counter); // digestInto doesn't trigger '.destroy'\n g.destroy();\n }\n const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);\n return { xk, authKey, counter, tagMask };\n }\n return {\n encrypt(plaintext) {\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const out = new Uint8Array(plaintext.length + tagLength);\n const toClean = [xk, authKey, counter, tagMask];\n if (!isAligned32(plaintext))\n toClean.push((plaintext = copyBytes(plaintext)));\n ctr32(xk, false, counter, plaintext, out.subarray(0, plaintext.length));\n const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));\n toClean.push(tag);\n out.set(tag, plaintext.length);\n clean(...toClean);\n return out;\n },\n decrypt(ciphertext) {\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const toClean = [xk, authKey, tagMask, counter];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = _computeTag(authKey, tagMask, data);\n toClean.push(tag);\n if (!equalBytes(tag, passedTag))\n throw new Error('aes/gcm: invalid ghash tag');\n const out = ctr32(xk, false, counter, data);\n clean(...toClean);\n return out;\n },\n };\n});\nconst limit = (name, min, max) => (value) => {\n if (!Number.isSafeInteger(value) || min > value || value > max) {\n const minmax = '[' + min + '..' + max + ']';\n throw new Error('' + name + ': expected value in range ' + minmax + ', got ' + value);\n }\n};\n/**\n * **SIV** (Synthetic IV): GCM with nonce-misuse resistance.\n * Repeating nonces reveal only the fact plaintexts are identical.\n * Also suffers from GCM issues: key wear-out limits & MAC forging.\n * See [RFC 8452](https://www.rfc-editor.org/rfc/rfc8452).\n */\nexport const gcmsiv = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16, varSizeNonce: true }, function aessiv(key, nonce, AAD) {\n const tagLength = 16;\n // From RFC 8452: Section 6\n const AAD_LIMIT = limit('AAD', 0, 2 ** 36);\n const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36);\n const NONCE_LIMIT = limit('nonce', 12, 12);\n const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16);\n abytes(key);\n validateKeyLength(key);\n NONCE_LIMIT(nonce.length);\n if (AAD !== undefined)\n AAD_LIMIT(AAD.length);\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const encKey = new Uint8Array(key.length);\n const authKey = new Uint8Array(16);\n const toClean = [xk, encKey];\n let _nonce = nonce;\n if (!isAligned32(_nonce))\n toClean.push((_nonce = copyBytes(_nonce)));\n const n32 = u32(_nonce);\n // prettier-ignore\n let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2];\n let counter = 0;\n for (const derivedKey of [authKey, encKey].map(u32)) {\n const d32 = u32(derivedKey);\n for (let i = 0; i < d32.length; i += 2) {\n // aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ...\n const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3);\n d32[i + 0] = o0;\n d32[i + 1] = o1;\n s0 = ++counter; // increment counter inside state\n }\n }\n const res = { authKey, encKey: expandKeyLE(encKey) };\n // Cleanup\n clean(...toClean);\n return res;\n }\n function _computeTag(encKey, authKey, data) {\n const tag = computeTag(polyval, true, authKey, data, AAD);\n // Compute the expected tag by XORing S_s and the nonce, clearing the\n // most significant bit of the last byte and encrypting with the\n // message-encryption key.\n for (let i = 0; i < 12; i++)\n tag[i] ^= nonce[i];\n tag[15] &= 0x7f; // Clear the highest bit\n // encrypt tag as block\n const t32 = u32(tag);\n // prettier-ignore\n let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3];\n ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3));\n ((t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3));\n return tag;\n }\n // actual decrypt/encrypt of message.\n function processSiv(encKey, tag, input) {\n let block = copyBytes(tag);\n block[15] |= 0x80; // Force highest bit\n const res = ctr32(encKey, true, block, input);\n // Cleanup\n clean(block);\n return res;\n }\n return {\n encrypt(plaintext) {\n PLAIN_LIMIT(plaintext.length);\n const { encKey, authKey } = deriveKeys();\n const tag = _computeTag(encKey, authKey, plaintext);\n const toClean = [encKey, authKey, tag];\n if (!isAligned32(plaintext))\n toClean.push((plaintext = copyBytes(plaintext)));\n const out = new Uint8Array(plaintext.length + tagLength);\n out.set(tag, plaintext.length);\n out.set(processSiv(encKey, tag, plaintext));\n // Cleanup\n clean(...toClean);\n return out;\n },\n decrypt(ciphertext) {\n CIPHER_LIMIT(ciphertext.length);\n const tag = ciphertext.subarray(-tagLength);\n const { encKey, authKey } = deriveKeys();\n const toClean = [encKey, authKey];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));\n const expectedTag = _computeTag(encKey, authKey, plaintext);\n toClean.push(expectedTag);\n if (!equalBytes(tag, expectedTag)) {\n clean(...toClean);\n throw new Error('invalid polyval tag');\n }\n // Cleanup\n clean(...toClean);\n return plaintext;\n },\n };\n});\nfunction isBytes32(a) {\n return (a instanceof Uint32Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint32Array'));\n}\nfunction encryptBlock(xk, block) {\n abytes(block, 16, 'block');\n if (!isBytes32(xk))\n throw new Error('_encryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n ((b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3));\n return block;\n}\nfunction decryptBlock(xk, block) {\n abytes(block, 16, 'block');\n if (!isBytes32(xk))\n throw new Error('_decryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n ((b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3));\n return block;\n}\n/**\n * AES-W (base for AESKW/AESKWP).\n * Specs: [SP800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf),\n * [RFC 3394](https://www.rfc-editor.org/rfc/rfc3394),\n * [RFC 5649](https://www.rfc-editor.org/rfc/rfc5649).\n */\nconst AESW = {\n /*\n High-level pseudocode:\n ```\n A: u64 = IV\n out = []\n for (let i=0, ctr = 0; i<6; i++) {\n for (const chunk of chunks(plaintext, 8)) {\n A ^= swapEndianess(ctr++)\n [A, res] = chunks(encrypt(A || chunk), 8);\n out ||= res\n }\n }\n out = A || out\n ```\n Decrypt is the same, but reversed.\n */\n encrypt(kek, out) {\n // Size is limited to 4GB, otherwise ctr will overflow and we'll need to switch to bigints.\n // If you need it larger, open an issue.\n if (out.length >= 2 ** 32)\n throw new Error('plaintext should be less than 4gb');\n const xk = expandKeyLE(kek);\n if (out.length === 16)\n encryptBlock(xk, out);\n else {\n const o32 = u32(out);\n // prettier-ignore\n let a0 = o32[0], a1 = o32[1]; // A\n for (let j = 0, ctr = 1; j < 6; j++) {\n for (let pos = 2; pos < o32.length; pos += 2, ctr++) {\n const { s0, s1, s2, s3 } = encrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n // A = MSB(64, B) ^ t where t = (n*j)+i\n ((a0 = s0), (a1 = s1 ^ byteSwap(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3));\n }\n }\n ((o32[0] = a0), (o32[1] = a1)); // out = A || out\n }\n xk.fill(0);\n },\n decrypt(kek, out) {\n if (out.length - 8 >= 2 ** 32)\n throw new Error('ciphertext should be less than 4gb');\n const xk = expandKeyDecLE(kek);\n const chunks = out.length / 8 - 1; // first chunk is IV\n if (chunks === 1)\n decryptBlock(xk, out);\n else {\n const o32 = u32(out);\n // prettier-ignore\n let a0 = o32[0], a1 = o32[1]; // A\n for (let j = 0, ctr = chunks * 6; j < 6; j++) {\n for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) {\n a1 ^= byteSwap(ctr);\n const { s0, s1, s2, s3 } = decrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n ((a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3));\n }\n }\n ((o32[0] = a0), (o32[1] = a1));\n }\n xk.fill(0);\n },\n};\nconst AESKW_IV = /* @__PURE__ */ new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6\n/**\n * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.\n * Reduces block size from 16 to 8 bytes.\n * For padded version, use aeskwp.\n * [RFC 3394](https://www.rfc-editor.org/rfc/rfc3394/),\n * [NIST.SP.800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf).\n */\nexport const aeskw = /* @__PURE__ */ wrapCipher({ blockSize: 8 }, (kek) => ({\n encrypt(plaintext) {\n if (!plaintext.length || plaintext.length % 8 !== 0)\n throw new Error('invalid plaintext length');\n if (plaintext.length === 8)\n throw new Error('8-byte keys not allowed in AESKW, use AESKWP instead');\n const out = concatBytes(AESKW_IV, plaintext);\n AESW.encrypt(kek, out);\n return out;\n },\n decrypt(ciphertext) {\n // ciphertext must be at least 24 bytes and a multiple of 8 bytes\n // 24 because should have at least two block (1 iv + 2).\n // Replace with 16 to enable '8-byte keys'\n if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8)\n throw new Error('invalid ciphertext length');\n const out = copyBytes(ciphertext);\n AESW.decrypt(kek, out);\n if (!equalBytes(out.subarray(0, 8), AESKW_IV))\n throw new Error('integrity check failed');\n out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n return out.subarray(8);\n },\n}));\n/*\nWe don't support 8-byte keys. The rabbit hole:\n\n- Wycheproof says: \"NIST SP 800-38F does not define the wrapping of 8 byte keys.\n RFC 3394 Section 2 on the other hand specifies that 8 byte keys are wrapped\n by directly encrypting one block with AES.\"\n - https://github.com/C2SP/wycheproof/blob/master/doc/key_wrap.md\n - \"RFC 3394 specifies in Section 2, that the input for the key wrap\n algorithm must be at least two blocks and otherwise the constant\n field and key are simply encrypted with ECB as a single block\"\n- What RFC 3394 actually says (in Section 2):\n - \"Before being wrapped, the key data is parsed into n blocks of 64 bits.\n The only restriction the key wrap algorithm places on n is that n be\n at least two\"\n - \"For key data with length less than or equal to 64 bits, the constant\n field used in this specification and the key data form a single\n 128-bit codebook input making this key wrap unnecessary.\"\n- Which means \"assert(n >= 2)\" and \"use something else for 8 byte keys\"\n- NIST SP800-38F actually prohibits 8-byte in \"5.3.1 Mandatory Limits\".\n It states that plaintext for KW should be \"2 to 2^54 -1 semiblocks\".\n- So, where does \"directly encrypt single block with AES\" come from?\n - Not RFC 3394. Pseudocode of key wrap in 2.2 explicitly uses\n loop of 6 for any code path\n - There is a weird W3C spec:\n https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/Overview.html#kw-aes128\n - This spec is outdated, as admitted by Wycheproof authors\n - There is RFC 5649 for padded key wrap, which is padding construction on\n top of AESKW. In '4.1.2' it says: \"If the padded plaintext contains exactly\n eight octets, then prepend the AIV as defined in Section 3 above to P[1] and\n encrypt the resulting 128-bit block using AES in ECB mode [Modes] with key\n K (the KEK). In this case, the output is two 64-bit blocks C[0] and C[1]:\"\n - Browser subtle crypto is actually crashes on wrapping keys less than 16 bytes:\n `Error: error:1C8000E6:Provider routines::invalid input length] { opensslErrorStack: [ 'error:030000BD:digital envelope routines::update error' ]`\n\nIn the end, seems like a bug in Wycheproof.\nThe 8-byte check can be easily disabled inside of AES_W.\n*/\nconst AESKWP_IV = 0xa65959a6; // single u32le value\n/**\n * AES-KW, but with padding and allows random keys.\n * Second u32 of IV is used as counter for length.\n * [RFC 5649](https://www.rfc-editor.org/rfc/rfc5649)\n */\nexport const aeskwp = /* @__PURE__ */ wrapCipher({ blockSize: 8 }, (kek) => ({\n encrypt(plaintext) {\n if (!plaintext.length)\n throw new Error('invalid plaintext length');\n const padded = Math.ceil(plaintext.length / 8) * 8;\n const out = new Uint8Array(8 + padded);\n out.set(plaintext, 8);\n const out32 = u32(out);\n out32[0] = AESKWP_IV;\n out32[1] = byteSwap(plaintext.length);\n AESW.encrypt(kek, out);\n return out;\n },\n decrypt(ciphertext) {\n // 16 because should have at least one block\n if (ciphertext.length < 16)\n throw new Error('invalid ciphertext length');\n const out = copyBytes(ciphertext);\n const o32 = u32(out);\n AESW.decrypt(kek, out);\n const len = byteSwap(o32[1]) >>> 0;\n const padded = Math.ceil(len / 8) * 8;\n if (o32[0] !== AESKWP_IV || out.length - 8 !== padded)\n throw new Error('integrity check failed');\n for (let i = len; i < padded; i++)\n if (out[8 + i] !== 0)\n throw new Error('integrity check failed');\n out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n return out.subarray(8, 8 + len);\n },\n}));\nclass _AesCtrDRBG {\n blockLen;\n key;\n nonce;\n state;\n reseedCnt;\n constructor(keyLen, seed, personalization) {\n this.blockLen = ctr.blockSize;\n const keyLenBytes = keyLen / 8;\n const nonceLen = 16;\n this.state = new Uint8Array(keyLenBytes + nonceLen);\n this.key = this.state.subarray(0, keyLenBytes);\n this.nonce = this.state.subarray(keyLenBytes, keyLenBytes + nonceLen);\n this.reseedCnt = 1;\n incBytes(this.nonce, false, 1);\n this.addEntropy(seed, personalization);\n }\n update(data) {\n // cannot re-use state here, because we will wipe current key\n ctr(this.key, this.nonce).encrypt(new Uint8Array(this.state.length), this.state);\n if (data) {\n abytes(data);\n for (let i = 0; i < data.length; i++)\n this.state[i] ^= data[i];\n }\n incBytes(this.nonce, false, 1);\n }\n addEntropy(seed, info) {\n abytes(seed, this.state.length, 'seed');\n const _seed = seed.slice();\n if (info) {\n abytes(info);\n if (info.length > _seed.length)\n throw new Error('info length is too big');\n for (let i = 0; i < info.length; i++)\n _seed[i] ^= info[i];\n }\n this.update(_seed);\n _seed.fill(0);\n this.reseedCnt = 1;\n }\n randomBytes(len, info) {\n anumber(len);\n if (this.reseedCnt++ >= 2 ** 48)\n throw new Error('entropy exhausted');\n if (info)\n this.update(info);\n const res = new Uint8Array(len);\n ctr(this.key, this.nonce).encrypt(res, res);\n incBytes(this.nonce, false, Math.ceil(len / this.blockLen));\n this.update(info);\n return res;\n }\n clean() {\n this.state.fill(0);\n this.reseedCnt = 0;\n }\n}\nconst createAesDrbg = (keyLen) => {\n return (seed, personalization = undefined) => new _AesCtrDRBG(keyLen, seed, personalization);\n};\n/**\n * AES-CTR DRBG 128-bit - CSPRNG (cryptographically secure pseudorandom number generator).\n * It's best to limit usage to non-production, non-critical cases: for example, test-only.\n */\nexport const rngAesCtrDrbg128 = /* @__PURE__ */ createAesDrbg(128);\n/**\n * AES-CTR DRBG 256-bit - CSPRNG (cryptographically secure pseudorandom number generator).\n * It's best to limit usage to non-production, non-critical cases: for example, test-only.\n */\nexport const rngAesCtrDrbg256 = /* @__PURE__ */ createAesDrbg(256);\n//#region CMAC\n/**\n * Left-shift by one bit and conditionally XOR with 0x87:\n * ```\n * if MSB(L) is equal to 0\n * then K1 := L << 1;\n * else K1 := (L << 1) XOR const_Rb;\n * ```\n *\n * Specs: [RFC 4493, Section 2.3](https://www.rfc-editor.org/rfc/rfc4493.html#section-2.3),\n * [RFC 5297 Section 2.3](https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.3)\n *\n * @returns modified `block` (for chaining)\n */\nfunction dbl(block) {\n let carry = 0;\n // Left shift by 1 bit\n for (let i = BLOCK_SIZE - 1; i >= 0; i--) {\n const newCarry = (block[i] & 0x80) >>> 7;\n block[i] = (block[i] << 1) | carry;\n carry = newCarry;\n }\n // XOR with 0x87 if there was a carry from the most significant bit\n if (carry) {\n block[BLOCK_SIZE - 1] ^= 0x87;\n }\n return block;\n}\n/**\n * `a XOR b`, running in-site on `a`.\n * @param a left operand and output\n * @param b right operand\n * @returns `a` (for chaining)\n */\nfunction xorBlock(a, b) {\n if (a.length !== b.length)\n throw new Error('xorBlock: blocks must have same length');\n for (let i = 0; i < a.length; i++) {\n a[i] = a[i] ^ b[i];\n }\n return a;\n}\n/**\n * xorend as defined in [RFC 5297 Section 2.1](https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.1).\n *\n * ```\n * leftmost(A, len(A)-len(B)) || (rightmost(A, len(B)) xor B)\n * ```\n */\nfunction xorend(a, b) {\n if (b.length > a.length) {\n throw new Error('xorend: len(B) must be less than or equal to len(A)');\n }\n // keep leftmost part of `a` unchanged\n // and xor only the rightmost part:\n const offset = a.length - b.length;\n for (let i = 0; i < b.length; i++) {\n a[offset + i] = a[offset + i] ^ b[i];\n }\n return a;\n}\n/**\n * Internal CMAC class.\n */\nclass _CMAC {\n buffer;\n destroyed;\n k1;\n k2;\n xk;\n constructor(key) {\n abytes(key);\n validateKeyLength(key);\n this.xk = expandKeyLE(key);\n this.buffer = new Uint8Array(0);\n this.destroyed = false;\n // L = AES_encrypt(K, const_Zero)\n const L = new Uint8Array(BLOCK_SIZE);\n encryptBlock(this.xk, L);\n // Generate subkeys K1 and K2 from the main key according to\n // [RFC 4493, Section 2.3](https://www.rfc-editor.org/rfc/rfc4493.html#section-2.3)\n // K1\n this.k1 = dbl(L);\n this.k2 = dbl(new Uint8Array(this.k1));\n }\n update(data) {\n const { destroyed, buffer } = this;\n if (destroyed)\n throw new Error('CMAC instance was destroyed');\n abytes(data);\n const newBuffer = new Uint8Array(buffer.length + data.length);\n newBuffer.set(buffer);\n newBuffer.set(data, buffer.length);\n this.buffer = newBuffer;\n return this;\n }\n // see https://www.rfc-editor.org/rfc/rfc4493.html#section-2.4\n digest() {\n if (this.destroyed)\n throw new Error('CMAC instance was destroyed');\n const { buffer } = this;\n const msgLen = buffer.length;\n // Step 2:\n let n = Math.ceil(msgLen / BLOCK_SIZE); // n := ceil(len/const_Bsize);\n // Step 3:\n let flag; // denoting if last block is complete or not\n if (n === 0) {\n n = 1;\n flag = false;\n }\n else {\n flag = msgLen % BLOCK_SIZE === 0; // if len mod const_Bsize is 0\n }\n // Step 4:\n const lastBlockStart = (n - 1) * BLOCK_SIZE;\n const lastBlockData = buffer.subarray(lastBlockStart);\n let m_last;\n if (flag) {\n // M_last := M_n XOR K1;\n m_last = xorBlock(new Uint8Array(lastBlockData), this.k1);\n }\n else {\n // M_last := padding(M_n) XOR K2;\n //\n // [...] padding(x) is the concatenation of x and a single '1',\n // followed by the minimum number of '0's, so that the total length is\n // equal to 128 bits.\n const padded = new Uint8Array(BLOCK_SIZE);\n padded.set(lastBlockData);\n padded[lastBlockData.length] = 0x80; // single '1' bit\n m_last = xorBlock(padded, this.k2);\n }\n // Step 5:\n let x = new Uint8Array(BLOCK_SIZE); // X := const_Zero;\n // Step 6:\n for (let i = 0; i < n - 1; i++) {\n const m_i = buffer.subarray(i * BLOCK_SIZE, (i + 1) * BLOCK_SIZE); // M_i\n xorBlock(x, m_i); // Y := X XOR M_i;\n encryptBlock(this.xk, x); // X := AES-128(K,Y);\n }\n // Step 7:\n xorBlock(x, m_last); // Y := M_last XOR X;\n encryptBlock(this.xk, x); // T := AES-128(K,Y);\n // cleanup:\n clean(m_last);\n return x; // T\n }\n destroy() {\n const { buffer, destroyed, xk, k1, k2 } = this;\n if (destroyed)\n return;\n this.destroyed = true;\n clean(buffer, xk, k1, k2);\n }\n}\n/**\n * AES-CMAC (Cipher-based Message Authentication Code).\n * Specs: [RFC 4493](https://www.rfc-editor.org/rfc/rfc4493.html).\n */\nexport const cmac = (key, message) => new _CMAC(key).update(message).digest();\ncmac.create = (key) => new _CMAC(key);\n/**\n * S2V (Synthetic Initialization Vector) function as described in [RFC 5297 Section 2.4](https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.4).\n *\n * ```\n * S2V(K, S1, ..., Sn) {\n * if n = 0 then\n * return V = AES-CMAC(K, <one>)\n * fi\n * D = AES-CMAC(K, <zero>)\n * for i = 1 to n-1 do\n * D = dbl(D) xor AES-CMAC(K, Si)\n * done\n * if len(Sn) >= 128 then\n * T = Sn xorend D\n * else\n * T = dbl(D) xor pad(Sn)\n * fi\n * return V = AES-CMAC(K, T)\n * }\n * ```\n *\n * S2V takes a key and a vector of strings S1, S2, ..., Sn and returns a 128-bit string.\n * The S2V function is used to generate a synthetic IV for AES-SIV.\n *\n * @param key - AES key (128, 192, or 256 bits)\n * @param strings - Array of byte arrays to process\n * @returns 128-bit synthetic IV\n */\nfunction s2v(key, strings) {\n validateKeyLength(key);\n const len = strings.length;\n if (len > 127) {\n // see https://datatracker.ietf.org/doc/html/rfc5297.html#section-7\n throw new Error('s2v: number of input strings must be less than or equal to 127');\n }\n if (len === 0)\n return cmac(key, ONE_BLOCK);\n // D = AES-CMAC(K, <zero>)\n let d = cmac(key, EMPTY_BLOCK);\n // for i = 1 to n-1 do\n // D = dbl(D) xor AES-CMAC(K, Si)\n for (let i = 0; i < len - 1; i++) {\n dbl(d);\n const cmacResult = cmac(key, strings[i]);\n xorBlock(d, cmacResult);\n clean(cmacResult);\n }\n const s_n = strings[len - 1];\n let t;\n // if len(Sn) >= 128 then\n if (s_n.byteLength >= BLOCK_SIZE) {\n // T = Sn xorend D\n t = xorend(Uint8Array.from(s_n), d);\n }\n else {\n // pad(Sn):\n const paddedSn = new Uint8Array(BLOCK_SIZE);\n paddedSn.set(s_n);\n paddedSn[s_n.length] = 0x80; // padding: 0x80 followed by zeros\n // T = dbl(D) xor pad(Sn)\n t = xorBlock(dbl(d), paddedSn);\n clean(paddedSn);\n }\n // V = AES-CMAC(K, T)\n const result = cmac(key, t);\n clean(d, t);\n return result;\n}\n/** Use `gcmsiv` or `aessiv`. */\nexport const siv = () => {\n throw new Error('\"siv\" from v1 is now \"gcmsiv\"');\n};\n/**\n * **SIV**: Synthetic Initialization Vector (SIV) Authenticated Encryption\n * Nonce is derived from the plaintext and AAD using the S2V function.\n * See [RFC 5297](https://datatracker.ietf.org/doc/html/rfc5297.html).\n */\nexport const aessiv = /* @__PURE__ */ wrapCipher({ blockSize: 16, tagLength: 16 }, function aessiv(key, ...AAD) {\n // From RFC 5297: Section 6.1, 6.2, 6.3:\n const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 132);\n const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 132 + 16);\n if (AAD.length > 126) {\n // see https://datatracker.ietf.org/doc/html/rfc5297.html#section-7\n throw new Error('\"AAD\" number of elements must be less than or equal to 126');\n }\n AAD.forEach((aad) => abytes(aad));\n abytes(key);\n if (![32, 48, 64].includes(key.length))\n throw new Error('\"aes key\" expected Uint8Array of length 32/48/64, got length=' + key.length);\n // The key is split into equal halves, K1 = leftmost(K, len(K)/2) and\n // K2 = rightmost(K, len(K)/2). K1 is used for S2V and K2 is used for CTR.\n const k1 = key.subarray(0, key.length / 2);\n const k2 = key.subarray(key.length / 2);\n return {\n // https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.6\n encrypt(plaintext) {\n PLAIN_LIMIT(plaintext.length);\n const v = s2v(k1, [...AAD, plaintext]);\n // clear out the 31st and 63rd (rightmost) bit:\n const q = Uint8Array.from(v);\n q[8] &= 0x7f;\n q[12] &= 0x7f;\n // encrypt:\n const c = ctr(k2, q).encrypt(plaintext);\n return concatBytes(v, c);\n },\n // https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.7\n decrypt(ciphertext) {\n CIPHER_LIMIT(ciphertext.length);\n const v = ciphertext.subarray(0, BLOCK_SIZE);\n const c = ciphertext.subarray(BLOCK_SIZE);\n // clear out the 31st and 63rd (rightmost) bit:\n const q = Uint8Array.from(v);\n q[8] &= 0x7f;\n q[12] &= 0x7f;\n // decrypt:\n const p = ctr(k2, q).decrypt(c);\n // verify tag:\n const t = s2v(k1, [...AAD, p]);\n if (equalBytes(t, v)) {\n return p;\n }\n else {\n throw new Error('invalid siv tag');\n }\n },\n };\n});\n//#endregion\n/** Unsafe low-level internal methods. May change at any time. */\nexport const unsafe = {\n expandKeyLE,\n expandKeyDecLE,\n encrypt,\n decrypt,\n encryptBlock,\n decryptBlock,\n ctrCounter,\n ctr32,\n dbl,\n xorBlock,\n xorend,\n s2v,\n};\n//# sourceMappingURL=aes.js.map","/**\n * Memo encryption/decryption for Zattera blockchain\n * Based on ECIES (Elliptic Curve Integrated Encryption Scheme)\n */\n\nimport { sha256, sha512 } from '@noble/hashes/sha2';\nimport * as aes from '@noble/ciphers/aes.js';\nimport { randomBytes } from '@noble/ciphers/utils.js';\nimport bs58 from 'bs58';\nimport { PrivateKey, PublicKey } from './keys.js';\n\n/**\n * Generate a random nonce\n * @param size Size of nonce in bytes (default: 8)\n * @returns Random nonce\n */\nfunction generateNonce(size: number = 8): Uint8Array {\n return randomBytes(size);\n}\n\n/**\n * Encode a memo for encryption\n * @param privateKey Sender's private key\n * @param publicKey Recipient's public key\n * @param memo Memo text (will be prefixed with # if not already)\n * @param nonce Optional nonce for testing (default: random)\n * @returns Encrypted memo string with # prefix\n *\n * @example\n * ```typescript\n * const senderKey = PrivateKey.fromSeed('sender seed');\n * const recipientPubKey = PrivateKey.fromSeed('recipient seed').toPublic();\n * const encrypted = await encodeMemo(senderKey, recipientPubKey, 'Hello!');\n * // Returns: \"#<base58_encoded_encrypted_data>\"\n * ```\n */\nexport function encodeMemo(\n privateKey: PrivateKey,\n publicKey: PublicKey,\n memo: string,\n nonce?: Uint8Array\n): string {\n // If memo doesn't start with #, it's not encrypted\n if (!memo.startsWith('#')) {\n memo = '#' + memo;\n }\n\n // Remove the # prefix for encryption\n const message = memo.slice(1);\n const messageBytes = new TextEncoder().encode(message);\n\n // Generate or use provided nonce\n const nonceBytes = nonce ?? generateNonce(8);\n\n // Get shared secret using ECDH\n const sharedSecret = privateKey.getSharedSecret(publicKey);\n\n // Derive encryption key and IV from shared secret and nonce\n // Key derivation: SHA512(nonce || shared_secret)\n const combined = new Uint8Array(nonceBytes.length + sharedSecret.length);\n combined.set(nonceBytes);\n combined.set(sharedSecret, nonceBytes.length);\n\n const hash = sha512(combined);\n\n // Split hash into IV (first 16 bytes) and key (next 32 bytes)\n const iv = hash.slice(0, 16);\n const encryptionKey = hash.slice(16, 48);\n\n // Encrypt the message\n const cipher = aes.cbc(encryptionKey, iv);\n const encrypted = cipher.encrypt(messageBytes);\n\n // Calculate checksum (first 4 bytes of SHA256 of encryption key)\n const checksumHash = sha256(encryptionKey);\n const checksum = checksumHash.slice(0, 4);\n\n // Serialize: nonce (8 bytes) + checksum (4 bytes) + encrypted data\n const serialized = new Uint8Array(nonceBytes.length + checksum.length + encrypted.length);\n serialized.set(nonceBytes, 0);\n serialized.set(checksum, nonceBytes.length);\n serialized.set(encrypted, nonceBytes.length + checksum.length);\n\n // Encode to base58 and add # prefix\n return '#' + bs58.encode(serialized);\n}\n\n/**\n * Decode an encrypted memo\n *\n * Note: This function is deprecated. Use decodeMemoWithKey instead, as it requires\n * the sender's public key to properly decrypt the memo.\n *\n * @param _privateKey Recipient's private key (unused)\n * @param memo Encrypted memo string (must start with #)\n * @returns Never - throws error directing to use decodeMemoWithKey\n * @deprecated Use decodeMemoWithKey instead\n */\nexport function decodeMemo(_privateKey: PrivateKey, memo: string): string {\n // If memo doesn't start with #, it's not encrypted\n if (!memo.startsWith('#')) {\n return memo;\n }\n\n throw new Error('decodeMemo requires sender public key - use decodeMemoWithKey instead');\n}\n\n/**\n * Decode an encrypted memo with explicit public key\n * @param privateKey Recipient's private key\n * @param publicKey Sender's public key\n * @param memo Encrypted memo string (must start with #)\n * @returns Decrypted memo text (with # prefix)\n *\n * @example\n * ```typescript\n * const recipientKey = PrivateKey.fromSeed('recipient seed');\n * const senderPubKey = PrivateKey.fromSeed('sender seed').toPublic();\n * const decrypted = await decodeMemoWithKey(recipientKey, senderPubKey, encryptedMemo);\n * // Returns: \"#Hello!\"\n * ```\n */\nexport function decodeMemoWithKey(\n privateKey: PrivateKey,\n publicKey: PublicKey,\n memo: string\n): string {\n // If memo doesn't start with #, it's not encrypted\n if (!memo.startsWith('#')) {\n return memo;\n }\n\n try {\n // Remove # prefix and decode from base58\n const decoded = bs58.decode(memo.slice(1));\n\n // Extract components\n const nonce = decoded.slice(0, 8);\n const checksum = decoded.slice(8, 12);\n const encrypted = decoded.slice(12);\n\n // Get shared secret using ECDH\n const sharedSecret = privateKey.getSharedSecret(publicKey);\n\n // Derive encryption key and IV\n const combined = new Uint8Array(nonce.length + sharedSecret.length);\n combined.set(nonce);\n combined.set(sharedSecret, nonce.length);\n\n const hash = sha512(combined);\n const iv = hash.slice(0, 16);\n const encryptionKey = hash.slice(16, 48);\n\n // Verify checksum\n const checksumHash = sha256(encryptionKey);\n const expectedChecksum = checksumHash.slice(0, 4);\n\n let checksumValid = true;\n for (let i = 0; i < 4; i++) {\n if (checksum[i] !== expectedChecksum[i]) {\n checksumValid = false;\n break;\n }\n }\n\n if (!checksumValid) {\n throw new Error('Invalid memo checksum');\n }\n\n // Decrypt the message\n const decipher = aes.cbc(encryptionKey, iv);\n const decrypted = decipher.decrypt(encrypted);\n\n // Convert to string and add # prefix\n const message = new TextDecoder().decode(decrypted);\n return '#' + message;\n } catch (error) {\n throw new Error(`Failed to decode memo: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n","/**\n * Authentication and transaction signing for Zattera blockchain\n */\n\nimport { sha256 } from '@noble/hashes/sha2';\nimport { PrivateKey, PublicKey, Signature, generateKeys as genKeys } from './keys.js';\nimport { serializeTransaction } from './serializer.js';\nimport type { Transaction, SignedTransaction, Operation } from '../types/index.js';\n\nexport * from './keys.js';\nexport * from './serializer.js';\nexport * from './memo.js';\n\n/**\n * Configuration for signing\n */\nexport interface SignConfig {\n chainId: string;\n addressPrefix?: string;\n}\n\n/**\n * Sign a transaction with one or more private keys\n *\n * @param transaction The transaction to sign\n * @param privateKeys Array of private keys (WIF format) or PrivateKey instances\n * @param chainId Chain ID (hex string without 0x prefix)\n * @returns Signed transaction with signatures\n *\n * @example\n * ```typescript\n * const signedTx = await signTransaction(\n * transaction,\n * ['5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3'],\n * '0000000000000000000000000000000000000000000000000000000000000000'\n * );\n * ```\n */\nexport async function signTransaction(\n transaction: Transaction,\n privateKeys: (string | PrivateKey)[],\n chainId: string\n): Promise<SignedTransaction> {\n // Serialize the transaction (without signatures)\n const txBuffer = serializeTransaction(transaction);\n\n // Convert chain ID from hex to bytes\n const chainIdBytes = hexToBytes(chainId);\n\n // Create the digest: chainId + serialized transaction\n const digest = new Uint8Array(chainIdBytes.length + txBuffer.length);\n digest.set(chainIdBytes);\n digest.set(txBuffer, chainIdBytes.length);\n\n // Hash the digest with SHA-256\n const messageHash = sha256(digest);\n\n // Sign with each private key\n const signatures: string[] = [];\n\n for (const key of privateKeys) {\n const privateKey = typeof key === 'string' ? PrivateKey.fromWif(key) : key;\n const signature = await privateKey.sign(messageHash);\n signatures.push(bufferToHex(signature.toBuffer()));\n }\n\n // Return signed transaction\n return {\n ...transaction,\n signatures,\n };\n}\n\n/**\n * Verify a transaction signature\n *\n * @param transaction The signed transaction\n * @param chainId Chain ID (hex string without 0x prefix)\n * @returns Array of public keys that signed the transaction\n */\nexport async function verifyTransactionSignatures(\n transaction: SignedTransaction,\n chainId: string\n): Promise<PublicKey[]> {\n // Serialize the transaction (without signatures)\n const { signatures, ...txWithoutSigs } = transaction;\n const txBuffer = serializeTransaction(txWithoutSigs);\n\n // Create the digest\n const chainIdBytes = hexToBytes(chainId);\n const digest = new Uint8Array(chainIdBytes.length + txBuffer.length);\n digest.set(chainIdBytes);\n digest.set(txBuffer, chainIdBytes.length);\n\n // Hash the digest\n const messageHash = sha256(digest);\n\n // Recover public keys from signatures\n const publicKeys: PublicKey[] = [];\n\n for (const sigHex of signatures) {\n const sigBytes = hexToBytes(sigHex);\n const signature = new Signature(sigBytes);\n const publicKey = await signature.recoverPublicKey(messageHash);\n publicKeys.push(publicKey);\n }\n\n return publicKeys;\n}\n\n/**\n * Create a transaction ready for signing\n *\n * @param refBlockNum Reference block number (from head_block_number & 0xFFFF)\n * @param refBlockPrefix Reference block prefix (from block header)\n * @param expiration Expiration date (ISO 8601 string or Date)\n * @param operations Array of operations\n * @returns Transaction object ready for signing\n *\n * @example\n * ```typescript\n * const tx = createTransaction(\n * 12345,\n * 4567890,\n * new Date(Date.now() + 60000),\n * [\n * ['vote', { voter: 'alice', author: 'bob', permlink: 'test', weight: 10000 }]\n * ]\n * );\n * ```\n */\nexport function createTransaction(\n refBlockNum: number,\n refBlockPrefix: number,\n expiration: string | Date,\n operations: unknown[]\n): Transaction {\n const expirationString = typeof expiration === 'string'\n ? expiration\n : (expiration.toISOString().split('.')[0] ?? ''); // Remove milliseconds\n\n return {\n ref_block_num: refBlockNum & 0xffff, // Ensure it's within uint16 range\n ref_block_prefix: refBlockPrefix >>> 0, // Ensure it's uint32\n expiration: expirationString,\n operations: operations as Operation[],\n extensions: [],\n };\n}\n\n/**\n * Helper: Convert hex string to Uint8Array\n */\nfunction hexToBytes(hex: string): Uint8Array {\n // Remove '0x' prefix if present\n const cleanHex = hex.startsWith('0x') ? hex.slice(2) : hex;\n\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Helper: Convert Uint8Array to hex string\n */\nfunction bufferToHex(buffer: Uint8Array): string {\n return Array.from(buffer)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/**\n * Auth API - Comprehensive authentication utilities\n */\nexport const Auth = {\n /**\n * Generate all role keys from account name and password\n * @param name Account name\n * @param password Password\n * @param roles Array of role names (default: ['owner', 'active', 'posting', 'memo'])\n * @returns Object mapping roles to private WIF keys and public keys\n *\n * @example\n * ```typescript\n * const keys = Auth.getPrivateKeys('alice', 'password123');\n * console.log(keys.active); // WIF private key\n * console.log(keys.activePubkey); // ZTR... public key\n * ```\n */\n getPrivateKeys(\n name: string,\n password: string,\n roles: string[] = ['owner', 'active', 'posting', 'memo']\n ): Record<string, string> {\n const result: Record<string, string> = {};\n const keys = genKeys(name, password, roles);\n\n for (const role of roles) {\n const roleKey = keys[role];\n if (roleKey) {\n result[role] = roleKey.private;\n result[`${role}Pubkey`] = roleKey.public;\n }\n }\n\n return result;\n },\n\n /**\n * Generate public keys only from account name and password\n * @param name Account name\n * @param password Password\n * @param roles Array of role names\n * @returns Object mapping roles to public keys\n */\n generateKeys(\n name: string,\n password: string,\n roles: string[] = ['owner', 'active', 'posting', 'memo']\n ): Record<string, string> {\n const keys = genKeys(name, password, roles);\n const result: Record<string, string> = {};\n\n for (const role of roles) {\n const roleKey = keys[role];\n if (roleKey) {\n result[role] = roleKey.public;\n }\n }\n\n return result;\n },\n\n /**\n * Convert account credentials to WIF format for a specific role\n * @param name Account name\n * @param password Password\n * @param role Role name (e.g., 'active', 'posting')\n * @returns WIF private key\n */\n toWif(name: string, password: string, role: string = 'active'): string {\n const privateKey = PrivateKey.fromLogin(name, password, role);\n return privateKey.toWif();\n },\n\n /**\n * Convert WIF private key to public key\n * @param privateWif WIF format private key\n * @param addressPrefix Address prefix (default: 'ZTR')\n * @returns Public key string\n */\n wifToPublic(privateWif: string, addressPrefix: string = 'ZTR'): string {\n const privateKey = PrivateKey.fromWif(privateWif);\n const publicKey = privateKey.toPublic();\n return publicKey.toString(addressPrefix);\n },\n\n /**\n * Check if a WIF key is valid\n * @param privateWif WIF format private key\n * @returns true if valid, false otherwise\n */\n isWif(privateWif: string): boolean {\n try {\n PrivateKey.fromWif(privateWif);\n return true;\n } catch {\n return false;\n }\n },\n\n /**\n * Sign a transaction with private keys\n * @param tx Transaction to sign\n * @param keys Array of WIF private keys\n * @param chainId Chain ID\n * @returns Signed transaction\n */\n signTransaction(\n tx: Transaction,\n keys: string[],\n chainId: string\n ): Promise<SignedTransaction> {\n return signTransaction(tx, keys, chainId);\n },\n\n /**\n * Verify account credentials against authorities\n * @param name Account name\n * @param password Password\n * @param auths Authority public keys to verify against\n * @param role Role to check (default: 'active')\n * @returns true if credentials match, false otherwise\n */\n verify(\n name: string,\n password: string,\n auths: { owner?: string[]; active?: string[]; posting?: string[] },\n role: string = 'active'\n ): boolean {\n const privateKey = PrivateKey.fromLogin(name, password, role);\n const publicKey = privateKey.toPublic().toString('ZTR');\n\n const roleAuths = auths[role as keyof typeof auths];\n if (!roleAuths) {\n return false;\n }\n\n return roleAuths.includes(publicKey);\n },\n};\n","/**\n * Zattera RPC Types\n */\n\n// ============================================================================\n// Client Configuration\n// ============================================================================\n\n/**\n * Supported network names for chain ID computation\n */\nexport type NetworkName = 'zattera' | 'testnet';\n\nexport interface ZatteraClientConfig {\n endpoint: string;\n networkName?: NetworkName;\n timeout?: number;\n retries?: number;\n}\n\n// ============================================================================\n// JSON-RPC 2.0 Protocol Types\n// ============================================================================\n\nexport interface JsonRpcRequest {\n jsonrpc: '2.0';\n method: string;\n params?: unknown[] | Record<string, unknown>;\n id: string | number;\n}\n\nexport interface JsonRpcResponse<T = unknown> {\n jsonrpc: '2.0';\n result?: T;\n error?: JsonRpcError;\n id: string | number | null;\n}\n\nexport interface JsonRpcError {\n code: number;\n message: string;\n data?: unknown;\n}\n\nexport type RpcMethod = string;\nexport type RpcParams = unknown[];\n\n// JSON-RPC Error Codes\nexport enum JsonRpcErrorCode {\n PARSE_ERROR = -32700,\n INVALID_REQUEST = -32600,\n METHOD_NOT_FOUND = -32601,\n INVALID_PARAMS = -32602,\n INTERNAL_ERROR = -32603,\n SERVER_ERROR = -32000,\n NO_PARAMS = -32001,\n PARSE_PARAMS_ERROR = -32002,\n ERROR_DURING_CALL = -32003,\n}\n\n// ============================================================================\n// Core Protocol Types\n// ============================================================================\n\nexport type AccountName = string;\nexport type BlockId = string;\nexport type TransactionId = string;\nexport type Signature = string;\nexport type PublicKey = string;\nexport type PrivateKey = string;\nexport type ShareType = string; // int64 as string to avoid precision loss\nexport type AssetSymbol = string;\n\nexport interface Asset {\n amount: ShareType;\n symbol: AssetSymbol;\n precision: number;\n}\n\nexport interface Price {\n base: Asset;\n quote: Asset;\n}\n\n// ============================================================================\n// Transaction Types\n// ============================================================================\n\nexport interface Transaction {\n ref_block_num: number;\n ref_block_prefix: number;\n expiration: string; // ISO 8601 datetime\n operations: Operation[];\n extensions: unknown[];\n}\n\nexport interface SignedTransaction extends Transaction {\n signatures: Signature[];\n}\n\nexport type Operation = unknown[]; // [operation_type, operation_data]\n\n// ============================================================================\n// Block Types\n// ============================================================================\n\nexport interface BlockHeader {\n previous: BlockId;\n timestamp: string;\n witness: AccountName;\n transaction_merkle_root: string;\n extensions: unknown[];\n}\n\nexport interface SignedBlockHeader extends BlockHeader {\n witness_signature: Signature;\n}\n\nexport interface SignedBlock extends SignedBlockHeader {\n transactions: SignedTransaction[];\n block_id?: BlockId;\n signing_key?: PublicKey;\n transaction_ids?: TransactionId[];\n}\n\n// ============================================================================\n// Database API Types\n// ============================================================================\n\nexport interface DynamicGlobalProperties {\n id: number;\n head_block_number: number;\n head_block_id: BlockId;\n time: string;\n current_witness: AccountName;\n total_pow: number;\n num_pow_witnesses: number;\n virtual_supply: Asset;\n current_supply: Asset;\n init_sbd_supply: Asset;\n current_sbd_supply: Asset;\n total_vesting_fund_steem: Asset;\n total_vesting_shares: Asset;\n total_reward_fund_steem: Asset;\n total_reward_shares2: string;\n pending_rewarded_vesting_shares: Asset;\n pending_rewarded_vesting_steem: Asset;\n sbd_interest_rate: number;\n sbd_print_rate: number;\n maximum_block_size: number;\n required_actions_partition_percent: number;\n current_aslot: number;\n recent_slots_filled: string;\n participation_count: number;\n last_irreversible_block_num: number;\n vote_power_reserve_rate: number;\n delegation_return_period: number;\n reverse_auction_seconds: number;\n available_account_subsidies: number;\n sbd_stop_percent: number;\n sbd_start_percent: number;\n next_maintenance_time: string;\n last_budget_time: string;\n content_reward_percent: number;\n vesting_reward_percent: number;\n sps_fund_percent: number;\n sps_interval_ledger: Asset;\n downvote_pool_percent: number;\n}\n\nexport interface ChainConfig {\n ZATTERA_CHAIN_ID: string;\n ZATTERA_ADDRESS_PREFIX: string;\n ZATTERA_GENESIS_TIME: string;\n ZATTERA_MINING_TIME: string;\n ZATTERA_MIN_ACCOUNT_NAME_LENGTH: number;\n ZATTERA_MAX_ACCOUNT_NAME_LENGTH: number;\n ZATTERA_MIN_PERMLINK_LENGTH: number;\n ZATTERA_MAX_PERMLINK_LENGTH: number;\n ZATTERA_BLOCK_INTERVAL: number;\n ZATTERA_BLOCKS_PER_YEAR: number;\n ZATTERA_BLOCKS_PER_DAY: number;\n ZATTERA_START_VESTING_BLOCK: number;\n ZATTERA_INIT_MINER_NAME: string;\n ZATTERA_NUM_INIT_MINERS: number;\n ZATTERA_INIT_TIME: string;\n ZATTERA_MAX_WITNESSES: number;\n ZATTERA_MAX_VOTED_WITNESSES_HF0: number;\n ZATTERA_MAX_MINER_WITNESSES_HF0: number;\n ZATTERA_MAX_RUNNER_WITNESSES_HF0: number;\n [key: string]: unknown;\n}\n\nexport interface WitnessSchedule {\n id: number;\n current_virtual_time: string;\n next_shuffle_block_num: number;\n current_shuffled_witnesses: AccountName[];\n num_scheduled_witnesses: number;\n elected_weight: number;\n timeshare_weight: number;\n miner_weight: number;\n witness_pay_normalization_factor: number;\n median_props: {\n account_creation_fee: Asset;\n maximum_block_size: number;\n sbd_interest_rate: number;\n };\n majority_version: string;\n max_voted_witnesses: number;\n max_miner_witnesses: number;\n max_runner_witnesses: number;\n hardfork_required_witnesses: number;\n account_subsidy_budget: number;\n account_subsidy_decay: number;\n}\n\nexport interface HardforkProperties {\n id: number;\n processed_hardforks: string[];\n last_hardfork: number;\n current_hardfork_version: string;\n next_hardfork: string;\n next_hardfork_time: string;\n}\n\nexport interface RewardFund {\n id: number;\n name: string;\n reward_balance: Asset;\n recent_claims: string;\n last_update: string;\n content_constant: string;\n percent_curation_rewards: number;\n percent_content_rewards: number;\n author_reward_curve: string;\n curation_reward_curve: string;\n}\n\nexport interface PriceFeed {\n base: Asset;\n quote: Asset;\n}\n\nexport interface FeedHistory {\n id: number;\n current_median_history: Price;\n market_median_history: Price;\n current_min_history: Price;\n current_max_history: Price;\n price_history: Price[];\n}\n\n// ============================================================================\n// Account Types\n// ============================================================================\n\nexport interface Account {\n id: number;\n name: AccountName;\n owner: Authority;\n active: Authority;\n posting: Authority;\n memo_key: PublicKey;\n json_metadata: string;\n posting_json_metadata: string;\n proxy: AccountName;\n last_owner_update: string;\n last_account_update: string;\n created: string;\n mined: boolean;\n recovery_account: AccountName;\n reset_account: AccountName;\n last_account_recovery: string;\n comment_count: number;\n lifetime_vote_count: number;\n post_count: number;\n can_vote: boolean;\n voting_manabar: {\n current_mana: string;\n last_update_time: number;\n };\n downvote_manabar: {\n current_mana: string;\n last_update_time: number;\n };\n balance: Asset;\n savings_balance: Asset;\n sbd_balance: Asset;\n sbd_seconds: string;\n sbd_seconds_last_update: string;\n sbd_last_interest_payment: string;\n savings_sbd_balance: Asset;\n savings_sbd_seconds: string;\n savings_sbd_seconds_last_update: string;\n savings_sbd_last_interest_payment: string;\n savings_withdraw_requests: number;\n reward_sbd_balance: Asset;\n reward_steem_balance: Asset;\n reward_vesting_balance: Asset;\n reward_vesting_steem: Asset;\n vesting_shares: Asset;\n delegated_vesting_shares: Asset;\n received_vesting_shares: Asset;\n vesting_withdraw_rate: Asset;\n post_voting_power: Asset;\n next_vesting_withdrawal: string;\n withdrawn: number;\n to_withdraw: number;\n withdraw_routes: number;\n pending_transfers: number;\n curation_rewards: number;\n posting_rewards: number;\n proxied_vsf_votes: number[];\n witnesses_voted_for: number;\n last_post: string;\n last_root_post: string;\n last_vote_time: string;\n post_bandwidth: number;\n pending_claimed_accounts: number;\n delayed_votes: unknown[];\n open_recurrent_transfers: number;\n vesting_balance: Asset;\n reputation: string;\n transfer_history: unknown[];\n market_history: unknown[];\n post_history: unknown[];\n vote_history: unknown[];\n other_history: unknown[];\n witness_votes: AccountName[];\n tags_usage: unknown[];\n guest_bloggers: AccountName[];\n}\n\nexport interface Authority {\n weight_threshold: number;\n account_auths: [AccountName, number][];\n key_auths: [PublicKey, number][];\n}\n\nexport interface OwnerHistory {\n id: number;\n account: AccountName;\n previous_owner_authority: Authority;\n last_valid_time: string;\n}\n\nexport interface AccountRecoveryRequest {\n id: number;\n account_to_recover: AccountName;\n new_owner_authority: Authority;\n expires: string;\n}\n\nexport interface Escrow {\n id: number;\n escrow_id: number;\n from: AccountName;\n to: AccountName;\n agent: AccountName;\n ratification_deadline: string;\n escrow_expiration: string;\n sbd_balance: Asset;\n steem_balance: Asset;\n pending_fee: Asset;\n to_approved: boolean;\n agent_approved: boolean;\n disputed: boolean;\n}\n\nexport interface VestingDelegation {\n id: number;\n delegator: AccountName;\n delegatee: AccountName;\n vesting_shares: Asset;\n min_delegation_time: string;\n}\n\nexport interface ConversionRequest {\n id: number;\n owner: AccountName;\n requestid: number;\n amount: Asset;\n conversion_date: string;\n}\n\n// ============================================================================\n// Comment/Discussion Types\n// ============================================================================\n\nexport interface Comment {\n id: number;\n author: AccountName;\n permlink: string;\n category: string;\n parent_author: AccountName;\n parent_permlink: string;\n title: string;\n body: string;\n json_metadata: string;\n last_update: string;\n created: string;\n active: string;\n last_payout: string;\n depth: number;\n children: number;\n net_rshares: string;\n abs_rshares: string;\n vote_rshares: string;\n children_abs_rshares: string;\n cashout_time: string;\n max_cashout_time: string;\n total_vote_weight: number;\n reward_weight: number;\n total_payout_value: Asset;\n curator_payout_value: Asset;\n author_rewards: number;\n net_votes: number;\n root_author: AccountName;\n root_permlink: string;\n max_accepted_payout: Asset;\n percent_steem_dollars: number;\n allow_replies: boolean;\n allow_votes: boolean;\n allow_curation_rewards: boolean;\n beneficiaries: Beneficiary[];\n url: string;\n root_title: string;\n pending_payout_value: Asset;\n total_pending_payout_value: Asset;\n active_votes: ActiveVote[];\n replies: string[];\n author_reputation: string;\n promoted: Asset;\n body_length: number;\n reblogged_by: AccountName[];\n}\n\nexport interface Beneficiary {\n account: AccountName;\n weight: number;\n}\n\nexport interface ActiveVote {\n voter: AccountName;\n weight: number;\n rshares: string;\n percent: number;\n reputation: string;\n time: string;\n}\n\nexport interface Vote {\n id: number;\n voter: AccountName;\n author: AccountName;\n permlink: string;\n weight: number;\n rshares: string;\n vote_percent: number;\n last_update: string;\n num_changes: number;\n}\n\n// ============================================================================\n// Witness Types\n// ============================================================================\n\nexport interface Witness {\n id: number;\n owner: AccountName;\n created: string;\n url: string;\n votes: string;\n virtual_last_update: string;\n virtual_position: string;\n virtual_scheduled_time: string;\n total_missed: number;\n last_aslot: number;\n last_confirmed_block_num: number;\n pow_worker: number;\n signing_key: PublicKey;\n props: {\n account_creation_fee: Asset;\n maximum_block_size: number;\n sbd_interest_rate: number;\n account_subsidy_budget: number;\n account_subsidy_decay: number;\n };\n sbd_exchange_rate: Price;\n last_sbd_exchange_update: string;\n last_work: string;\n running_version: string;\n hardfork_version_vote: string;\n hardfork_time_vote: string;\n available_witness_account_subsidies: number;\n}\n\nexport interface WitnessVote {\n id: number;\n witness: AccountName;\n account: AccountName;\n}\n\n// ============================================================================\n// Market Types\n// ============================================================================\n\nexport interface LimitOrder {\n id: number;\n created: string;\n expiration: string;\n seller: AccountName;\n orderid: number;\n for_sale: number;\n sell_price: Price;\n}\n\nexport interface OrderBook {\n bids: Order[];\n asks: Order[];\n}\n\nexport interface Order {\n order_price: Price;\n real_price: string;\n steem: number;\n sbd: number;\n created: string;\n}\n\n// ============================================================================\n// List/Find Query Types\n// ============================================================================\n\nexport enum ListOrder {\n BY_NAME = 'by_name',\n BY_PROXY = 'by_proxy',\n BY_NEXT_VESTING_WITHDRAWAL = 'by_next_vesting_withdrawal',\n BY_ACCOUNT = 'by_account',\n BY_EXPIRATION = 'by_expiration',\n BY_EFFECTIVE_DATE = 'by_effective_date',\n BY_VOTE = 'by_vote',\n BY_ACCOUNT_WITNESS = 'by_account_witness',\n BY_WITNESS_ACCOUNT = 'by_witness_account',\n BY_FROM_ID = 'by_from_id',\n BY_RATIFICATION_DEADLINE = 'by_ratification_deadline',\n BY_WITHDRAW_ROUTE = 'by_withdraw_route',\n BY_DESTINATION = 'by_destination',\n BY_COMPLETE_FROM_ID = 'by_complete_from_id',\n BY_TO_COMPLETE = 'by_to_complete',\n BY_DELEGATION = 'by_delegation',\n BY_ACCOUNT_EXPIRATION = 'by_account_expiration',\n BY_CONVERSION_DATE = 'by_conversion_date',\n BY_CASHOUT_TIME = 'by_cashout_time',\n BY_PERMLINK = 'by_permlink',\n BY_ROOT = 'by_root',\n BY_PARENT = 'by_parent',\n BY_LAST_UPDATE = 'by_last_update',\n BY_AUTHOR_LAST_UPDATE = 'by_author_last_update',\n BY_COMMENT_VOTER = 'by_comment_voter',\n BY_VOTER_COMMENT = 'by_voter_comment',\n BY_PRICE = 'by_price',\n BY_ACCOUNT_CREATION = 'by_account_creation',\n}\n\n// ============================================================================\n// API Method Parameters\n// ============================================================================\n\nexport interface ListAccountsParams {\n start?: AccountName | null;\n limit: number;\n order: ListOrder;\n [key: string]: unknown;\n}\n\nexport interface FindAccountsParams {\n accounts: AccountName[];\n [key: string]: unknown;\n}\n\nexport interface ListWitnessesParams {\n start?: AccountName | null;\n limit: number;\n order: ListOrder;\n [key: string]: unknown;\n}\n\nexport interface GetAccountHistoryParams {\n account: AccountName;\n start: number;\n limit: number;\n [key: string]: unknown;\n}\n\nexport interface GetOpsInBlockParams {\n block_num: number;\n only_virtual: boolean;\n [key: string]: unknown;\n}\n\nexport interface DiscussionQuery {\n tag?: string;\n limit?: number;\n filter_tags?: string[];\n select_authors?: AccountName[];\n select_tags?: string[];\n truncate_body?: number;\n start_author?: AccountName;\n start_permlink?: string;\n parent_author?: AccountName;\n parent_permlink?: string;\n [key: string]: unknown;\n}\n\nexport interface GetFollowersParams {\n account: AccountName;\n start: AccountName | null;\n type: string;\n limit: number;\n [key: string]: unknown;\n}\n\nexport interface GetFollowingParams {\n account: AccountName;\n start: AccountName | null;\n type: string;\n limit: number;\n [key: string]: unknown;\n}\n\n// ============================================================================\n// API Method Return Types\n// ============================================================================\n\nexport interface BroadcastTransactionResult {\n id: TransactionId;\n block_num: number;\n trx_num: number;\n expired: boolean;\n}\n\nexport interface VerifyAuthorityResult {\n valid: boolean;\n}\n\nexport interface GetTransactionResult {\n ref_block_num: number;\n ref_block_prefix: number;\n expiration: string;\n operations: Operation[];\n extensions: unknown[];\n signatures: Signature[];\n transaction_id: TransactionId;\n block_num: number;\n transaction_num: number;\n}\n\nexport interface AccountHistoryEntry {\n trx_id: TransactionId;\n block: number;\n trx_in_block: number;\n op_in_trx: number;\n virtual_op: number;\n timestamp: string;\n op: Operation;\n}\n\nexport interface Ticker {\n latest: string;\n lowest_ask: string;\n highest_bid: string;\n percent_change: string;\n steem_volume: Asset;\n sbd_volume: Asset;\n}\n\nexport interface Volume {\n steem_volume: Asset;\n sbd_volume: Asset;\n}\n\nexport interface TradeHistory {\n date: string;\n current_pays: Asset;\n open_pays: Asset;\n}\n\nexport interface MarketHistory {\n id: number;\n open: string;\n high: string;\n low: string;\n close: string;\n steem_volume: Asset;\n sbd_volume: Asset;\n}\n\nexport interface Bucket {\n bucket_size: number;\n}\n"],"names":["isBytes","a","abytes","b","lengths","aexists","instance","checkFinished","aoutput","out","min","clean","arrays","i","createView","arr","rotr","word","shift","rotl","utf8ToBytes","str","toBytes","data","Hash","createHasher","hashCons","hashC","msg","tmp","setBigUint64","view","byteOffset","value","isLE","_32n","_u32_max","wh","wl","h","l","Chi","c","Maj","HashMD","blockLen","outputLen","padOffset","buffer","len","pos","take","dataView","oview","outLen","state","res","to","length","finished","destroyed","SHA256_IV","SHA512_IV","U32_MASK64","fromBig","n","le","split","lst","Ah","Al","shrSH","_l","s","shrSL","rotrSH","rotrSL","rotrBH","rotrBL","add","Bh","Bl","add3L","Cl","add3H","low","Ch","add4L","Dl","add4H","Dh","add5L","El","add5H","Eh","SHA256_K","SHA256_W","SHA256","A","B","C","D","E","F","G","H","offset","W15","W2","s0","s1","sigma1","T1","T2","K512","u64.split","SHA512_Kh","SHA512_Kl","SHA512_W_H","SHA512_W_L","SHA512","Fh","Fl","Gh","Gl","Hh","Hl","W15h","W15l","s0h","u64.rotrSH","u64.shrSH","s0l","u64.rotrSL","u64.shrSL","W2h","W2l","s1h","u64.rotrBH","s1l","u64.rotrBL","SUMl","u64.add4L","SUMh","u64.add4H","sigma1h","sigma1l","CHIh","CHIl","T1ll","u64.add5L","T1h","u64.add5H","T1l","sigma0h","sigma0l","MAJh","MAJl","u64.add","All","u64.add3L","u64.add3H","sha256","sha512","generateChainId","networkName","hash","ZatteraClient","config","method","params","request","lastError","attempt","controller","timeoutId","response","error","resolve","requests","batchRequest","req","item","owners","start","limit","order","owner","accounts","from","account","comments","author","permlink","trx","availableKeys","signers","signatures","requiredOwner","requiredActive","requiredPosting","requiredOther","maxBlockAge","block","blockNum","id","blockRangeBegin","blockRangeEnd","startTag","query","startEntryId","accountLowerBound","blogAccount","end","bucketSeconds","keys","secp256k1_CURVE","P","N","Gx","Gy","_b","L","L2","err","m","isBig","isStr","u8n","u8fr","buf","padh","pad","bytesToHex","e","_ch","ch","hexToBytes","hex","hl","al","array","ai","hi","n1","n2","toU8","cr","subtle","concatBytes","arrs","r","sum","randomBytes","big","arange","max","M","modN","invert","num","md","x","u","q","apoint","p","Point","koblitz","afield0","afield","agroup","isEven","y","u8of","getPrefix","lift_x","px","py","pz","bytes","head","tail","sliceBytesNumBE","evenY","other","X1","Y1","Z1","X2","Y2","Z2","X1Z2","X2Z1","Y1Z2","Y2Z1","I","X3","Y3","Z3","b3","t0","t1","t2","t3","t4","t5","safe","wNAF","f","d","z","iz","isCompressed","x32b","numTo32b","ap","k","toPrivScalar","doubleScalarMulUns","R","u1","u2","bytesToNumBE","B256","pr","highS","getPublicKey","privKey","Signature$1","Signature","recovery","bit","recoverPublicKey","bits2int","delta","bits2int_modN","signOpts","veriOpts","prepSig","msgh","priv","opts","lowS","extraEntropy","i2o","h1i","h1o","seed","k2sig","kBytes","ik","normS","hmacDrbg","asynchronous","v","NULL","reset","_e","etc","reseed","gen","pred","signAsync","verify","sig","pub","sigg","rs","is","radj","Rb","ir","getSharedSecret","privA","pubB","hashToPrivateKey","_sha","key","msgs","name","W","scalarBits","pwindows","pwindowSize","precompute","points","w","Gpows","ctneg","cnd","comp","pow_2_w","maxNum","mask","shiftBy","wbits","off","offF","offP","isNeg","Rho160","Id160","_","Pi160","idxLR","j","idxL","idxR","shifts160","shiftsL160","idx","shiftsR160","Kl160","Kr160","ripemd_f","group","BUF_160","RIPEMD160","h0","h1","h2","h3","h4","ar","bl","br","cl","dl","dr","el","er","rGroup","hbl","hbr","rl","rr","sl","sr","tl","tr","ripemd160","base","ALPHABET","BASE_MAP","xc","BASE","LEADER","FACTOR","iFACTOR","encode","source","zeroes","pbegin","pend","size","b58","carry","it1","it2","decodeUnsafe","psz","b256","charCode","it3","it4","vch","decode","string","bs58","basex","PrivateKey","wif","decoded","privateKey","checksum","hash1","expectedChecksum","arraysEqual","accountName","password","role","normalized","versioned","result","publicKeyBytes","secp256k1.getPublicKey","PublicKey","messageHash","secp256k1.signAsync","publicKey","secp256k1.getSharedSecret","offsetHash","offsetBigInt","keyBigInt","childKeyHex","childKeyBytes","publicKeyString","prefix","keyString","signature","secp256k1.verify","_offset","recoveryByte","secp256k1.Signature","generateKeys","roles","isWif","isPublicKey","TransactionSerializer","bigValue","byte","writeItem","serializeTransaction","tx","serializer","expirationDate","expirationSeconds","op","serializeOperation","ext","operation","opType","opData","opId","getOperationId","serializeOperationData","opName","serializeSignedTransaction","txBytes","title","needsLen","ofLen","got","u32","overlapBytes","complexOverlapBytes","input","output","wrapCipher","constructor","wrappedCipher","args","nonce","tagl","cipher","checkOutput","fnLength","called","getOutput","expectedLength","onlyAligned","isAligned32","copyBytes","bytesLength","BLOCK_SIZE","POLY","validateKeyLength","mul2","mul","sbox","t","box","invSbox","rotr32_8","rotl32_8","genTtable","fn","T0","T3","T01","T23","sbox2","tableEncoding","tableDecoding","xPowers","expandKeyLE","toClean","k32","Nk","subByte","applySbox","xk","expandKeyDecLE","encKey","apply0123","s2","s3","encrypt","rounds","decrypt","validateBlockDecrypt","validateBlockEncrypt","plaintext","pcks5","dst","remaining","left","validatePCKS","lastByte","padPCKS","tmp32","paddingByte","cbc","iv","o","_out","_iv","n32","ciphertext","ps0","ps1","ps2","ps3","o0","o1","o2","o3","generateNonce","encodeMemo","memo","message","messageBytes","nonceBytes","sharedSecret","combined","encryptionKey","encrypted","aes.cbc","serialized","decodeMemo","_privateKey","decodeMemoWithKey","checksumValid","decrypted","signTransaction","transaction","privateKeys","chainId","txBuffer","chainIdBytes","digest","bufferToHex","verifyTransactionSignatures","txWithoutSigs","publicKeys","sigHex","sigBytes","createTransaction","refBlockNum","refBlockPrefix","expiration","operations","expirationString","cleanHex","Auth","genKeys","roleKey","privateWif","addressPrefix","auths","roleAuths","JsonRpcErrorCode","ListOrder"],"mappings":"AAIA;AASO,SAASA,GAAQC,GAAG;AACvB,SAAOA,aAAa,cAAe,YAAY,OAAOA,CAAC,KAAKA,EAAE,YAAY,SAAS;AACvF;AAOO,SAASC,GAAOC,MAAMC,GAAS;AAClC,MAAI,CAACJ,GAAQG,CAAC;AACV,UAAM,IAAI,MAAM,qBAAqB;AACzC,MAAIC,EAAQ,SAAS,KAAK,CAACA,EAAQ,SAASD,EAAE,MAAM;AAChD,UAAM,IAAI,MAAM,mCAAmCC,IAAU,kBAAkBD,EAAE,MAAM;AAC/F;AASO,SAASE,GAAQC,GAAUC,IAAgB,IAAM;AACpD,MAAID,EAAS;AACT,UAAM,IAAI,MAAM,kCAAkC;AACtD,MAAIC,KAAiBD,EAAS;AAC1B,UAAM,IAAI,MAAM,uCAAuC;AAC/D;AAEO,SAASE,GAAQC,GAAKH,GAAU;AACnCJ,EAAAA,GAAOO,CAAG;AACV,QAAMC,IAAMJ,EAAS;AACrB,MAAIG,EAAI,SAASC;AACb,UAAM,IAAI,MAAM,2DAA2DA,CAAG;AAEtF;A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