@junobuild/core-standalone 3.3.2-next-2025-12-30 → 3.4.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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../../node_modules/@dfinity/principal/src/utils/base32.ts", "../../../../node_modules/@dfinity/principal/src/utils/getCrc.ts", "../../../../node_modules/@noble/hashes/src/crypto.ts", "../../../../node_modules/@noble/hashes/src/utils.ts", "../../../../node_modules/@noble/hashes/src/_md.ts", "../../../../node_modules/@noble/hashes/src/_u64.ts", "../../../../node_modules/@noble/hashes/src/sha2.ts", "../../../../node_modules/@dfinity/principal/src/principal.ts", "../../../../node_modules/@dfinity/agent/src/errors.ts", "../../../../node_modules/@dfinity/candid/src/utils/buffer.ts", "../../../../node_modules/@dfinity/candid/src/utils/bigint-math.ts", "../../../../node_modules/@dfinity/candid/src/utils/leb128.ts", "../../../../node_modules/@dfinity/agent/src/utils/buffer.ts", "../../../../node_modules/@dfinity/agent/src/request_id.ts", "../../../../node_modules/@dfinity/agent/src/constants.ts", "../../../../node_modules/@dfinity/agent/src/auth.ts", "../../../../node_modules/@noble/curves/src/utils.ts", "../../../../node_modules/@noble/curves/src/abstract/modular.ts", "../../../../node_modules/@noble/curves/src/abstract/curve.ts", "../../../../node_modules/@noble/curves/src/abstract/edwards.ts", "../../../../node_modules/@noble/curves/src/ed25519.ts", "../../../../node_modules/@dfinity/agent/src/der.ts", "../../../../node_modules/@dfinity/identity/src/identity/ed25519.ts", "../../../../node_modules/@dfinity/identity/src/identity/ecdsa.ts", "../../../../node_modules/@dfinity/identity/src/identity/partial.ts", "../../../../node_modules/@dfinity/identity/src/identity/delegation.ts", "../../../../node_modules/@icp-sdk/auth/src/client/idle-manager.ts", "../../../../node_modules/idb/build/wrap-idb-value.js", "../../../../node_modules/idb/build/index.js", "../../../../node_modules/@icp-sdk/auth/src/client/db.ts", "../../../../node_modules/@icp-sdk/auth/src/client/storage.ts", "../../../../node_modules/@icp-sdk/auth/src/client/auth-client.ts", "../../src/auth/constants/auth.constants.ts", "../../../../node_modules/@dfinity/utils/src/enums/token.enums.ts", "../../../../node_modules/@dfinity/utils/src/constants/constants.ts", "../../../../node_modules/@dfinity/utils/src/parser/token.ts", "../../../../node_modules/@dfinity/utils/src/services/canister.ts", "../../../../node_modules/@dfinity/utils/src/utils/nullish.utils.ts", "../../../../node_modules/@dfinity/utils/src/services/query.ts", "../../../../node_modules/@dfinity/utils/src/utils/actor.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/agent.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/asserts.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/arrays.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/base32.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/base64.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/crc.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/json.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/crypto.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/date.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/debounce.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/did.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/principal.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/version.utils.ts", "../../src/auth/stores/auth-client.store.ts", "../../src/auth/workers/auth.worker.ts", "../../src/workers/auth.worker.ts"],
4
- "sourcesContent": ["const alphabet = 'abcdefghijklmnopqrstuvwxyz234567';\n\n// Build a lookup table for decoding.\nconst lookupTable: Record<string, number> = Object.create(null);\nfor (let i = 0; i < alphabet.length; i++) {\n lookupTable[alphabet[i]] = i;\n}\n\n// Add aliases for rfc4648.\nlookupTable['0'] = lookupTable.o;\nlookupTable['1'] = lookupTable.i;\n\n/**\n * @param input The Uint8Array to encode.\n * @returns A Base32 string encoding the input.\n */\nexport function base32Encode(input: Uint8Array): string {\n // How many bits will we skip from the first byte.\n let skip = 0;\n // 5 high bits, carry from one byte to the next.\n let bits = 0;\n\n // The output string in base32.\n let output = '';\n\n function encodeByte(byte: number) {\n if (skip < 0) {\n // we have a carry from the previous byte\n bits |= byte >> -skip;\n } else {\n // no carry\n bits = (byte << skip) & 248;\n }\n\n if (skip > 3) {\n // Not enough data to produce a character, get us another one\n skip -= 8;\n return 1;\n }\n\n if (skip < 4) {\n // produce a character\n output += alphabet[bits >> 3];\n skip += 5;\n }\n\n return 0;\n }\n\n for (let i = 0; i < input.length; ) {\n i += encodeByte(input[i]);\n }\n\n return output + (skip < 0 ? alphabet[bits >> 3] : '');\n}\n\n/**\n * @param input The base32 encoded string to decode.\n */\nexport function base32Decode(input: string): Uint8Array {\n // how many bits we have from the previous character.\n let skip = 0;\n // current byte we're producing.\n let byte = 0;\n\n const output = new Uint8Array(((input.length * 4) / 3) | 0);\n let o = 0;\n\n function decodeChar(char: string) {\n // Consume a character from the stream, store\n // the output in this.output. As before, better\n // to use update().\n let val = lookupTable[char.toLowerCase()];\n if (val === undefined) {\n throw new Error(`Invalid character: ${JSON.stringify(char)}`);\n }\n\n // move to the high bits\n val <<= 3;\n byte |= val >>> skip;\n skip += 5;\n\n if (skip >= 8) {\n // We have enough bytes to produce an output\n output[o++] = byte;\n skip -= 8;\n\n if (skip > 0) {\n byte = (val << (5 - skip)) & 255;\n } else {\n byte = 0;\n }\n }\n }\n\n for (const c of input) {\n decodeChar(c);\n }\n\n return output.slice(0, o);\n}\n", "// This file is translated to JavaScript from\n// https://lxp32.github.io/docs/a-simple-example-crc32-calculation/\nconst lookUpTable: Uint32Array = new Uint32Array([\n 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,\n 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,\n 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,\n 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,\n 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,\n 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,\n 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,\n 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,\n 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,\n 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,\n 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,\n 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,\n 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,\n 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,\n 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,\n 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,\n 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,\n 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,\n 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,\n 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,\n 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,\n 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,\n 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,\n 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,\n 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,\n 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,\n 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,\n 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,\n 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,\n 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,\n 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,\n 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,\n]);\n\n/**\n * Calculate the CRC32 of a Uint8Array.\n * @param buf The Uint8Array to calculate the CRC32 of.\n */\nexport function getCrc32(buf: Uint8Array): number {\n let crc = -1;\n\n for (let i = 0; i < buf.length; i++) {\n const byte = buf[i];\n const t = (byte ^ crc) & 0xff;\n crc = lookUpTable[t] ^ (crc >>> 8);\n }\n\n return (crc ^ -1) >>> 0;\n}\n", "/**\n * Internal webcrypto alias.\n * We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n * See utils.ts for details.\n * @module\n */\ndeclare const globalThis: Record<string, any> | undefined;\nexport const crypto: any =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\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\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\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\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) 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/**\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 (): Promise<void> => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== 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 as T1 & T2;\n}\n\n/** Hash interface. */\nexport type IHash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\n\n/** For runtime check if class implements interface */\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n abstract clone(): T;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\n/** Hash function */\nexport type CHash = ReturnType<typeof createHasher>;\n/** Hash function with output */\nexport type CHashO = ReturnType<typeof createOptHasher>;\n/** XOF with output */\nexport type CHashXO = ReturnType<typeof createXOFer>;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher<T extends Hash<T>>(\n hashCons: () => Hash<T>\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash<T>;\n} {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function createOptHasher<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): Hash<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\n\nexport function createXOFer<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): HashXOF<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\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", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { type Input, Hash, abytes, aexists, aoutput, clean, createView, toBytes } from './utils.ts';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD<T extends HashMD<T>> extends Hash<T> {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n super();\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: Input): this {\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) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n", "/**\n * Internal helpers for u64. 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);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false): Uint32Array[] {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));\n\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(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n", "/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [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.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, rotr } from './utils.ts';\n\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\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD<SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n\n constructor(outputLen: number = 32) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\nexport class SHA224 extends SHA256 {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// 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\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\nexport class SHA512 extends HashMD<SHA512> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor(outputLen: number = 64) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // 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 protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nexport class SHA384 extends SHA512 {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\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\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]);\n\nexport class SHA512_224 extends SHA512 {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\nexport class SHA512_256 extends SHA512 {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634.\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: CHash = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash = /* @__PURE__ */ createHasher(() => new SHA224());\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash = /* @__PURE__ */ createHasher(() => new SHA384());\n\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: CHash = /* @__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: CHash = /* @__PURE__ */ createHasher(() => new SHA512_224());\n", "import { base32Decode, base32Encode } from './utils/base32.ts';\nimport { getCrc32 } from './utils/getCrc.ts';\nimport { sha224 } from '@noble/hashes/sha2';\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils';\n\nexport const JSON_KEY_PRINCIPAL = '__principal__';\nconst SELF_AUTHENTICATING_SUFFIX = 2;\nconst ANONYMOUS_SUFFIX = 4;\n\nconst MANAGEMENT_CANISTER_PRINCIPAL_TEXT_STR = 'aaaaa-aa';\n\nexport type JsonnablePrincipal = {\n [JSON_KEY_PRINCIPAL]: string;\n};\n\nexport class Principal {\n public static anonymous(): Principal {\n return new this(new Uint8Array([ANONYMOUS_SUFFIX]));\n }\n\n /**\n * Utility method, returning the principal representing the management canister, decoded from the hex string `'aaaaa-aa'`\n * @returns {Principal} principal of the management canister\n */\n public static managementCanister(): Principal {\n return this.fromText(MANAGEMENT_CANISTER_PRINCIPAL_TEXT_STR);\n }\n\n public static selfAuthenticating(publicKey: Uint8Array): Principal {\n const sha = sha224(publicKey);\n return new this(new Uint8Array([...sha, SELF_AUTHENTICATING_SUFFIX]));\n }\n\n public static from(other: unknown): Principal {\n if (typeof other === 'string') {\n return Principal.fromText(other);\n } else if (Object.getPrototypeOf(other) === Uint8Array.prototype) {\n return new Principal(other as Uint8Array);\n } else if (Principal.isPrincipal(other)) {\n return new Principal(other._arr);\n }\n\n throw new Error(`Impossible to convert ${JSON.stringify(other)} to Principal.`);\n }\n\n public static fromHex(hex: string): Principal {\n return new this(hexToBytes(hex));\n }\n\n public static fromText(text: string): Principal {\n let maybePrincipal = text;\n // If formatted as JSON string, parse it first\n if (text.includes(JSON_KEY_PRINCIPAL)) {\n const obj = JSON.parse(text);\n if (JSON_KEY_PRINCIPAL in obj) {\n maybePrincipal = obj[JSON_KEY_PRINCIPAL];\n }\n }\n\n const canisterIdNoDash = maybePrincipal.toLowerCase().replace(/-/g, '');\n\n let arr = base32Decode(canisterIdNoDash);\n arr = arr.slice(4, arr.length);\n\n const principal = new this(arr);\n if (principal.toText() !== maybePrincipal) {\n throw new Error(\n `Principal \"${principal.toText()}\" does not have a valid checksum (original value \"${maybePrincipal}\" may not be a valid Principal ID).`,\n );\n }\n\n return principal;\n }\n\n public static fromUint8Array(arr: Uint8Array): Principal {\n return new this(arr);\n }\n\n public static isPrincipal(other: unknown): other is Principal {\n return (\n other instanceof Principal ||\n (typeof other === 'object' &&\n other !== null &&\n '_isPrincipal' in other &&\n (other as { _isPrincipal: boolean })['_isPrincipal'] === true &&\n '_arr' in other &&\n (other as { _arr: Uint8Array })['_arr'] instanceof Uint8Array)\n );\n }\n\n public readonly _isPrincipal = true;\n\n protected constructor(private _arr: Uint8Array) {}\n\n public isAnonymous(): boolean {\n return this._arr.byteLength === 1 && this._arr[0] === ANONYMOUS_SUFFIX;\n }\n\n public toUint8Array(): Uint8Array {\n return this._arr;\n }\n\n public toHex(): string {\n return bytesToHex(this._arr).toUpperCase();\n }\n\n public toText(): string {\n const checksumArrayBuf = new ArrayBuffer(4);\n const view = new DataView(checksumArrayBuf);\n view.setUint32(0, getCrc32(this._arr));\n const checksum = new Uint8Array(checksumArrayBuf);\n\n const array = new Uint8Array([...checksum, ...this._arr]);\n\n const result = base32Encode(array);\n const matches = result.match(/.{1,5}/g);\n if (!matches) {\n // This should only happen if there's no character, which is unreachable.\n throw new Error();\n }\n return matches.join('-');\n }\n\n public toString(): string {\n return this.toText();\n }\n\n /**\n * Serializes to JSON\n * @returns {JsonnablePrincipal} a JSON object with a single key, {@link JSON_KEY_PRINCIPAL}, whose value is the principal as a string\n */\n public toJSON(): JsonnablePrincipal {\n return { [JSON_KEY_PRINCIPAL]: this.toText() };\n }\n\n /**\n * Utility method taking a Principal to compare against. Used for determining canister ranges in certificate verification\n * @param {Principal} other - a {@link Principal} to compare\n * @returns {'lt' | 'eq' | 'gt'} `'lt' | 'eq' | 'gt'` a string, representing less than, equal to, or greater than\n */\n public compareTo(other: Principal): 'lt' | 'eq' | 'gt' {\n for (let i = 0; i < Math.min(this._arr.length, other._arr.length); i++) {\n if (this._arr[i] < other._arr[i]) return 'lt';\n else if (this._arr[i] > other._arr[i]) return 'gt';\n }\n // Here, at least one principal is a prefix of the other principal (they could be the same)\n if (this._arr.length < other._arr.length) return 'lt';\n if (this._arr.length > other._arr.length) return 'gt';\n return 'eq';\n }\n\n /**\n * Utility method checking whether a provided Principal is less than or equal to the current one using the {@link Principal.compareTo} method\n * @param other a {@link Principal} to compare\n * @returns {boolean} boolean\n */\n public ltEq(other: Principal): boolean {\n const cmp = this.compareTo(other);\n return cmp == 'lt' || cmp == 'eq';\n }\n\n /**\n * Utility method checking whether a provided Principal is greater than or equal to the current one using the {@link Principal.compareTo} method\n * @param other a {@link Principal} to compare\n * @returns {boolean} boolean\n */\n public gtEq(other: Principal): boolean {\n const cmp = this.compareTo(other);\n return cmp == 'gt' || cmp == 'eq';\n }\n}\n", "import { Principal } from '@dfinity/principal';\nimport {\n type HttpDetailsResponse,\n type NodeSignature,\n type ReplicaRejectCode,\n} from './agent/api.ts';\nimport { type RequestId } from './request_id.ts';\nimport { type Expiry, type RequestStatusResponseStatus } from './agent/http/index.ts';\nimport { type HttpHeaderField } from './agent/http/types.ts';\nimport { LookupPathStatus, LookupSubtreeStatus } from './certificate.ts';\nimport { bytesToHex } from '@noble/hashes/utils';\n\nexport enum ErrorKindEnum {\n Trust = 'Trust',\n Protocol = 'Protocol',\n Reject = 'Reject',\n Transport = 'Transport',\n External = 'External',\n Limit = 'Limit',\n Input = 'Input',\n Unknown = 'Unknown',\n}\n\nexport type RequestContext = {\n requestId?: RequestId;\n senderPubKey: Uint8Array;\n senderSignature: Uint8Array;\n ingressExpiry: Expiry;\n};\n\nexport type CallContext = {\n canisterId: Principal;\n methodName: string;\n httpDetails: HttpDetailsResponse;\n};\n\nabstract class ErrorCode {\n public requestContext?: RequestContext;\n public callContext?: CallContext;\n\n constructor(public readonly isCertified: boolean = false) {}\n\n public abstract toErrorMessage(): string;\n\n public toString(): string {\n let errorMessage = this.toErrorMessage();\n if (this.requestContext) {\n errorMessage +=\n `\\nRequest context:\\n` +\n ` Request ID (hex): ${this.requestContext.requestId ? bytesToHex(this.requestContext.requestId) : 'undefined'}\\n` +\n ` Sender pubkey (hex): ${bytesToHex(this.requestContext.senderPubKey)}\\n` +\n ` Sender signature (hex): ${bytesToHex(this.requestContext.senderSignature)}\\n` +\n ` Ingress expiry: ${this.requestContext.ingressExpiry.toString()}`;\n }\n if (this.callContext) {\n errorMessage +=\n `\\nCall context:\\n` +\n ` Canister ID: ${this.callContext.canisterId.toText()}\\n` +\n ` Method name: ${this.callContext.methodName}\\n` +\n ` HTTP details: ${JSON.stringify(this.callContext.httpDetails, null, 2)}`;\n }\n return errorMessage;\n }\n}\n\n/**\n * An error that happens in the Agent. This is the root of all errors and should be used\n * everywhere in the Agent code (this package).\n *\n * To know if the error is certified, use the `isCertified` getter.\n */\nexport class AgentError extends Error {\n public name = 'AgentError';\n // override the Error.cause property\n public readonly cause: { code: ErrorCode; kind: ErrorKindEnum };\n\n get code(): ErrorCode {\n return this.cause.code;\n }\n set code(code: ErrorCode) {\n this.cause.code = code;\n }\n\n get kind(): ErrorKindEnum {\n return this.cause.kind;\n }\n set kind(kind: ErrorKindEnum) {\n this.cause.kind = kind;\n }\n\n /**\n * Reads the `isCertified` property of the underlying error code.\n * @returns `true` if the error is certified, `false` otherwise.\n */\n get isCertified(): boolean {\n return this.code.isCertified;\n }\n\n constructor(code: ErrorCode, kind: ErrorKindEnum) {\n super(code.toString());\n this.cause = { code, kind };\n Object.setPrototypeOf(this, AgentError.prototype);\n }\n\n public hasCode<C extends ErrorCode>(code: new (...args: never[]) => C): boolean {\n return this.code instanceof code;\n }\n\n public toString(): string {\n return `${this.name} (${this.kind}): ${this.message}`;\n }\n}\n\nclass ErrorKind extends AgentError {\n public static fromCode<C extends ErrorCode, E extends ErrorKind>(\n this: new (code: C) => E,\n code: C,\n ): E {\n return new this(code);\n }\n}\n\nexport class TrustError extends ErrorKind {\n public name = 'TrustError';\n\n constructor(code: ErrorCode) {\n super(code, ErrorKindEnum.Trust);\n Object.setPrototypeOf(this, TrustError.prototype);\n }\n}\n\nexport class ProtocolError extends ErrorKind {\n public name = 'ProtocolError';\n\n constructor(code: ErrorCode) {\n super(code, ErrorKindEnum.Protocol);\n Object.setPrototypeOf(this, ProtocolError.prototype);\n }\n}\n\nexport class RejectError extends ErrorKind {\n public name = 'RejectError';\n\n constructor(code: ErrorCode) {\n super(code, ErrorKindEnum.Reject);\n Object.setPrototypeOf(this, RejectError.prototype);\n }\n}\n\nexport class TransportError extends ErrorKind {\n public name = 'TransportError';\n\n constructor(code: ErrorCode) {\n super(code, ErrorKindEnum.Transport);\n Object.setPrototypeOf(this, TransportError.prototype);\n }\n}\n\nexport class ExternalError extends ErrorKind {\n public name = 'ExternalError';\n\n constructor(code: ErrorCode) {\n super(code, ErrorKindEnum.External);\n Object.setPrototypeOf(this, ExternalError.prototype);\n }\n}\n\nexport class LimitError extends ErrorKind {\n public name = 'LimitError';\n\n constructor(code: ErrorCode) {\n super(code, ErrorKindEnum.Limit);\n Object.setPrototypeOf(this, LimitError.prototype);\n }\n}\n\nexport class InputError extends ErrorKind {\n public name = 'InputError';\n\n constructor(code: ErrorCode) {\n super(code, ErrorKindEnum.Input);\n Object.setPrototypeOf(this, InputError.prototype);\n }\n}\n\nexport class UnknownError extends ErrorKind {\n public name = 'UnknownError';\n\n constructor(code: ErrorCode) {\n super(code, ErrorKindEnum.Unknown);\n Object.setPrototypeOf(this, UnknownError.prototype);\n }\n}\n\nexport class CertificateVerificationErrorCode extends ErrorCode {\n public name = 'CertificateVerificationErrorCode';\n\n constructor(\n public readonly reason: string,\n public readonly error?: unknown,\n ) {\n super();\n Object.setPrototypeOf(this, CertificateVerificationErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n let errorMessage = this.reason;\n if (this.error) {\n errorMessage += `: ${formatUnknownError(this.error)}`;\n }\n return `Certificate verification error: \"${errorMessage}\"`;\n }\n}\n\nexport class CertificateTimeErrorCode extends ErrorCode {\n public name = 'CertificateTimeErrorCode';\n\n constructor(\n public readonly maxAgeInMinutes: number,\n public readonly certificateTime: Date,\n public readonly currentTime: Date,\n public readonly timeDiffMsecs: number,\n public readonly ageType: 'past' | 'future',\n ) {\n super();\n Object.setPrototypeOf(this, CertificateTimeErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Certificate is signed more than ${this.maxAgeInMinutes} minutes in the ${this.ageType}. Certificate time: ${this.certificateTime.toISOString()} Current time: ${this.currentTime.toISOString()} Clock drift: ${this.timeDiffMsecs}ms`;\n }\n}\n\nexport class CertificateHasTooManyDelegationsErrorCode extends ErrorCode {\n public name = 'CertificateHasTooManyDelegationsErrorCode';\n\n constructor() {\n super();\n Object.setPrototypeOf(this, CertificateHasTooManyDelegationsErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return 'Certificate has too many delegations';\n }\n}\n\nexport class CertificateNotAuthorizedErrorCode extends ErrorCode {\n public name = 'CertificateNotAuthorizedErrorCode';\n\n constructor(\n public readonly canisterId: Principal,\n public readonly subnetId: Principal,\n ) {\n super();\n Object.setPrototypeOf(this, CertificateNotAuthorizedErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `The certificate contains a delegation that does not include the canister ${this.canisterId.toText()} in the canister_ranges field. Subnet ID: ${this.subnetId.toText()}`;\n }\n}\n\nexport class LookupErrorCode extends ErrorCode {\n public name = 'LookupErrorCode';\n\n constructor(\n public readonly message: string,\n public readonly lookupStatus: LookupPathStatus | LookupSubtreeStatus,\n ) {\n super();\n Object.setPrototypeOf(this, LookupErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `${this.message}. Lookup status: ${this.lookupStatus}`;\n }\n}\n\nexport class MalformedLookupFoundValueErrorCode extends ErrorCode {\n public name = 'MalformedLookupFoundValueErrorCode';\n\n constructor(public readonly message: string) {\n super();\n Object.setPrototypeOf(this, MalformedLookupFoundValueErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return this.message;\n }\n}\n\nexport class MissingLookupValueErrorCode extends ErrorCode {\n public name = 'MissingLookupValueErrorCode';\n\n constructor(public readonly message: string) {\n super();\n Object.setPrototypeOf(this, MissingLookupValueErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return this.message;\n }\n}\n\nexport class DerKeyLengthMismatchErrorCode extends ErrorCode {\n public name = 'DerKeyLengthMismatchErrorCode';\n\n constructor(\n public readonly expectedLength: number,\n public readonly actualLength: number,\n ) {\n super();\n Object.setPrototypeOf(this, DerKeyLengthMismatchErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `BLS DER-encoded public key must be ${this.expectedLength} bytes long, but is ${this.actualLength} bytes long`;\n }\n}\n\nexport class DerPrefixMismatchErrorCode extends ErrorCode {\n public name = 'DerPrefixMismatchErrorCode';\n\n constructor(\n public readonly expectedPrefix: Uint8Array,\n public readonly actualPrefix: Uint8Array,\n ) {\n super();\n Object.setPrototypeOf(this, DerPrefixMismatchErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `BLS DER-encoded public key is invalid. Expected the following prefix: ${bytesToHex(this.expectedPrefix)}, but got ${bytesToHex(this.actualPrefix)}`;\n }\n}\n\nexport class DerDecodeLengthMismatchErrorCode extends ErrorCode {\n public name = 'DerDecodeLengthMismatchErrorCode';\n\n constructor(\n public readonly expectedLength: number,\n public readonly actualLength: number,\n ) {\n super();\n Object.setPrototypeOf(this, DerDecodeLengthMismatchErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `DER payload mismatch: Expected length ${this.expectedLength}, actual length: ${this.actualLength}`;\n }\n}\n\nexport class DerDecodeErrorCode extends ErrorCode {\n public name = 'DerDecodeErrorCode';\n\n constructor(public readonly error: string) {\n super();\n Object.setPrototypeOf(this, DerDecodeErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Failed to decode DER: ${this.error}`;\n }\n}\n\nexport class DerEncodeErrorCode extends ErrorCode {\n public name = 'DerEncodeErrorCode';\n\n constructor(public readonly error: string) {\n super();\n Object.setPrototypeOf(this, DerEncodeErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Failed to encode DER: ${this.error}`;\n }\n}\n\nexport class CborDecodeErrorCode extends ErrorCode {\n public name = 'CborDecodeErrorCode';\n\n constructor(\n public readonly error: unknown,\n public readonly input: Uint8Array,\n ) {\n super();\n Object.setPrototypeOf(this, CborDecodeErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Failed to decode CBOR: ${formatUnknownError(this.error)}, input: ${bytesToHex(this.input)}`;\n }\n}\n\nexport class CborEncodeErrorCode extends ErrorCode {\n public name = 'CborEncodeErrorCode';\n\n constructor(\n public readonly error: unknown,\n public readonly value: unknown,\n ) {\n super();\n Object.setPrototypeOf(this, CborEncodeErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Failed to encode CBOR: ${formatUnknownError(this.error)}, input: ${this.value}`;\n }\n}\n\nexport class HexDecodeErrorCode extends ErrorCode {\n public name = 'HexDecodeErrorCode';\n\n constructor(public readonly error: string) {\n super();\n Object.setPrototypeOf(this, HexDecodeErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Failed to decode hex: ${this.error}`;\n }\n}\n\nexport class TimeoutWaitingForResponseErrorCode extends ErrorCode {\n public name = 'TimeoutWaitingForResponseErrorCode';\n\n constructor(\n public readonly message: string,\n public readonly requestId?: RequestId,\n public readonly status?: RequestStatusResponseStatus,\n ) {\n super();\n Object.setPrototypeOf(this, TimeoutWaitingForResponseErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n let errorMessage = `${this.message}\\n`;\n if (this.requestId) {\n errorMessage += ` Request ID: ${bytesToHex(this.requestId)}\\n`;\n }\n if (this.status) {\n errorMessage += ` Request status: ${this.status}\\n`;\n }\n return errorMessage;\n }\n}\n\nexport class CertificateOutdatedErrorCode extends ErrorCode {\n public name = 'CertificateOutdatedErrorCode';\n\n constructor(\n public readonly maxIngressExpiryInMinutes: number,\n public readonly requestId: RequestId,\n public readonly retryTimes?: number,\n ) {\n super();\n Object.setPrototypeOf(this, CertificateOutdatedErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n let errorMessage = `Certificate is stale (over ${this.maxIngressExpiryInMinutes} minutes). Is the computer's clock synchronized?\\n Request ID: ${bytesToHex(this.requestId)}\\n`;\n if (this.retryTimes !== undefined) {\n errorMessage += ` Retried ${this.retryTimes} times.`;\n }\n return errorMessage;\n }\n}\n\nexport class CertifiedRejectErrorCode extends ErrorCode {\n public name = 'CertifiedRejectErrorCode';\n\n constructor(\n public readonly requestId: RequestId,\n public readonly rejectCode: ReplicaRejectCode,\n public readonly rejectMessage: string,\n public readonly rejectErrorCode: string | undefined,\n ) {\n super(true);\n Object.setPrototypeOf(this, CertifiedRejectErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return (\n `The replica returned a rejection error:\\n` +\n ` Request ID: ${bytesToHex(this.requestId)}\\n` +\n ` Reject code: ${this.rejectCode}\\n` +\n ` Reject text: ${this.rejectMessage}\\n` +\n ` Error code: ${this.rejectErrorCode}\\n`\n );\n }\n}\n\nexport class UncertifiedRejectErrorCode extends ErrorCode {\n public name = 'UncertifiedRejectErrorCode';\n\n constructor(\n public readonly requestId: RequestId,\n public readonly rejectCode: ReplicaRejectCode,\n public readonly rejectMessage: string,\n public readonly rejectErrorCode: string | undefined,\n public readonly signatures: NodeSignature[] | undefined,\n ) {\n super();\n Object.setPrototypeOf(this, UncertifiedRejectErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return (\n `The replica returned a rejection error:\\n` +\n ` Request ID: ${bytesToHex(this.requestId)}\\n` +\n ` Reject code: ${this.rejectCode}\\n` +\n ` Reject text: ${this.rejectMessage}\\n` +\n ` Error code: ${this.rejectErrorCode}\\n`\n );\n }\n}\n\nexport class UncertifiedRejectUpdateErrorCode extends ErrorCode {\n public name = 'UncertifiedRejectUpdateErrorCode';\n\n constructor(\n public readonly requestId: RequestId,\n public readonly rejectCode: ReplicaRejectCode,\n public readonly rejectMessage: string,\n public readonly rejectErrorCode: string | undefined,\n ) {\n super();\n Object.setPrototypeOf(this, UncertifiedRejectUpdateErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return (\n `The replica returned a rejection error:\\n` +\n ` Request ID: ${bytesToHex(this.requestId)}\\n` +\n ` Reject code: ${this.rejectCode}\\n` +\n ` Reject text: ${this.rejectMessage}\\n` +\n ` Error code: ${this.rejectErrorCode}\\n`\n );\n }\n}\n\nexport class RequestStatusDoneNoReplyErrorCode extends ErrorCode {\n public name = 'RequestStatusDoneNoReplyErrorCode';\n\n constructor(public readonly requestId: RequestId) {\n super();\n Object.setPrototypeOf(this, RequestStatusDoneNoReplyErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return (\n `Call was marked as done but we never saw the reply:\\n` +\n ` Request ID: ${bytesToHex(this.requestId)}\\n`\n );\n }\n}\n\nexport class MissingRootKeyErrorCode extends ErrorCode {\n public name = 'MissingRootKeyErrorCode';\n\n constructor(public readonly shouldFetchRootKey?: boolean) {\n super();\n Object.setPrototypeOf(this, MissingRootKeyErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n if (this.shouldFetchRootKey === undefined) {\n return 'Agent is missing root key';\n }\n return `Agent is missing root key and the shouldFetchRootKey value is set to ${this.shouldFetchRootKey}. The root key should only be unknown if you are in local development. Otherwise you should avoid fetching and use the default IC Root Key or the known root key of your environment.`;\n }\n}\n\nexport class HashValueErrorCode extends ErrorCode {\n public name = 'HashValueErrorCode';\n\n constructor(public readonly value: unknown) {\n super();\n Object.setPrototypeOf(this, HashValueErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Attempt to hash a value of unsupported type: ${this.value}`;\n }\n}\n\nexport class HttpDefaultFetchErrorCode extends ErrorCode {\n public name = 'HttpDefaultFetchErrorCode';\n\n constructor(public readonly error: string) {\n super();\n Object.setPrototypeOf(this, HttpDefaultFetchErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return this.error;\n }\n}\n\nexport class IdentityInvalidErrorCode extends ErrorCode {\n public name = 'IdentityInvalidErrorCode';\n\n constructor() {\n super();\n Object.setPrototypeOf(this, IdentityInvalidErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return \"This identity has expired due this application's security policy. Please refresh your authentication.\";\n }\n}\n\nexport class IngressExpiryInvalidErrorCode extends ErrorCode {\n public name = 'IngressExpiryInvalidErrorCode';\n\n constructor(\n public readonly message: string,\n public readonly providedIngressExpiryInMinutes: number,\n ) {\n super();\n Object.setPrototypeOf(this, IngressExpiryInvalidErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `${this.message}. Provided ingress expiry time is ${this.providedIngressExpiryInMinutes} minutes.`;\n }\n}\n\nexport class CreateHttpAgentErrorCode extends ErrorCode {\n public name = 'CreateHttpAgentErrorCode';\n\n constructor() {\n super();\n Object.setPrototypeOf(this, CreateHttpAgentErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return 'Failed to create agent from provided agent';\n }\n}\n\nexport class MalformedSignatureErrorCode extends ErrorCode {\n public name = 'MalformedSignatureErrorCode';\n\n constructor(public readonly error: string) {\n super();\n Object.setPrototypeOf(this, MalformedSignatureErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Query response contained a malformed signature: ${this.error}`;\n }\n}\n\nexport class MissingSignatureErrorCode extends ErrorCode {\n public name = 'MissingSignatureErrorCode';\n\n constructor() {\n super();\n Object.setPrototypeOf(this, MissingSignatureErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return 'Query response did not contain any node signatures';\n }\n}\n\nexport class MalformedPublicKeyErrorCode extends ErrorCode {\n public name = 'MalformedPublicKeyErrorCode';\n\n constructor() {\n super();\n Object.setPrototypeOf(this, MalformedPublicKeyErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return 'Read state response contained a malformed public key';\n }\n}\n\nexport class QuerySignatureVerificationFailedErrorCode extends ErrorCode {\n public name = 'QuerySignatureVerificationFailedErrorCode';\n\n constructor(public readonly nodeId: string) {\n super();\n Object.setPrototypeOf(this, QuerySignatureVerificationFailedErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Query signature verification failed. Node ID: ${this.nodeId}`;\n }\n}\n\nexport class UnexpectedErrorCode extends ErrorCode {\n public name = 'UnexpectedErrorCode';\n\n constructor(public readonly error: unknown) {\n super();\n Object.setPrototypeOf(this, UnexpectedErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Unexpected error: ${formatUnknownError(this.error)}`;\n }\n}\n\nexport class HashTreeDecodeErrorCode extends ErrorCode {\n public name = 'HashTreeDecodeErrorCode';\n\n constructor(public readonly error: string) {\n super();\n Object.setPrototypeOf(this, HashTreeDecodeErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Failed to decode certificate: ${this.error}`;\n }\n}\n\nexport class HttpErrorCode extends ErrorCode {\n public name = 'HttpErrorCode';\n\n constructor(\n public readonly status: number,\n public readonly statusText: string,\n public readonly headers: HttpHeaderField[],\n public readonly bodyText?: string,\n ) {\n super();\n Object.setPrototypeOf(this, HttpErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n let errorMessage =\n 'HTTP request failed:\\n' +\n ` Status: ${this.status} (${this.statusText})\\n` +\n ` Headers: ${JSON.stringify(this.headers)}\\n`;\n if (this.bodyText) {\n errorMessage += ` Body: ${this.bodyText}\\n`;\n }\n return errorMessage;\n }\n}\n\nexport class HttpV3ApiNotSupportedErrorCode extends ErrorCode {\n public name = 'HttpV3ApiNotSupportedErrorCode';\n\n constructor() {\n super();\n Object.setPrototypeOf(this, HttpV3ApiNotSupportedErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return 'HTTP request failed: v3 API is not supported';\n }\n}\n\nexport class HttpFetchErrorCode extends ErrorCode {\n public name = 'HttpFetchErrorCode';\n\n constructor(public readonly error: unknown) {\n super();\n Object.setPrototypeOf(this, HttpFetchErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Failed to fetch HTTP request: ${formatUnknownError(this.error)}`;\n }\n}\n\nexport class MissingCanisterIdErrorCode extends ErrorCode {\n public name = 'MissingCanisterIdErrorCode';\n\n constructor(public readonly receivedCanisterId: unknown) {\n super();\n Object.setPrototypeOf(this, MissingCanisterIdErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Canister ID is required, but received ${typeof this.receivedCanisterId} instead. If you are using automatically generated declarations, this may be because your application is not setting the canister ID in process.env correctly.`;\n }\n}\n\nexport class InvalidReadStateRequestErrorCode extends ErrorCode {\n public name = 'InvalidReadStateRequestErrorCode';\n\n constructor(public readonly request: unknown) {\n super();\n Object.setPrototypeOf(this, InvalidReadStateRequestErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Invalid read state request: ${this.request}`;\n }\n}\n\nexport class ExpiryJsonDeserializeErrorCode extends ErrorCode {\n public name = 'ExpiryJsonDeserializeErrorCode';\n\n constructor(public readonly error: string) {\n super();\n Object.setPrototypeOf(this, ExpiryJsonDeserializeErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Failed to deserialize expiry: ${this.error}`;\n }\n}\n\nexport class InvalidRootKeyErrorCode extends ErrorCode {\n public name = 'InvalidRootKeyErrorCode';\n\n constructor(\n public readonly rootKey: Uint8Array,\n public readonly expectedLength: number,\n ) {\n super();\n Object.setPrototypeOf(this, InvalidRootKeyErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Invalid root key. Expected length: ${this.expectedLength}, actual length: ${this.rootKey.length}`;\n }\n}\n\nexport class MissingCookieErrorCode extends ErrorCode {\n public name = 'MissingCookieErrorCode';\n\n constructor(public readonly expectedCookieName: string) {\n super();\n Object.setPrototypeOf(this, MissingCookieErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Cookie '${this.expectedCookieName}' not found`;\n }\n}\n\nexport class EmptyCookieErrorCode extends ErrorCode {\n public name = 'EmptyCookieErrorCode';\n\n constructor(public readonly expectedCookieName: string) {\n super();\n Object.setPrototypeOf(this, EmptyCookieErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Cookie '${this.expectedCookieName}' is empty`;\n }\n}\n\nfunction formatUnknownError(error: unknown): string {\n if (error instanceof Error) {\n return error.stack ?? error.message;\n }\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n}\n\n/**\n * Special error used to indicate that a code path is unreachable.\n *\n * For internal use only.\n */\nexport const UNREACHABLE_ERROR = new Error('unreachable');\n", "/**\n * Concatenate multiple Uint8Arrays.\n * @param uint8Arrays The Uint8Arrays to concatenate.\n */\nexport function concat(...uint8Arrays: Uint8Array[]): Uint8Array {\n const result = new Uint8Array(uint8Arrays.reduce((acc, curr) => acc + curr.byteLength, 0));\n let index = 0;\n for (const b of uint8Arrays) {\n result.set(b, index);\n index += b.byteLength;\n }\n return result;\n}\n\n/**\n * A class that abstracts a pipe-like Uint8Array.\n */\nexport class PipeArrayBuffer {\n /**\n * The reading view. It's a sliding window as we read and write, pointing to the buffer.\n * @private\n */\n private _view: Uint8Array;\n\n /**\n * Save a checkpoint of the reading view (for backtracking)\n */\n public save(): Uint8Array {\n return this._view;\n }\n\n /**\n * Restore a checkpoint of the reading view (for backtracking)\n * @param checkPoint a previously saved checkpoint\n */\n public restore(checkPoint: Uint8Array) {\n if (!(checkPoint instanceof Uint8Array)) {\n throw new Error('Checkpoint must be a Uint8Array');\n }\n this._view = checkPoint;\n }\n\n /**\n * The actual buffer containing the bytes.\n * @private\n */\n private _buffer: Uint8Array;\n\n /**\n * Creates a new instance of a pipe\n * @param buffer an optional buffer to start with\n * @param length an optional amount of bytes to use for the length.\n */\n constructor(buffer?: Uint8Array, length = buffer?.byteLength || 0) {\n if (buffer && !(buffer instanceof Uint8Array)) {\n try {\n buffer = uint8FromBufLike(buffer);\n } catch {\n throw new Error('Buffer must be a Uint8Array');\n }\n }\n if (length < 0 || !Number.isInteger(length)) {\n throw new Error('Length must be a non-negative integer');\n }\n if (buffer && length > buffer.byteLength) {\n throw new Error('Length cannot exceed buffer length');\n }\n this._buffer = buffer || new Uint8Array(0);\n this._view = new Uint8Array(this._buffer.buffer, 0, length);\n }\n\n get buffer(): Uint8Array {\n // Return a copy of the buffer.\n return this._view.slice();\n }\n\n get byteLength(): number {\n return this._view.byteLength;\n }\n\n /**\n * Read `num` number of bytes from the front of the pipe.\n * @param num The number of bytes to read.\n */\n public read(num: number): Uint8Array {\n const result = this._view.subarray(0, num);\n this._view = this._view.subarray(num);\n return result.slice();\n }\n\n public readUint8(): number | undefined {\n if (this._view.byteLength === 0) {\n return undefined;\n }\n const result = this._view[0];\n this._view = this._view.subarray(1);\n return result;\n }\n\n /**\n * Write a buffer to the end of the pipe.\n * @param buf The bytes to write.\n */\n public write(buf: Uint8Array): void {\n if (!(buf instanceof Uint8Array)) {\n throw new Error('Buffer must be a Uint8Array');\n }\n const offset = this._view.byteLength;\n if (this._view.byteOffset + this._view.byteLength + buf.byteLength >= this._buffer.byteLength) {\n // Alloc grow the view to include the new bytes.\n this.alloc(buf.byteLength);\n } else {\n // Update the view to include the new bytes.\n this._view = new Uint8Array(\n this._buffer.buffer,\n this._view.byteOffset,\n this._view.byteLength + buf.byteLength,\n );\n }\n\n this._view.set(buf, offset);\n }\n\n /**\n * Whether or not there is more data to read from the buffer\n */\n public get end(): boolean {\n return this._view.byteLength === 0;\n }\n\n /**\n * Allocate a fixed amount of memory in the buffer. This does not affect the view.\n * @param amount A number of bytes to add to the buffer.\n */\n public alloc(amount: number) {\n if (amount <= 0 || !Number.isInteger(amount)) {\n throw new Error('Amount must be a positive integer');\n }\n // Add a little bit of exponential growth.\n const b = new Uint8Array(((this._buffer.byteLength + amount) * 1.2) | 0);\n const v = new Uint8Array(b.buffer, 0, this._view.byteLength + amount);\n v.set(this._view);\n this._buffer = b;\n this._view = v;\n }\n}\n\n/**\n * Returns a true Uint8Array from an ArrayBufferLike object.\n * @param bufLike a buffer-like object\n * @returns Uint8Array\n */\nexport function uint8FromBufLike(\n bufLike:\n | ArrayBuffer\n | Uint8Array\n | DataView\n | ArrayBufferView\n | ArrayBufferLike\n | [number]\n | number[]\n | { buffer: ArrayBuffer },\n): Uint8Array {\n if (!bufLike) {\n throw new Error('Input cannot be null or undefined');\n }\n\n if (bufLike instanceof Uint8Array) {\n return bufLike;\n }\n if (bufLike instanceof ArrayBuffer) {\n return new Uint8Array(bufLike);\n }\n if (Array.isArray(bufLike)) {\n return new Uint8Array(bufLike);\n }\n if ('buffer' in bufLike) {\n return uint8FromBufLike(bufLike.buffer);\n }\n return new Uint8Array(bufLike);\n}\n\n/**\n *\n * @param u1 uint8Array 1\n * @param u2 uint8Array 2\n * @returns number - negative if u1 < u2, positive if u1 > u2, 0 if u1 === u2\n */\nexport function compare(u1: Uint8Array, u2: Uint8Array): number {\n if (u1.byteLength !== u2.byteLength) {\n return u1.byteLength - u2.byteLength;\n }\n for (let i = 0; i < u1.length; i++) {\n if (u1[i] !== u2[i]) {\n return u1[i] - u2[i];\n }\n }\n return 0;\n}\n\n/**\n * Checks two uint8Arrays for equality.\n * @param u1 uint8Array 1\n * @param u2 uint8Array 2\n * @returns boolean\n */\nexport function uint8Equals(u1: Uint8Array, u2: Uint8Array): boolean {\n return compare(u1, u2) === 0;\n}\n\n/**\n * Helpers to convert a Uint8Array to a DataView.\n * @param uint8 Uint8Array\n * @returns DataView\n */\nexport function uint8ToDataView(uint8: Uint8Array): DataView {\n if (!(uint8 instanceof Uint8Array)) {\n throw new Error('Input must be a Uint8Array');\n }\n return new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);\n}\n", "/**\n * Equivalent to `Math.log2(n)` with support for `BigInt` values\n * @param n bigint or integer\n * @returns integer\n */\nexport function ilog2(n: bigint | number): number {\n const nBig = BigInt(n);\n if (n <= 0) {\n throw new RangeError('Input must be positive');\n }\n return nBig.toString(2).length - 1;\n}\n\n/**\n * Equivalent to `2 ** n` with support for `BigInt` values\n * (necessary for browser preprocessors which replace the `**` operator with `Math.pow`)\n * @param n bigint or integer\n * @returns bigint\n */\nexport function iexp2(n: bigint | number): bigint {\n const nBig = BigInt(n);\n if (n < 0) {\n throw new RangeError('Input must be non-negative');\n }\n return BigInt(1) << nBig;\n}\n", "// Note: this file uses buffer-pipe, which on Node only, uses the Node Buffer\n// implementation, which isn't compatible with the NPM buffer package\n// which we use everywhere else. This means that we have to transform\n// one into the other, hence why every function that returns a Buffer\n// actually return `new Buffer(pipe.buffer)`.\n// TODO: The best solution would be to have our own buffer type around\n// Uint8Array which is standard.\nimport { PipeArrayBuffer as Pipe } from './buffer.ts';\nimport { ilog2 } from './bigint-math.ts';\n\nfunction eob(): never {\n throw new Error('unexpected end of buffer');\n}\n\n/**\n *\n * @param pipe Pipe from buffer-pipe\n * @param num number\n * @returns Uint8Array\n */\nexport function safeRead(pipe: Pipe, num: number): Uint8Array {\n if (pipe.byteLength < num) {\n eob();\n }\n return pipe.read(num);\n}\n\n/**\n * @param pipe - PipeArrayBuffer simulating buffer-pipe api\n */\nexport function safeReadUint8(pipe: Pipe): number {\n const byte = pipe.readUint8();\n if (byte === undefined) {\n eob();\n }\n return byte;\n}\n\n/**\n * Encode a positive number (or bigint) into a Buffer. The number will be floored to the\n * nearest integer.\n * @param value The number to encode.\n */\nexport function lebEncode(value: bigint | number): Uint8Array {\n if (typeof value === 'number') {\n value = BigInt(value);\n }\n\n if (value < BigInt(0)) {\n throw new Error('Cannot leb encode negative values.');\n }\n\n const byteLength = (value === BigInt(0) ? 0 : ilog2(value)) + 1;\n const pipe = new Pipe(new Uint8Array(byteLength), 0);\n while (true) {\n const i = Number(value & BigInt(0x7f));\n value /= BigInt(0x80);\n if (value === BigInt(0)) {\n pipe.write(new Uint8Array([i]));\n break;\n } else {\n pipe.write(new Uint8Array([i | 0x80]));\n }\n }\n\n return pipe.buffer;\n}\n\n/**\n * Decode a leb encoded buffer into a bigint. The number will always be positive (does not\n * support signed leb encoding).\n * @param pipe A Buffer containing the leb encoded bits.\n */\nexport function lebDecode(pipe: Pipe): bigint {\n let weight = BigInt(1);\n let value = BigInt(0);\n let byte;\n\n do {\n byte = safeReadUint8(pipe);\n value += BigInt(byte & 0x7f).valueOf() * weight;\n weight *= BigInt(128);\n } while (byte >= 0x80);\n\n return value;\n}\n\n/**\n * Encode a number (or bigint) into a Buffer, with support for negative numbers. The number\n * will be floored to the nearest integer.\n * @param value The number to encode.\n */\nexport function slebEncode(value: bigint | number): Uint8Array {\n if (typeof value === 'number') {\n value = BigInt(value);\n }\n\n const isNeg = value < BigInt(0);\n if (isNeg) {\n value = -value - BigInt(1);\n }\n const byteLength = (value === BigInt(0) ? 0 : ilog2(value)) + 1;\n const pipe = new Pipe(new Uint8Array(byteLength), 0);\n while (true) {\n const i = getLowerBytes(value);\n value /= BigInt(0x80);\n\n // prettier-ignore\n if ( ( isNeg && value === BigInt(0) && (i & 0x40) !== 0)\n || (!isNeg && value === BigInt(0) && (i & 0x40) === 0)) {\n pipe.write(new Uint8Array([i]));\n break;\n } else {\n pipe.write(new Uint8Array([i | 0x80]));\n }\n }\n\n function getLowerBytes(num: bigint): number {\n const bytes = num % BigInt(0x80);\n if (isNeg) {\n // We swap the bits here again, and remove 1 to do two's complement.\n return Number(BigInt(0x80) - bytes - BigInt(1));\n } else {\n return Number(bytes);\n }\n }\n return pipe.buffer;\n}\n\n/**\n * Decode a leb encoded buffer into a bigint. The number is decoded with support for negative\n * signed-leb encoding.\n * @param pipe A Buffer containing the signed leb encoded bits.\n */\nexport function slebDecode(pipe: Pipe): bigint {\n // Get the size of the buffer, then cut a buffer of that size.\n const pipeView = new Uint8Array(pipe.buffer);\n let len = 0;\n for (; len < pipeView.byteLength; len++) {\n if (pipeView[len] < 0x80) {\n // If it's a positive number, we reuse lebDecode.\n if ((pipeView[len] & 0x40) === 0) {\n return lebDecode(pipe);\n }\n break;\n }\n }\n\n const bytes = new Uint8Array(safeRead(pipe, len + 1));\n let value = BigInt(0);\n for (let i = bytes.byteLength - 1; i >= 0; i--) {\n value = value * BigInt(0x80) + BigInt(0x80 - (bytes[i] & 0x7f) - 1);\n }\n return -value - BigInt(1);\n}\n\n/**\n *\n * @param value bigint or number\n * @param byteLength number\n * @returns Uint8Array\n */\nexport function writeUIntLE(value: bigint | number, byteLength: number): Uint8Array {\n if (BigInt(value) < BigInt(0)) {\n throw new Error('Cannot write negative values.');\n }\n return writeIntLE(value, byteLength);\n}\n\n/**\n *\n * @param value - bigint or number\n * @param byteLength - number\n * @returns Uint8Array\n */\nexport function writeIntLE(value: bigint | number, byteLength: number): Uint8Array {\n value = BigInt(value);\n\n const pipe = new Pipe(new Uint8Array(Math.min(1, byteLength)), 0);\n let i = 0;\n let mul = BigInt(256);\n let sub = BigInt(0);\n let byte = Number(value % mul);\n pipe.write(new Uint8Array([byte]));\n while (++i < byteLength) {\n if (value < 0 && sub === BigInt(0) && byte !== 0) {\n sub = BigInt(1);\n }\n byte = Number((value / mul - sub) % BigInt(256));\n pipe.write(new Uint8Array([byte]));\n mul *= BigInt(256);\n }\n\n return pipe.buffer;\n}\n\n/**\n *\n * @param pipe Pipe from buffer-pipe\n * @param byteLength number\n * @returns bigint\n */\nexport function readUIntLE(pipe: Pipe, byteLength: number): bigint {\n if (byteLength <= 0 || !Number.isInteger(byteLength)) {\n throw new Error('Byte length must be a positive integer');\n }\n let val = BigInt(safeReadUint8(pipe));\n let mul = BigInt(1);\n let i = 0;\n while (++i < byteLength) {\n mul *= BigInt(256);\n const byte = BigInt(safeReadUint8(pipe));\n val = val + mul * byte;\n }\n return val;\n}\n\n/**\n *\n * @param pipe Pipe from buffer-pipe\n * @param byteLength number\n * @returns bigint\n */\nexport function readIntLE(pipe: Pipe, byteLength: number): bigint {\n if (byteLength <= 0 || !Number.isInteger(byteLength)) {\n throw new Error('Byte length must be a positive integer');\n }\n let val = readUIntLE(pipe, byteLength);\n const mul = BigInt(2) ** (BigInt(8) * BigInt(byteLength - 1) + BigInt(7));\n if (val >= mul) {\n val -= mul * BigInt(2);\n }\n return val;\n}\n", "/**\n * Returns a true Uint8Array from an ArrayBufferLike object.\n * @param bufLike a buffer-like object\n * @returns Uint8Array\n */\nexport function uint8FromBufLike(\n bufLike:\n | ArrayBuffer\n | Uint8Array\n | DataView\n | ArrayBufferView\n | ArrayBufferLike\n | [number]\n | number[]\n | { buffer: ArrayBuffer },\n): Uint8Array {\n if (!bufLike) {\n throw new Error('Input cannot be null or undefined');\n }\n\n if (bufLike instanceof Uint8Array) {\n return bufLike;\n }\n if (bufLike instanceof ArrayBuffer) {\n return new Uint8Array(bufLike);\n }\n if (Array.isArray(bufLike)) {\n return new Uint8Array(bufLike);\n }\n if ('buffer' in bufLike) {\n return uint8FromBufLike(bufLike.buffer);\n }\n return new Uint8Array(bufLike);\n}\n\n/**\n * Returns a true ArrayBuffer from a Uint8Array, as Uint8Array.buffer is unsafe.\n * @param {Uint8Array} arr Uint8Array to convert\n * @returns ArrayBuffer\n */\nexport function uint8ToBuf(arr: Uint8Array): ArrayBuffer {\n const buf = new ArrayBuffer(arr.byteLength);\n const view = new Uint8Array(buf);\n view.set(arr);\n return buf;\n}\n\n/**\n * Compares two Uint8Arrays for equality.\n * @param a The first Uint8Array.\n * @param b The second Uint8Array.\n * @returns True if the Uint8Arrays are equal, false otherwise.\n */\nexport function uint8Equals(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", "import { lebEncode, compare } from '@dfinity/candid';\nimport { Principal } from '@dfinity/principal';\nimport { HashValueErrorCode, InputError } from './errors.ts';\nimport { uint8FromBufLike } from './utils/buffer.ts';\nimport { concatBytes } from '@noble/hashes/utils';\nimport { sha256 } from '@noble/hashes/sha2';\n\nexport type RequestId = Uint8Array & { __requestId__: void };\n\ninterface ToHashable {\n toHash(): unknown;\n}\n\n/**\n *\n * @param value unknown value\n * @returns Uint8Array\n */\nexport function hashValue(value: unknown): Uint8Array {\n if (typeof value === 'string') {\n return hashString(value);\n } else if (typeof value === 'number') {\n return sha256(lebEncode(value));\n } else if (value instanceof Uint8Array || ArrayBuffer.isView(value)) {\n return sha256(uint8FromBufLike(value));\n } else if (Array.isArray(value)) {\n const vals = value.map(hashValue);\n return sha256(concatBytes(...vals));\n } else if (value && typeof value === 'object' && (value as Principal)._isPrincipal) {\n return sha256((value as Principal).toUint8Array());\n } else if (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as ToHashable).toHash === 'function'\n ) {\n return hashValue((value as ToHashable).toHash());\n // TODO This should be move to a specific async method as the webauthn flow required\n // the flow to be synchronous to ensure Safari touch id works.\n // } else if (value instanceof Promise) {\n // return value.then(x => hashValue(x));\n } else if (typeof value === 'object') {\n return hashOfMap(value as Record<string, unknown>);\n } else if (typeof value === 'bigint') {\n // Do this check much later than the other bigint check because this one is much less\n // type-safe.\n // So we want to try all the high-assurance type guards before this 'probable' one.\n return sha256(lebEncode(value));\n }\n throw InputError.fromCode(new HashValueErrorCode(value));\n}\n\nconst hashString = (value: string): Uint8Array => {\n const encoded = new TextEncoder().encode(value);\n return sha256(encoded);\n};\n\n/**\n * Get the RequestId of the provided ic-ref request.\n * RequestId is the result of the representation-independent-hash function.\n * https://sdk.dfinity.org/docs/interface-spec/index.html#hash-of-map\n * @param request - ic-ref request to hash into RequestId\n */\nexport function requestIdOf(request: Record<string, unknown>): RequestId {\n return hashOfMap(request) as RequestId;\n}\n\n/**\n * Hash a map into a Uint8Array using the representation-independent-hash function.\n * https://sdk.dfinity.org/docs/interface-spec/index.html#hash-of-map\n * @param map - Any non-nested object\n * @returns Uint8Array\n */\nexport function hashOfMap(map: Record<string, unknown>): Uint8Array {\n const hashed: Array<[Uint8Array, Uint8Array]> = Object.entries(map)\n .filter(([, value]) => value !== undefined)\n .map(([key, value]: [string, unknown]) => {\n const hashedKey = hashString(key);\n const hashedValue = hashValue(value);\n\n return [hashedKey, hashedValue] as [Uint8Array, Uint8Array];\n });\n\n const traversed: Array<[Uint8Array, Uint8Array]> = hashed;\n\n const sorted: Array<[Uint8Array, Uint8Array]> = traversed.sort(([k1], [k2]) => {\n return compare(k1, k2);\n });\n\n const concatenated = concatBytes(...sorted.map(x => concatBytes(...x)));\n const result = sha256(concatenated);\n return result;\n}\n", "// Default delta for ingress expiry is 5 minutes.\nexport const DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS = 5 * 60 * 1000;\n\n/**\n * The `\\x0Aic-request` domain separator used in the signature of IC requests.\n */\nexport const IC_REQUEST_DOMAIN_SEPARATOR = new TextEncoder().encode('\\x0Aic-request');\n\n/**\n * The `\\x0Bic-response` domain separator used in the signature of IC responses.\n */\nexport const IC_RESPONSE_DOMAIN_SEPARATOR = new TextEncoder().encode('\\x0Bic-response');\n\n/**\n * The `\\x1Aic-request-auth-delegation` domain separator used in the signature of delegations.\n */\nexport const IC_REQUEST_AUTH_DELEGATION_DOMAIN_SEPARATOR = new TextEncoder().encode(\n '\\x1Aic-request-auth-delegation',\n);\n", "import { Principal } from '@dfinity/principal';\nimport { type HttpAgentRequest } from './agent/http/types.ts';\nimport { requestIdOf } from './request_id.ts';\nimport { bytesToHex, concatBytes } from '@noble/hashes/utils';\nimport { IC_REQUEST_DOMAIN_SEPARATOR } from './constants.ts';\n/**\n * A Key Pair, containing a secret and public key.\n */\nexport interface KeyPair {\n secretKey: Uint8Array;\n publicKey: PublicKey;\n}\n\n/**\n * A public key that is DER encoded. This is a branded Uint8Array.\n */\nexport type DerEncodedPublicKey = Uint8Array & { __derEncodedPublicKey__?: void };\n\n/**\n * A signature array buffer.\n */\nexport type Signature = Uint8Array & { __signature__: void };\n\n/**\n * A Public Key implementation.\n */\nexport interface PublicKey {\n toDer(): DerEncodedPublicKey;\n // rawKey, toRaw, and derKey are optional for backwards compatibility.\n toRaw?(): Uint8Array;\n rawKey?: Uint8Array;\n derKey?: DerEncodedPublicKey;\n}\n\n/**\n * A General Identity object. This does not have to be a private key (for example,\n * the Anonymous identity), but it must be able to transform request.\n */\nexport interface Identity {\n /**\n * Get the principal represented by this identity. Normally should be a\n * `Principal.selfAuthenticating()`.\n */\n getPrincipal(): Principal;\n\n /**\n * Transform a request into a signed version of the request. This is done last\n * after the transforms on the body of a request. The returned object can be\n * anything, but must be serializable to CBOR.\n */\n transformRequest(request: HttpAgentRequest): Promise<unknown>;\n}\n\n/**\n * An Identity that can sign blobs.\n */\nexport abstract class SignIdentity implements Identity {\n protected _principal: Principal | undefined;\n\n /**\n * Returns the public key that would match this identity's signature.\n */\n public abstract getPublicKey(): PublicKey;\n\n /**\n * Signs a blob of data, with this identity's private key.\n */\n public abstract sign(blob: Uint8Array): Promise<Signature>;\n\n /**\n * Get the principal represented by this identity. Normally should be a\n * `Principal.selfAuthenticating()`.\n */\n public getPrincipal(): Principal {\n if (!this._principal) {\n this._principal = Principal.selfAuthenticating(new Uint8Array(this.getPublicKey().toDer()));\n }\n return this._principal;\n }\n\n /**\n * Transform a request into a signed version of the request. This is done last\n * after the transforms on the body of a request. The returned object can be\n * anything, but must be serializable to CBOR.\n * @param request - internet computer request to transform\n */\n public async transformRequest(request: HttpAgentRequest): Promise<unknown> {\n const { body, ...fields } = request;\n const requestId = requestIdOf(body);\n return {\n ...fields,\n body: {\n content: body,\n sender_pubkey: this.getPublicKey().toDer(),\n sender_sig: await this.sign(concatBytes(IC_REQUEST_DOMAIN_SEPARATOR, requestId)),\n },\n };\n }\n}\n\nexport class AnonymousIdentity implements Identity {\n public getPrincipal(): Principal {\n return Principal.anonymous();\n }\n\n public async transformRequest(request: HttpAgentRequest): Promise<unknown> {\n return {\n ...request,\n body: { content: request.body },\n };\n }\n}\n\n/*\n * We need to communicate with other agents on the page about identities,\n * but those messages may need to go across boundaries where it's not possible to\n * serialize/deserialize object prototypes easily.\n * So these are lightweight, serializable objects that contain enough information to recreate\n * SignIdentities, but don't commit to having all methods of SignIdentity.\n *\n * Use Case:\n * * DOM Events that let differently-versioned components communicate to one another about\n * Identities, even if they're using slightly different versions of agent packages to\n * create/interpret them.\n */\nexport interface AnonymousIdentityDescriptor {\n type: 'AnonymousIdentity';\n}\nexport interface PublicKeyIdentityDescriptor {\n type: 'PublicKeyIdentity';\n publicKey: string;\n}\nexport type IdentityDescriptor = AnonymousIdentityDescriptor | PublicKeyIdentityDescriptor;\n\n/**\n * Create an IdentityDescriptor from a @dfinity/identity Identity\n * @param identity - identity describe in returned descriptor\n */\nexport function createIdentityDescriptor(\n identity: SignIdentity | AnonymousIdentity,\n): IdentityDescriptor {\n const identityIndicator: IdentityDescriptor =\n 'getPublicKey' in identity\n ? { type: 'PublicKeyIdentity', publicKey: bytesToHex(identity.getPublicKey().toDer()) }\n : { type: 'AnonymousIdentity' };\n return identityIndicator;\n}\n", "/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes as abytes_,\n bytesToHex as bytesToHex_,\n concatBytes as concatBytes_,\n hexToBytes as hexToBytes_,\n isBytes as isBytes_,\n} from '@noble/hashes/utils.js';\nexport {\n abytes,\n anumber,\n bytesToHex,\n bytesToUtf8,\n concatBytes,\n hexToBytes,\n isBytes,\n randomBytes,\n utf8ToBytes,\n} from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n (message: Uint8Array | string): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nexport function abool(title: string, value: boolean): void {\n if (typeof value !== 'boolean') throw new Error(title + ' boolean expected, got ' + value);\n}\n\n// tmp name until v2\nexport function _abool2(value: boolean, title: string = ''): boolean {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\"`;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n\n// tmp name until v2\n/** Asserts something is Uint8Array. */\nexport function _abytes2(value: Uint8Array, length?: number, title: string = ''): Uint8Array {\n const bytes = isBytes_(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n\n// Used in weierstrass, der\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = num.toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex_(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n abytes_(bytes);\n return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes_(numberToHexUnpadded(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'secret key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n let res: Uint8Array;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes_(hex);\n } catch (e) {\n throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n }\n } else if (isBytes_(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n } else {\n throw new Error(title + ' must be hex string or Uint8Array');\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n return res;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes: Uint8Array): Uint8Array {\n return Uint8Array.from(bytes);\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as utf8ToBytes for ASCII or throws.\n */\nexport function asciiToBytes(ascii: string): Uint8Array {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(\n `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n );\n }\n return charCode;\n });\n}\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\n// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\n// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;\n\n// Is positive bigint\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\nexport function inRange(n: bigint, min: bigint, max: bigint): boolean {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number): bigint {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n: bigint, pos: number, value: boolean): bigint {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\ntype Pred<T> = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG<Key>(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg<T>(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred<T>) => T {\n if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n const u8n = (len: number) => new Uint8Array(len); // creates Uint8Array\n const u8of = (byte: number) => Uint8Array.of(byte); // another shortcut\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n(0)) => {\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) return;\n k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000) throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes_(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred<T>): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\n// Validating curves and fields\n\nconst validatorFns = {\n bigint: (val: any): boolean => typeof val === 'bigint',\n function: (val: any): boolean => typeof val === 'function',\n boolean: (val: any): boolean => typeof val === 'boolean',\n string: (val: any): boolean => typeof val === 'string',\n stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes_(val),\n isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),\n array: (val: any): boolean => Array.isArray(val),\n field: (val: any, object: any): any => (object as any).Fp.isValid(val),\n hash: (val: any): boolean => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap<T extends Record<string, any>> = { [K in keyof T]?: Validator };\n// type Record<K extends string | number | symbol, T> = { [P in K]: T; }\n\nexport function validateObject<T extends Record<string, any>>(\n object: T,\n validators: ValMap<T>,\n optValidators: ValMap<T> = {}\n): T {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function') throw new Error('invalid validator function');\n\n const val = object[fieldName as keyof typeof object];\n if (isOptional && val === undefined) return;\n if (!checkVal(val, object)) {\n throw new Error(\n 'param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val\n );\n }\n };\n for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n\nexport function isHash(val: CHash): boolean {\n return typeof val === 'function' && Number.isSafeInteger(val.outputLen);\n}\nexport function _validateObject(\n object: Record<string, any>,\n fields: Record<string, string>,\n optFields: Record<string, string> = {}\n): void {\n if (!object || typeof object !== 'object') throw new Error('expected valid options object');\n type Item = keyof typeof object;\n function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n const val = object[fieldName];\n if (isOpt && val === undefined) return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));\n Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));\n}\n\n/**\n * throws not implemented error\n */\nexport const notImplemented = (): never => {\n throw new Error('not implemented');\n};\n\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized<T extends object, R, O extends any[]>(\n fn: (arg: T, ...args: O) => R\n): (arg: T, ...args: O) => R {\n const map = new WeakMap<T, R>();\n return (arg: T, ...args: O): R => {\n const val = map.get(arg);\n if (val !== undefined) return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n", "/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n _validateObject,\n anumber,\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n} from '../utils.ts';\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);\n// prettier-ignore\nconst _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\n}\n\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n) throw new Error('invert: expected non-zero number');\n if (modulo <= _0n) throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\nfunction assertIsSquare<T>(Fp: IField<T>, root: T, n: T): void {\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n}\n\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4<T>(Fp: IField<T>, n: T) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\n const root = Fp.pow(n, p1div4);\n assertIsSquare(Fp, root, n);\n return root;\n}\n\nfunction sqrt5mod8<T>(Fp: IField<T>, n: T) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n assertIsSquare(Fp, root, n);\n return root;\n}\n\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));// 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n return <T>(Fp: IField<T>, n: T) => {\n let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = Fp.eql(Fp.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = Fp.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = Fp.cmov(tv1, tv2, e3);// 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(Fp, root, n);\n return root;\n };\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow<T>(Fp: IField<T>, n: T): T {\n if (Fp.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) \u2261 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P \u2261 3 (mod 4)\n * 2. P \u2261 5 (mod 8)\n * 3. P \u2261 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nexport function FpSqrt(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // P \u2261 3 (mod 4) => \u221An = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P \u2261 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P \u2261 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n) return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint): boolean =>\n (mod(num, modulo) & _1n) === _1n;\n\n/** Field is not always over prime: for example, Fp2 has ORDER(q)=p^m. */\nexport interface IField<T> {\n ORDER: bigint;\n isLE: boolean;\n BYTES: number;\n BITS: number;\n MASK: bigint;\n ZERO: T;\n ONE: T;\n // 1-arg\n create: (num: T) => T;\n isValid: (num: T) => boolean;\n is0: (num: T) => boolean;\n isValidNot0: (num: T) => boolean;\n neg(num: T): T;\n inv(num: T): T;\n sqrt(num: T): T;\n sqr(num: T): T;\n // 2-args\n eql(lhs: T, rhs: T): boolean;\n add(lhs: T, rhs: T): T;\n sub(lhs: T, rhs: T): T;\n mul(lhs: T, rhs: T | bigint): T;\n pow(lhs: T, power: bigint): T;\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n addN(lhs: T, rhs: T): T;\n subN(lhs: T, rhs: T): T;\n mulN(lhs: T, rhs: T | bigint): T;\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.\n isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n allowedLengths?: number[];\n // legendre?(num: T): T;\n invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array, skipValidation?: boolean): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\nexport function validateField<T>(field: IField<T>): IField<T> {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n } as Record<string, string>;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n _validateObject(field, opts);\n // const max = 16384;\n // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');\n // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');\n return field;\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow<T>(Fp: IField<T>, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch<T>(Fp: IField<T>, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv<T>(Fp: IField<T>, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) \u2261 1 if a is a square (mod p), quadratic residue\n * * (a | p) \u2261 -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) \u2261 0 if a \u2261 0 (mod p)\n */\nexport function FpLegendre<T>(Fp: IField<T>, n: T): -1 | 0 | 1 {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare<T>(Fp: IField<T>, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n\nexport type NLength = { nByteLength: number; nBitLength: number };\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number): NLength {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;\ntype SqrtFn = (n: bigint) => bigint;\ntype FieldOpts = Partial<{\n sqrt: SqrtFn;\n isLE: boolean;\n BITS: number;\n modFromBytes: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n allowedLengths?: readonly number[]; // for P521 (adds padding for smaller sizes)\n}>;\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. `Object.freeze`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER field order, probably prime, or could be composite\n * @param bitLen how many bits the field consumes\n * @param isLE (default: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n ORDER: bigint,\n bitLenOrOpts?: number | FieldOpts, // TODO: use opts only in v2?\n isLE = false,\n opts: { sqrt?: SqrtFn } = {}\n): Readonly<FpField> {\n if (ORDER <= _0n) throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n let _nbitLength: number | undefined = undefined;\n let _sqrt: SqrtFn | undefined = undefined;\n let modFromBytes: boolean = false;\n let allowedLengths: undefined | readonly number[] = undefined;\n if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {\n if (opts.sqrt || isLE) throw new Error('cannot specify opts in two arguments');\n const _opts = bitLenOrOpts;\n if (_opts.BITS) _nbitLength = _opts.BITS;\n if (_opts.sqrt) _sqrt = _opts.sqrt;\n if (typeof _opts.isLE === 'boolean') isLE = _opts.isLE;\n if (typeof _opts.modFromBytes === 'boolean') modFromBytes = _opts.modFromBytes;\n allowedLengths = _opts.allowedLengths;\n } else {\n if (typeof bitLenOrOpts === 'number') _nbitLength = bitLenOrOpts;\n if (opts.sqrt) _sqrt = opts.sqrt;\n }\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);\n if (BYTES > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n let sqrtP: ReturnType<typeof FpSqrt>; // cached sqrtP\n const f: Readonly<FpField> = Object.freeze({\n ORDER,\n isLE,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n allowedLengths: allowedLengths,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n // is valid and invertible\n isValidNot0: (num: bigint) => !f.is0(num) && f.isValid(num),\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n\n inv: (num) => invert(num, ORDER),\n sqrt:\n _sqrt ||\n ((n) => {\n if (!sqrtP) sqrtP = FpSqrt(ORDER);\n return sqrtP(f, n);\n }),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes, skipValidation = true) => {\n if (allowedLengths) {\n if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error(\n 'Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length\n );\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes) scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!f.isValid(scalar)) throw new Error('invalid field element: outside of range 0..ORDER');\n // NOTE: we don't validate scalar here, please use isValid. This done such way because some\n // protocol may allow non-reduced scalar that reduced later or changed some other way.\n return scalar;\n },\n // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov: (a, b, c) => (c ? b : a),\n } as FpField);\n return Object.freeze(f);\n}\n\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\n\nexport function FpSqrtOdd<T>(Fp: IField<T>, elm: T): T {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven<T>(Fp: IField<T>, elm: T): T {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use `mapKeyToField` instead\n */\nexport function hashToPrivateScalar(\n hash: string | Uint8Array,\n groupOrder: bigint,\n isLE = false\n): bigint {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(\n 'hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen\n );\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n", "/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, validateObject } from '../utils.ts';\nimport { Field, FpInvertBatch, nLength, validateField, type IField } from './modular.ts';\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint<T> = {\n x: T;\n y: T;\n} & { Z?: never };\n\n// This was initialy do this way to re-use montgomery ladder in field (add->mul,double->sqr), but\n// that didn't happen and there is probably not much reason to have separate Group like this?\nexport interface Group<T extends Group<T>> {\n double(): T;\n negate(): T;\n add(other: T): T;\n subtract(other: T): T;\n equals(other: T): boolean;\n multiply(scalar: bigint): T;\n toAffine?(invertedZ?: any): AffinePoint<any>;\n}\n\n// We can't \"abstract out\" coordinates (X, Y, Z; and T in Edwards): argument names of constructor\n// are not accessible. See Typescript gh-56093, gh-41594.\n//\n// We have to use recursive types, so it will return actual point, not constained `CurvePoint`.\n// If, at any point, P is `any`, it will erase all types and replace it\n// with `any`, because of recursion, `any implements CurvePoint`,\n// but we lose all constrains on methods.\n\n/** Base interface for all elliptic curve Points. */\nexport interface CurvePoint<F, P extends CurvePoint<F, P>> extends Group<P> {\n /** Affine x coordinate. Different from projective / extended X coordinate. */\n x: F;\n /** Affine y coordinate. Different from projective / extended Y coordinate. */\n y: F;\n Z?: F;\n double(): P;\n negate(): P;\n add(other: P): P;\n subtract(other: P): P;\n equals(other: P): boolean;\n multiply(scalar: bigint): P;\n assertValidity(): void;\n clearCofactor(): P;\n is0(): boolean;\n isTorsionFree(): boolean;\n isSmallOrder(): boolean;\n multiplyUnsafe(scalar: bigint): P;\n /**\n * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}.\n * @param isLazy calculate cache now. Default (true) ensures it's deferred to first `multiply()`\n */\n precompute(windowSize?: number, isLazy?: boolean): P;\n /** Converts point to 2D xy affine coordinates */\n toAffine(invertedZ?: F): AffinePoint<F>;\n toBytes(): Uint8Array;\n toHex(): string;\n}\n\n/** Base interface for all elliptic curve Point constructors. */\nexport interface CurvePointCons<P extends CurvePoint<any, P>> {\n [Symbol.hasInstance]: (item: unknown) => boolean;\n BASE: P;\n ZERO: P;\n /** Field for basic curve math */\n Fp: IField<P_F<P>>;\n /** Scalar field, for scalars in multiply and others */\n Fn: IField<bigint>;\n /** Creates point from x, y. Does NOT validate if the point is valid. Use `.assertValidity()`. */\n fromAffine(p: AffinePoint<P_F<P>>): P;\n fromBytes(bytes: Uint8Array): P;\n fromHex(hex: Uint8Array | string): P;\n}\n\n// Type inference helpers: PC - PointConstructor, P - Point, Fp - Field element\n// Short names, because we use them a lot in result types:\n// * we can't do 'P = GetCurvePoint<PC>': this is default value and doesn't constrain anything\n// * we can't do 'type X = GetCurvePoint<PC>': it won't be accesible for arguments/return types\n// * `CurvePointCons<P extends CurvePoint<any, P>>` constraints from interface definition\n// won't propagate, if `PC extends CurvePointCons<any>`: the P would be 'any', which is incorrect\n// * PC could be super specific with super specific P, which implements CurvePoint<any, P>.\n// this means we need to do stuff like\n// `function test<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(`\n// if we want type safety around P, otherwise PC_P<PC> will be any\n\n/** Returns Fp type from Point (P_F<P> == P.F) */\nexport type P_F<P extends CurvePoint<any, P>> = P extends CurvePoint<infer F, P> ? F : never;\n/** Returns Fp type from PointCons (PC_F<PC> == PC.P.F) */\nexport type PC_F<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['Fp']['ZERO'];\n/** Returns Point type from PointCons (PC_P<PC> == PC.P) */\nexport type PC_P<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['ZERO'];\n\n// Ugly hack to get proper type inference, because in typescript fails to infer resursively.\n// The hack allows to do up to 10 chained operations without applying type erasure.\n//\n// Types which won't work:\n// * `CurvePointCons<CurvePoint<any, any>>`, will return `any` after 1 operation\n// * `CurvePointCons<any>: WeierstrassPointCons<bigint> extends CurvePointCons<any> = false`\n// * `P extends CurvePoint, PC extends CurvePointCons<P>`\n// * It can't infer P from PC alone\n// * Too many relations between F, P & PC\n// * It will infer P/F if `arg: CurvePointCons<F, P>`, but will fail if PC is generic\n// * It will work correctly if there is an additional argument of type P\n// * But generally, we don't want to parametrize `CurvePointCons` over `F`: it will complicate\n// types, making them un-inferable\n// prettier-ignore\nexport type PC_ANY = CurvePointCons<\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any, any>\n >>>>>>>>>\n>;\n\nexport interface CurveLengths {\n secretKey?: number;\n publicKey?: number;\n publicKeyUncompressed?: number;\n publicKeyHasPrefix?: boolean;\n signature?: number;\n seed?: number;\n}\nexport type GroupConstructor<T> = {\n BASE: T;\n ZERO: T;\n};\n/** @deprecated */\nexport type ExtendedGroupConstructor<T> = GroupConstructor<T> & {\n Fp: IField<any>;\n Fn: IField<bigint>;\n fromAffine(ap: AffinePoint<any>): T;\n};\nexport type Mapper<T> = (i: T[]) => T[];\n\nexport function negateCt<T extends { negate: () => T }>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\n}\n\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\nexport function normalizeZ<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[]\n): P[] {\n const invertedZs = FpInvertBatch(\n c.Fp,\n points.map((p) => p.Z!)\n );\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\n\nfunction validateW(W: number, bits: number) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\n\n/** Internal wNAF opts for specific W and scalarBits */\nexport type WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\n\nfunction validateMSMPoints(points: any[], c: any) {\n if (!Array.isArray(points)) throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c)) throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars: any[], field: any) {\n if (!Array.isArray(scalars)) throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s)) throw new Error('invalid scalar at index ' + i);\n });\n}\n\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap<any, any[]>();\nconst pointWindowSizes = new WeakMap<any, number>();\n\nfunction getW(P: any): number {\n // To disable precomputes:\n // return 1;\n return pointWindowSizes.get(P) || 1;\n}\n\nfunction assert0(n: bigint): void {\n if (n !== _0n) throw new Error('invalid wNAF');\n}\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / \uD835\uDC4A) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport class wNAF<PC extends PC_ANY> {\n private readonly BASE: PC_P<PC>;\n private readonly ZERO: PC_P<PC>;\n private readonly Fn: PC['Fn'];\n readonly bits: number;\n\n // Parametrized with a given Point class (not individual point)\n constructor(Point: PC, bits: number) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n\n // non-const time multiplication ladder\n _unsafeLadder(elm: PC_P<PC>, n: bigint, p: PC_P<PC> = this.ZERO): PC_P<PC> {\n let d: PC_P<PC> = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(\uD835\uDC4A\u22121) * (Math.ceil(\uD835\uDC5B / \uD835\uDC4A) + 1), where:\n * - \uD835\uDC4A is the window size\n * - \uD835\uDC5B is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param point Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n private precomputeWindow(point: PC_P<PC>, W: number): PC_P<PC>[] {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points: PC_P<PC>[] = [];\n let p: PC_P<PC> = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n private wNAF(W: number, precomputes: PC_P<PC>[], n: bigint): { p: PC_P<PC>; f: PC_P<PC> } {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n)) throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points: JIT won't eliminate f.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n }\n\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n private wNAFUnsafe(\n W: number,\n precomputes: PC_P<PC>[],\n n: bigint,\n acc: PC_P<PC> = this.ZERO\n ): PC_P<PC> {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n\n private getPrecomputes(W: number, point: PC_P<PC>, transform?: Mapper<PC_P<PC>>): PC_P<PC>[] {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W) as PC_P<PC>[];\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function') comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n\n cached(\n point: PC_P<PC>,\n scalar: bigint,\n transform?: Mapper<PC_P<PC>>\n ): { p: PC_P<PC>; f: PC_P<PC> } {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n\n unsafe(point: PC_P<PC>, scalar: bigint, transform?: Mapper<PC_P<PC>>, prev?: PC_P<PC>): PC_P<PC> {\n const W = getW(point);\n if (W === 1) return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n createCache(P: PC_P<PC>, W: number): void {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n\n hasCache(elm: PC_P<PC>): boolean {\n return getW(elm) !== 1;\n }\n}\n\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n */\nexport function mulEndoUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n Point: PC,\n point: P,\n k1: bigint,\n k2: bigint\n): { p1: P; p2: P } {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) p1 = p1.add(acc);\n if (k2 & _1n) p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\n}\n\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka secret keys / bigints)\n */\nexport function pippenger<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n fieldN: IField<bigint>,\n points: P[],\n scalars: bigint[]\n): P {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();\n }\n return sum as P;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n fieldN: IField<bigint>,\n points: P[],\n windowSize: number\n): (scalars: bigint[]) => P {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar \u00D7 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 \u00D7 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 \u00D7 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p: P) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars: bigint[]): P => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr) continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\n\n// TODO: remove\n/**\n * Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n * Though generator can be different (Fp2 / Fp6 for BLS).\n */\nexport type BasicCurve<T> = {\n Fp: IField<T>; // Field over which we'll do calculations (Fp)\n n: bigint; // Curve order, total count of valid points in the field\n nBitLength?: number; // bit length of curve order\n nByteLength?: number; // byte length of curve order\n h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n hEff?: bigint; // Number to multiply to clear cofactor\n Gx: T; // base point X coordinate\n Gy: T; // base point Y coordinate\n allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\n// TODO: remove\n/** @deprecated */\nexport function validateBasic<FP, T>(\n curve: BasicCurve<FP> & T\n): Readonly<\n {\n readonly nBitLength: number;\n readonly nByteLength: number;\n } & BasicCurve<FP> &\n T & {\n p: bigint;\n }\n> {\n validateField(curve.Fp);\n validateObject(\n curve,\n {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n },\n {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n }\n );\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n } as const);\n}\n\nexport type ValidCurveParams<T> = {\n p: bigint;\n n: bigint;\n h: bigint;\n a: T;\n b?: T;\n d?: T;\n Gx: T;\n Gy: T;\n};\n\nfunction createField<T>(order: bigint, field?: IField<T>, isLE?: boolean): IField<T> {\n if (field) {\n if (field.ORDER !== order) throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n } else {\n return Field(order, { isLE }) as unknown as IField<T>;\n }\n}\nexport type FpFn<T> = { Fp: IField<T>; Fn: IField<bigint> };\n\n/** Validates CURVE opts and creates fields */\nexport function _createCurveFields<T>(\n type: 'weierstrass' | 'edwards',\n CURVE: ValidCurveParams<T>,\n curveOpts: Partial<FpFn<T>> = {},\n FpFnLE?: boolean\n): FpFn<T> & { CURVE: ValidCurveParams<T> } {\n if (FpFnLE === undefined) FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object') throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h'] as const) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b: 'b' | 'd' = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b] as const;\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\n", "/**\n * Twisted Edwards curve. The formula is: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2.\n * For design rationale of types / exports, see weierstrass module documentation.\n * Untwisted Edwards curves exist, but they aren't used in real-world protocols.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n _validateObject,\n _abool2 as abool,\n _abytes2 as abytes,\n aInRange,\n bytesToHex,\n bytesToNumberLE,\n concatBytes,\n copyBytes,\n ensureBytes,\n isBytes,\n memoized,\n notImplemented,\n randomBytes as randomBytesWeb,\n type FHash,\n type Hex,\n} from '../utils.ts';\nimport {\n _createCurveFields,\n normalizeZ,\n pippenger,\n wNAF,\n type AffinePoint,\n type BasicCurve,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport { Field, type IField, type NLength } from './modular.ts';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n\nexport type UVRatio = (u: bigint, v: bigint) => { isValid: boolean; value: bigint };\n\n/** Instance of Extended Point with coordinates in X, Y, Z, T. */\nexport interface EdwardsPoint extends CurvePoint<bigint, EdwardsPoint> {\n /** extended X coordinate. Different from affine x. */\n readonly X: bigint;\n /** extended Y coordinate. Different from affine y. */\n readonly Y: bigint;\n /** extended Z coordinate */\n readonly Z: bigint;\n /** extended T coordinate */\n readonly T: bigint;\n\n /** @deprecated use `toBytes` */\n toRawBytes(): Uint8Array;\n /** @deprecated use `p.precompute(windowSize)` */\n _setWindowSize(windowSize: number): void;\n /** @deprecated use .X */\n readonly ex: bigint;\n /** @deprecated use .Y */\n readonly ey: bigint;\n /** @deprecated use .Z */\n readonly ez: bigint;\n /** @deprecated use .T */\n readonly et: bigint;\n}\n/** Static methods of Extended Point with coordinates in X, Y, Z, T. */\nexport interface EdwardsPointCons extends CurvePointCons<EdwardsPoint> {\n new (X: bigint, Y: bigint, Z: bigint, T: bigint): EdwardsPoint;\n CURVE(): EdwardsOpts;\n fromBytes(bytes: Uint8Array, zip215?: boolean): EdwardsPoint;\n fromHex(hex: Hex, zip215?: boolean): EdwardsPoint;\n /** @deprecated use `import { pippenger } from '@noble/curves/abstract/curve.js';` */\n msm(points: EdwardsPoint[], scalars: bigint[]): EdwardsPoint;\n}\n/** @deprecated use EdwardsPoint */\nexport type ExtPointType = EdwardsPoint;\n/** @deprecated use EdwardsPointCons */\nexport type ExtPointConstructor = EdwardsPointCons;\n\n/**\n * Twisted Edwards curve options.\n *\n * * a: formula param\n * * d: formula param\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor. h*n is group order; n is subgroup order\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type EdwardsOpts = Readonly<{\n p: bigint;\n n: bigint;\n h: bigint;\n a: bigint;\n d: bigint;\n Gx: bigint;\n Gy: bigint;\n}>;\n\n/**\n * Extra curve options for Twisted Edwards.\n *\n * * Fp: redefined Field over curve.p\n * * Fn: redefined Field over curve.n\n * * uvRatio: helper function for decompression, calculating \u221A(u/v)\n */\nexport type EdwardsExtraOpts = Partial<{\n Fp: IField<bigint>;\n Fn: IField<bigint>;\n FpFnLE: boolean;\n uvRatio: (u: bigint, v: bigint) => { isValid: boolean; value: bigint };\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) options.\n *\n * * hash: hash function used to hash secret keys and messages\n * * adjustScalarBytes: clears bits to get valid field element\n * * domain: Used for hashing\n * * mapToCurve: for hash-to-curve standard\n * * prehash: RFC 8032 pre-hashing of messages to sign() / verify()\n * * randomBytes: function generating random bytes, used for randomSecretKey\n */\nexport type EdDSAOpts = Partial<{\n adjustScalarBytes: (bytes: Uint8Array) => Uint8Array;\n domain: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array;\n mapToCurve: (scalar: bigint[]) => AffinePoint<bigint>;\n prehash: FHash;\n randomBytes: (bytesLength?: number) => Uint8Array;\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) interface.\n *\n * Allows to create and verify signatures, create public and secret keys.\n */\nexport interface EdDSA {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Hex) => Uint8Array;\n sign: (message: Hex, secretKey: Hex, options?: { context?: Hex }) => Uint8Array;\n verify: (\n sig: Hex,\n message: Hex,\n publicKey: Hex,\n options?: { context?: Hex; zip215: boolean }\n ) => boolean;\n Point: EdwardsPointCons;\n utils: {\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n isValidSecretKey: (secretKey: Uint8Array) => boolean;\n isValidPublicKey: (publicKey: Uint8Array, zip215?: boolean) => boolean;\n\n /**\n * Converts ed public key to x public key.\n *\n * There is NO `fromMontgomery`:\n * - There are 2 valid ed25519 points for every x25519, with flipped coordinate\n * - Sometimes there are 0 valid ed25519 points, because x25519 *additionally*\n * accepts inputs on the quadratic twist, which can't be moved to ed25519\n *\n * @example\n * ```js\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomSecretKey());\n * const aPriv = x25519.utils.randomSecretKey();\n * x25519.getSharedSecret(aPriv, ed25519.utils.toMontgomery(someonesPub))\n * ```\n */\n toMontgomery: (publicKey: Uint8Array) => Uint8Array;\n /**\n * Converts ed secret key to x secret key.\n * @example\n * ```js\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomSecretKey());\n * const aPriv = ed25519.utils.randomSecretKey();\n * x25519.getSharedSecret(ed25519.utils.toMontgomerySecret(aPriv), someonesPub)\n * ```\n */\n toMontgomerySecret: (privateKey: Uint8Array) => Uint8Array;\n getExtendedPublicKey: (key: Hex) => {\n head: Uint8Array;\n prefix: Uint8Array;\n scalar: bigint;\n point: EdwardsPoint;\n pointBytes: Uint8Array;\n };\n\n /** @deprecated use `randomSecretKey` */\n randomPrivateKey: (seed?: Uint8Array) => Uint8Array;\n /** @deprecated use `point.precompute()` */\n precompute: (windowSize?: number, point?: EdwardsPoint) => EdwardsPoint;\n };\n lengths: CurveLengths;\n}\n\nfunction isEdValidXY(Fp: IField<bigint>, CURVE: EdwardsOpts, x: bigint, y: bigint): boolean {\n const x2 = Fp.sqr(x);\n const y2 = Fp.sqr(y);\n const left = Fp.add(Fp.mul(CURVE.a, x2), y2);\n const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));\n return Fp.eql(left, right);\n}\n\nexport function edwards(params: EdwardsOpts, extraOpts: EdwardsExtraOpts = {}): EdwardsPointCons {\n const validated = _createCurveFields('edwards', params, extraOpts, extraOpts.FpFnLE);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE as EdwardsOpts;\n const { h: cofactor } = CURVE;\n _validateObject(extraOpts, {}, { uvRatio: 'function' });\n\n // Important:\n // There are some places where Fp.BYTES is used instead of nByteLength.\n // So far, everything has been tested with curves of Fp.BYTES == nByteLength.\n // TODO: test and find curves which behave otherwise.\n const MASK = _2n << (BigInt(Fn.BYTES * 8) - _1n);\n const modP = (n: bigint) => Fp.create(n); // Function overrides\n\n // sqrt(u/v)\n const uvRatio =\n extraOpts.uvRatio ||\n ((u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n\n // Validate whether the passed curve params are valid.\n // equation ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2 should work for generator point.\n if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n\n /**\n * Asserts coordinate is valid: 0 <= n < MASK.\n * Coordinates >= Fp.ORDER are allowed for zip215.\n */\n function acoord(title: string, n: bigint, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n return n;\n }\n\n function aextpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ExtendedPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p: Point, iz?: bigint): AffinePoint<bigint> => {\n const { X, Y, Z } = p;\n const is0 = p.is0();\n if (iz == null) iz = is0 ? _8n : (Fp.inv(Z) as bigint); // 8 was chosen arbitrarily\n const x = modP(X * iz);\n const y = modP(Y * iz);\n const zz = Fp.mul(Z, iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x, y };\n });\n const assertValidMemo = memoized((p: Point) => {\n const { a, d } = CURVE;\n if (p.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX\u00B2 + Y\u00B2)Z\u00B2 = Z\u2074 + dX\u00B2Y\u00B2\n const { X, Y, Z, T } = p;\n const X2 = modP(X * X); // X\u00B2\n const Y2 = modP(Y * Y); // Y\u00B2\n const Z2 = modP(Z * Z); // Z\u00B2\n const Z4 = modP(Z2 * Z2); // Z\u2074\n const aX2 = modP(X2 * a); // aX\u00B2\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX\u00B2 + Y\u00B2)Z\u00B2\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z\u2074 + dX\u00B2Y\u00B2\n if (left !== right) throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT) throw new Error('bad point: equation left != right (2)');\n return true;\n });\n\n // Extended Point works in extended coordinates: (X, Y, Z, T) \u220B (x=X/Z, y=Y/Z, T=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point implements EdwardsPoint {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n // zero / infinity / identity point\n static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: bigint;\n readonly Y: bigint;\n readonly Z: bigint;\n readonly T: bigint;\n\n constructor(X: bigint, Y: bigint, Z: bigint, T: bigint) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y);\n this.Z = acoord('z', Z, true);\n this.T = acoord('t', T);\n Object.freeze(this);\n }\n\n static CURVE(): EdwardsOpts {\n return CURVE;\n }\n\n static fromAffine(p: AffinePoint<bigint>): Point {\n if (p instanceof Point) throw new Error('extended point not allowed');\n const { x, y } = p || {};\n acoord('x', x);\n acoord('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n\n // Uses algo from RFC8032 5.1.3.\n static fromBytes(bytes: Uint8Array, zip215 = false): Point {\n const len = Fp.BYTES;\n const { a, d } = CURVE;\n bytes = copyBytes(abytes(bytes, len, 'point'));\n abool(zip215, 'zip215');\n const normed = copyBytes(bytes); // copy again, we'll manipulate it\n const lastByte = bytes[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = bytesToNumberLE(normed);\n\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n aInRange('point.y', y, _0n, max);\n\n // Ed25519: x\u00B2 = (y\u00B2-1)/(dy\u00B2+1) mod p. Ed448: x\u00B2 = (y\u00B2-1)/(dy\u00B2-1) mod p. Generic case:\n // ax\u00B2+y\u00B2=1+dx\u00B2y\u00B2 => y\u00B2-1=dx\u00B2y\u00B2-ax\u00B2 => y\u00B2-1=x\u00B2(dy\u00B2-a) => x\u00B2=(y\u00B2-1)/(dy\u00B2-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y\u00B2 - 1\n const v = modP(d * y2 - a); // v = d y\u00B2 + 1.\n let { isValid, value: x } = uvRatio(u, v); // \u221A(u/v)\n if (!isValid) throw new Error('bad point: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('bad point: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromHex(bytes: Uint8Array, zip215 = false): Point {\n return Point.fromBytes(ensureBytes('point', bytes), zip215);\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n precompute(windowSize: number = 8, isLazy = true) {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_2n); // random number\n return this;\n }\n\n // Useful in fromAffine() - not for fromBytes(), which always created valid points.\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n aextpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n\n is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n negate(): Point {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));\n }\n\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double(): Point {\n const { a } = CURVE;\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other: Point) {\n aextpoint(other);\n const { a, d } = CURVE;\n const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n subtract(other: Point): Point {\n return this.add(other.negate());\n }\n\n // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n // 1 <= scalar < L\n if (!Fn.isValidNot0(scalar)) throw new Error('invalid scalar: expected 1 <= sc < curve.n');\n const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));\n return normalizeZ(Point, [p, f])[0];\n }\n\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n // Accepts optional accumulator to merge with multiply (important for sparse scalars)\n multiplyUnsafe(scalar: bigint, acc = Point.ZERO): Point {\n // 0 <= scalar < L\n if (!Fn.isValid(scalar)) throw new Error('invalid scalar: expected 0 <= sc < curve.n');\n if (scalar === _0n) return Point.ZERO;\n if (this.is0() || scalar === _1n) return this;\n return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);\n }\n\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder(): boolean {\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree(): boolean {\n return wnaf.unsafe(this, CURVE.n).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n return toAffineMemo(this, invertedZ);\n }\n\n clearCofactor(): Point {\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n toBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n // Fp.toBytes() allows non-canonical encoding of y (>= p).\n const bytes = Fp.toBytes(y);\n // Each y has 2 valid points: (x, y), (x,-y).\n // When compressing, it's enough to store y and use the last byte to encode sign of x\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0;\n return bytes;\n }\n toHex(): string {\n return bytesToHex(this.toBytes());\n }\n\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n\n // TODO: remove\n get ex(): bigint {\n return this.X;\n }\n get ey(): bigint {\n return this.Y;\n }\n get ez(): bigint {\n return this.Z;\n }\n get et(): bigint {\n return this.T;\n }\n static normalizeZ(points: Point[]): Point[] {\n return normalizeZ(Point, points);\n }\n static msm(points: Point[], scalars: bigint[]): Point {\n return pippenger(Point, Fn, points, scalars);\n }\n _setWindowSize(windowSize: number) {\n this.precompute(windowSize);\n }\n toRawBytes(): Uint8Array {\n return this.toBytes();\n }\n }\n const wnaf = new wNAF(Point, Fn.BITS);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n\n/**\n * Base class for prime-order points like Ristretto255 and Decaf448.\n * These points eliminate cofactor issues by representing equivalence classes\n * of Edwards curve points.\n */\nexport abstract class PrimeEdwardsPoint<T extends PrimeEdwardsPoint<T>>\n implements CurvePoint<bigint, T>\n{\n static BASE: PrimeEdwardsPoint<any>;\n static ZERO: PrimeEdwardsPoint<any>;\n static Fp: IField<bigint>;\n static Fn: IField<bigint>;\n\n protected readonly ep: EdwardsPoint;\n\n constructor(ep: EdwardsPoint) {\n this.ep = ep;\n }\n\n // Abstract methods that must be implemented by subclasses\n abstract toBytes(): Uint8Array;\n abstract equals(other: T): boolean;\n\n // Static methods that must be implemented by subclasses\n static fromBytes(_bytes: Uint8Array): any {\n notImplemented();\n }\n\n static fromHex(_hex: Hex): any {\n notImplemented();\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n // Common implementations\n clearCofactor(): T {\n // no-op for prime-order groups\n return this as any;\n }\n\n assertValidity(): void {\n this.ep.assertValidity();\n }\n\n toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n return this.ep.toAffine(invertedZ);\n }\n\n toHex(): string {\n return bytesToHex(this.toBytes());\n }\n\n toString(): string {\n return this.toHex();\n }\n\n isTorsionFree(): boolean {\n return true;\n }\n\n isSmallOrder(): boolean {\n return false;\n }\n\n add(other: T): T {\n this.assertSame(other);\n return this.init(this.ep.add(other.ep));\n }\n\n subtract(other: T): T {\n this.assertSame(other);\n return this.init(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): T {\n return this.init(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): T {\n return this.init(this.ep.multiplyUnsafe(scalar));\n }\n\n double(): T {\n return this.init(this.ep.double());\n }\n\n negate(): T {\n return this.init(this.ep.negate());\n }\n\n precompute(windowSize?: number, isLazy?: boolean): T {\n return this.init(this.ep.precompute(windowSize, isLazy));\n }\n\n // Helper methods\n abstract is0(): boolean;\n protected abstract assertSame(other: T): void;\n protected abstract init(ep: EdwardsPoint): T;\n\n /** @deprecated use `toBytes` */\n toRawBytes(): Uint8Array {\n return this.toBytes();\n }\n}\n\n/**\n * Initializes EdDSA signatures over given Edwards curve.\n */\nexport function eddsa(Point: EdwardsPointCons, cHash: FHash, eddsaOpts: EdDSAOpts = {}): EdDSA {\n if (typeof cHash !== 'function') throw new Error('\"hash\" function param is required');\n _validateObject(\n eddsaOpts,\n {},\n {\n adjustScalarBytes: 'function',\n randomBytes: 'function',\n domain: 'function',\n prehash: 'function',\n mapToCurve: 'function',\n }\n );\n\n const { prehash } = eddsaOpts;\n const { BASE, Fp, Fn } = Point;\n\n const randomBytes = eddsaOpts.randomBytes || randomBytesWeb;\n const adjustScalarBytes = eddsaOpts.adjustScalarBytes || ((bytes: Uint8Array) => bytes);\n const domain =\n eddsaOpts.domain ||\n ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => {\n abool(phflag, 'phflag');\n if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n\n // Little-endian SHA512 with modulo n\n function modN_LE(hash: Uint8Array): bigint {\n return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit\n }\n\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key: Hex) {\n const len = lengths.secretKey;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n return { head, prefix, scalar };\n }\n\n /** Convenience method that creates public key from scalar. RFC8032 5.1.5 */\n function getExtendedPublicKey(secretKey: Hex) {\n const { head, prefix, scalar } = getPrivateScalar(secretKey);\n const point = BASE.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toBytes();\n return { head, prefix, scalar, point, pointBytes };\n }\n\n /** Calculates EdDSA pub key. RFC8032 5.1.5. */\n function getPublicKey(secretKey: Hex): Uint8Array {\n return getExtendedPublicKey(secretKey).pointBytes;\n }\n\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context: Hex = Uint8Array.of(), ...msgs: Uint8Array[]) {\n const msg = concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg: Hex, secretKey: Hex, options: { context?: Hex } = {}): Uint8Array {\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = BASE.multiply(r).toBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L\n if (!Fn.isValid(s)) throw new Error('sign failed: invalid s'); // 0 <= s < L\n const rs = concatBytes(R, Fn.toBytes(s));\n return abytes(rs, lengths.signature, 'result');\n }\n\n // verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\n const verifyOpts: { context?: Hex; zip215?: boolean } = { zip215: true };\n\n /**\n * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n * An extended group equation is checked.\n */\n function verify(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean {\n const { context, zip215 } = options;\n const len = lengths.signature;\n sig = ensureBytes('signature', sig, len);\n msg = ensureBytes('message', msg);\n publicKey = ensureBytes('publicKey', publicKey, lengths.publicKey);\n if (zip215 !== undefined) abool(zip215, 'zip215');\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const mid = len / 2;\n const r = sig.subarray(0, mid);\n const s = bytesToNumberLE(sig.subarray(mid, len));\n let A, R, SB;\n try {\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromBytes(publicKey, zip215);\n R = Point.fromBytes(r, zip215);\n SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder()) return false; // zip215 allows public keys of small order\n\n const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Extended group equation\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().is0();\n }\n\n const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448\n const lengths = {\n secretKey: _size,\n publicKey: _size,\n signature: 2 * _size,\n seed: _size,\n };\n function randomSecretKey(seed = randomBytes(lengths.seed)): Uint8Array {\n return abytes(seed, lengths.seed, 'seed');\n }\n function keygen(seed?: Uint8Array) {\n const secretKey = utils.randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n }\n function isValidSecretKey(key: Uint8Array): boolean {\n return isBytes(key) && key.length === Fn.BYTES;\n }\n function isValidPublicKey(key: Uint8Array, zip215?: boolean): boolean {\n try {\n return !!Point.fromBytes(key, zip215);\n } catch (error) {\n return false;\n }\n }\n\n const utils = {\n getExtendedPublicKey,\n randomSecretKey,\n isValidSecretKey,\n isValidPublicKey,\n /**\n * Converts ed public key to x public key. Uses formula:\n * - ed25519:\n * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * - ed448:\n * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`\n * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`\n */\n toMontgomery(publicKey: Uint8Array): Uint8Array {\n const { y } = Point.fromBytes(publicKey);\n const size = lengths.publicKey;\n const is25519 = size === 32;\n if (!is25519 && size !== 57) throw new Error('only defined for 25519 and 448');\n const u = is25519 ? Fp.div(_1n + y, _1n - y) : Fp.div(y - _1n, y + _1n);\n return Fp.toBytes(u);\n },\n\n toMontgomerySecret(secretKey: Uint8Array): Uint8Array {\n const size = lengths.secretKey;\n abytes(secretKey, size);\n const hashed = cHash(secretKey.subarray(0, size));\n return adjustScalarBytes(hashed).subarray(0, size);\n },\n\n /** @deprecated */\n randomPrivateKey: randomSecretKey,\n /** @deprecated */\n precompute(windowSize = 8, point: EdwardsPoint = Point.BASE): EdwardsPoint {\n return point.precompute(windowSize, false);\n },\n };\n\n return Object.freeze({\n keygen,\n getPublicKey,\n sign,\n verify,\n utils,\n Point,\n lengths,\n });\n}\n\n// TODO: remove everything below\nexport type CurveType = BasicCurve<bigint> & {\n a: bigint; // curve param a\n d: bigint; // curve param d\n /** @deprecated the property will be removed in next release */\n hash: FHash; // Hashing\n randomBytes?: (bytesLength?: number) => Uint8Array; // CSPRNG\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing\n uvRatio?: UVRatio; // Ratio \u221A(u/v)\n prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify()\n mapToCurve?: (scalar: bigint[]) => AffinePoint<bigint>; // for hash-to-curve standard\n};\nexport type CurveTypeWithLength = Readonly<CurveType & Partial<NLength>>;\nexport type CurveFn = {\n /** @deprecated the property will be removed in next release */\n CURVE: CurveType;\n keygen: EdDSA['keygen'];\n getPublicKey: EdDSA['getPublicKey'];\n sign: EdDSA['sign'];\n verify: EdDSA['verify'];\n Point: EdwardsPointCons;\n /** @deprecated use `Point` */\n ExtendedPoint: EdwardsPointCons;\n utils: EdDSA['utils'];\n lengths: CurveLengths;\n};\nexport type EdComposed = {\n CURVE: EdwardsOpts;\n curveOpts: EdwardsExtraOpts;\n hash: FHash;\n eddsaOpts: EdDSAOpts;\n};\nfunction _eddsa_legacy_opts_to_new(c: CurveTypeWithLength): EdComposed {\n const CURVE: EdwardsOpts = {\n a: c.a,\n d: c.d,\n p: c.Fp.ORDER,\n n: c.n,\n h: c.h,\n Gx: c.Gx,\n Gy: c.Gy,\n };\n const Fp = c.Fp;\n const Fn = Field(CURVE.n, c.nBitLength, true);\n const curveOpts: EdwardsExtraOpts = { Fp, Fn, uvRatio: c.uvRatio };\n const eddsaOpts: EdDSAOpts = {\n randomBytes: c.randomBytes,\n adjustScalarBytes: c.adjustScalarBytes,\n domain: c.domain,\n prehash: c.prehash,\n mapToCurve: c.mapToCurve,\n };\n return { CURVE, curveOpts, hash: c.hash, eddsaOpts };\n}\nfunction _eddsa_new_output_to_legacy(c: CurveTypeWithLength, eddsa: EdDSA): CurveFn {\n const Point = eddsa.Point;\n const legacy = Object.assign({}, eddsa, {\n ExtendedPoint: Point,\n CURVE: c,\n nBitLength: Point.Fn.BITS,\n nByteLength: Point.Fn.BYTES,\n });\n return legacy;\n}\n// TODO: remove. Use eddsa\nexport function twistedEdwards(c: CurveTypeWithLength): CurveFn {\n const { CURVE, curveOpts, hash, eddsaOpts } = _eddsa_legacy_opts_to_new(c);\n const Point = edwards(CURVE, curveOpts);\n const EDDSA = eddsa(Point, hash, eddsaOpts);\n return _eddsa_new_output_to_legacy(c, EDDSA);\n}\n", "/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, utf8ToBytes } from '@noble/hashes/utils.js';\nimport { pippenger, type AffinePoint } from './abstract/curve.ts';\nimport {\n PrimeEdwardsPoint,\n twistedEdwards,\n type CurveFn,\n type EdwardsOpts,\n type EdwardsPoint,\n} from './abstract/edwards.ts';\nimport {\n _DST_scalar,\n createHasher,\n expand_message_xmd,\n type H2CHasher,\n type H2CHasherBase,\n type H2CMethod,\n type htfBasicOpts,\n} from './abstract/hash-to-curve.ts';\nimport {\n Field,\n FpInvertBatch,\n FpSqrtEven,\n isNegativeLE,\n mod,\n pow2,\n type IField,\n} from './abstract/modular.ts';\nimport { montgomery, type MontgomeryECDH as XCurveFn } from './abstract/montgomery.ts';\nimport { bytesToNumberLE, ensureBytes, equalBytes, type Hex } from './utils.ts';\n\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\n\n// P = 2n**255n-19n\nconst ed25519_CURVE_p = BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed'\n);\n\n// N = 2n**252n + 27742317777372353535851937790883648493n\n// a = Fp.create(BigInt(-1))\n// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\nconst ed25519_CURVE: EdwardsOpts = /* @__PURE__ */ (() => ({\n p: ed25519_CURVE_p,\n n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),\n h: _8n,\n a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),\n d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),\n Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),\n Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),\n}))();\n\nfunction ed25519_pow_2_252_3(x: bigint) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ed25519_CURVE_p;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\n\nfunction adjustScalarBytes(bytes: Uint8Array): Uint8Array {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\n// Fp.sqrt(Fp.neg(1))\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt(\n '19681161376707505956807079304988542015446066515923890162744021073123829784752'\n);\n// sqrt(u/v)\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ed25519_CURVE_p;\n const v3 = mod(v * v * v, P); // v\u00B3\n const v7 = mod(v3 * v3 * v, P); // v\u2077\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv\u00B3)(uv\u2077)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx\u00B2\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx\u00B2 = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx\u00B2 = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx\u00B2 = -u\u221A(-1)\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P)) x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n\nconst Fp = /* @__PURE__ */ (() => Field(ed25519_CURVE.p, { isLE: true }))();\nconst Fn = /* @__PURE__ */ (() => Field(ed25519_CURVE.n, { isLE: true }))();\n\nconst ed25519Defaults = /* @__PURE__ */ (() => ({\n ...ed25519_CURVE,\n Fp,\n hash: sha512,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/\u221Av\n uvRatio,\n}))();\n\n/**\n * ed25519 curve with EdDSA signatures.\n * @example\n * import { ed25519 } from '@noble/curves/ed25519';\n * const { secretKey, publicKey } = ed25519.keygen();\n * const msg = new TextEncoder().encode('hello');\n * const sig = ed25519.sign(msg, priv);\n * ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215\n * ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5\n */\nexport const ed25519: CurveFn = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();\n\nfunction ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) {\n if (ctx.length > 255) throw new Error('Context is too big');\n return concatBytes(\n utf8ToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n );\n}\n\n/** Context of ed25519. Uses context for domain separation. */\nexport const ed25519ctx: CurveFn = /* @__PURE__ */ (() =>\n twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n }))();\n\n/** Prehashed version of ed25519. Accepts already-hashed messages in sign() and verify(). */\nexport const ed25519ph: CurveFn = /* @__PURE__ */ (() =>\n twistedEdwards(\n Object.assign({}, ed25519Defaults, {\n domain: ed25519_domain,\n prehash: sha512,\n })\n ))();\n\n/**\n * ECDH using curve25519 aka x25519.\n * @example\n * import { x25519 } from '@noble/curves/ed25519';\n * const priv = 'a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4';\n * const pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c';\n * x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases\n * x25519.getPublicKey(priv) === x25519.scalarMultBase(priv);\n * x25519.getPublicKey(x25519.utils.randomSecretKey());\n */\nexport const x25519: XCurveFn = /* @__PURE__ */ (() => {\n const P = Fp.ORDER;\n return montgomery({\n P,\n type: 'x25519',\n powPminus2: (x: bigint): bigint => {\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n },\n adjustScalarBytes,\n });\n})();\n\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\nconst ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u: bigint) {\n const ELL2_C4 = (ed25519_CURVE_p - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic\n const ELL2_J = BigInt(486662);\n\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J);// 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd!(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\n\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u: bigint) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division\n return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd)\n}\n\n/** Hashing to ed25519 points / field. RFC 9380 methods. */\nexport const ed25519_hasher: H2CHasher<bigint> = /* @__PURE__ */ (() =>\n createHasher(\n ed25519.Point,\n (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]),\n {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: ed25519_CURVE_p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\n ))();\n\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// \u221A(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt(\n '25063068953384623474111414158702152701244531502492656460079210482610430750235'\n);\n// 1 / \u221A(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt(\n '54469307008909316920995813868745141605393597292927456921205312896311721017578'\n);\n// 1-d\u00B2\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt(\n '1159843021668779879193775521855586647937357759715417654439879720876111806838'\n);\n// (d-1)\u00B2\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt(\n '40440834346308536858101042469323190826248399146238708352240133220865137265952'\n);\n// Calculates 1/\u221A(number)\nconst invertSqrt = (number: bigint) => uvRatio(_1n, number);\n\nconst MAX_255B = /* @__PURE__ */ BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'\n);\nconst bytes255ToNumberLE = (bytes: Uint8Array) =>\n ed25519.Point.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\ntype ExtendedPoint = EdwardsPoint;\n\n/**\n * Computes Elligator map for Ristretto255.\n * Described in [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#appendix-B) and on\n * the [website](https://ristretto.group/formulas/elligator.html).\n */\nfunction calcElligatorRistrettoMap(r0: bigint): ExtendedPoint {\n const { d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P)) s_ = mod(-s_);\n if (!Ns_D_is_sq) s = s_; // 7\n if (!Ns_D_is_sq) c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\nfunction ristretto255_map(bytes: Uint8Array): _RistrettoPoint {\n abytes(bytes, 64);\n const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new _RistrettoPoint(R1.add(R2));\n}\n\n/**\n * Wrapper over Edwards Point for ristretto255.\n *\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nclass _RistrettoPoint extends PrimeEdwardsPoint<_RistrettoPoint> {\n // Do NOT change syntax: the following gymnastics is done,\n // because typescript strips comments, which makes bundlers disable tree-shaking.\n // prettier-ignore\n static BASE: _RistrettoPoint =\n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.BASE))();\n // prettier-ignore\n static ZERO: _RistrettoPoint =\n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.ZERO))();\n // prettier-ignore\n static Fp: IField<bigint> =\n /* @__PURE__ */ (() => Fp)();\n // prettier-ignore\n static Fn: IField<bigint> =\n /* @__PURE__ */ (() => Fn)();\n\n constructor(ep: ExtendedPoint) {\n super(ep);\n }\n\n static fromAffine(ap: AffinePoint<bigint>): _RistrettoPoint {\n return new _RistrettoPoint(ed25519.Point.fromAffine(ap));\n }\n\n protected assertSame(other: _RistrettoPoint): void {\n if (!(other instanceof _RistrettoPoint)) throw new Error('RistrettoPoint expected');\n }\n\n protected init(ep: EdwardsPoint): _RistrettoPoint {\n return new _RistrettoPoint(ep);\n }\n\n /** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\n static hashToCurve(hex: Hex): _RistrettoPoint {\n return ristretto255_map(ensureBytes('ristrettoHash', hex, 64));\n }\n\n static fromBytes(bytes: Uint8Array): _RistrettoPoint {\n abytes(bytes, 32);\n const { a, d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const s = bytes255ToNumberLE(bytes);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))\n throw new Error('invalid ristretto255 encoding 1');\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P)) x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n)\n throw new Error('invalid ristretto255 encoding 2');\n return new _RistrettoPoint(new ed25519.Point(x, y, _1n, t));\n }\n\n /**\n * Converts ristretto-encoded string to ristretto point.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex: Hex): _RistrettoPoint {\n return _RistrettoPoint.fromBytes(ensureBytes('ristrettoHex', hex, 32));\n }\n\n static msm(points: _RistrettoPoint[], scalars: bigint[]): _RistrettoPoint {\n return pippenger(_RistrettoPoint, ed25519.Point.Fn, points, scalars);\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n */\n toBytes(): Uint8Array {\n let { X, Y, Z, T } = this.ep;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const u1 = mod(mod(Z + Y) * mod(Z - Y)); // 1\n const u2 = mod(X * Y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * T); // 6\n let D: bigint; // 7\n if (isNegativeLE(T * zInv, P)) {\n let _x = mod(Y * SQRT_M1);\n let _y = mod(X * SQRT_M1);\n X = _x;\n Y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n } else {\n D = D2; // 8\n }\n if (isNegativeLE(X * zInv, P)) Y = mod(-Y); // 9\n let s = mod((Z - Y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P)) s = mod(-s);\n return Fp.toBytes(s); // 11\n }\n\n /**\n * Compares two Ristretto points.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).\n */\n equals(other: _RistrettoPoint): boolean {\n this.assertSame(other);\n const { X: X1, Y: Y1 } = this.ep;\n const { X: X2, Y: Y2 } = other.ep;\n const mod = (n: bigint) => Fp.create(n);\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n\n is0(): boolean {\n return this.equals(_RistrettoPoint.ZERO);\n }\n}\n\nexport const ristretto255: {\n Point: typeof _RistrettoPoint;\n} = { Point: _RistrettoPoint };\n\n/** Hashing to ristretto255 points / field. RFC 9380 methods. */\nexport const ristretto255_hasher: H2CHasherBase<bigint> = {\n hashToCurve(msg: Uint8Array, options?: htfBasicOpts): _RistrettoPoint {\n const DST = options?.DST || 'ristretto255_XMD:SHA-512_R255MAP_RO_';\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n return ristretto255_map(xmd);\n },\n hashToScalar(msg: Uint8Array, options: htfBasicOpts = { DST: _DST_scalar }) {\n const xmd = expand_message_xmd(msg, options.DST, 64, sha512);\n return Fn.create(bytesToNumberLE(xmd));\n },\n};\n\n// export const ristretto255_oprf: OPRF = createORPF({\n// name: 'ristretto255-SHA512',\n// Point: RistrettoPoint,\n// hash: sha512,\n// hashToGroup: ristretto255_hasher.hashToCurve,\n// hashToScalar: ristretto255_hasher.hashToScalar,\n// });\n\n/**\n * Weird / bogus points, useful for debugging.\n * All 8 ed25519 points of 8-torsion subgroup can be generated from the point\n * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.\n * \u27E8T\u27E9 = { O, T, 2T, 3T, 4T, 5T, 6T, 7T }\n */\nexport const ED25519_TORSION_SUBGROUP: string[] = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n\n/** @deprecated use `ed25519.utils.toMontgomery` */\nexport function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array {\n return ed25519.utils.toMontgomery(ensureBytes('pub', edwardsPub));\n}\n/** @deprecated use `ed25519.utils.toMontgomery` */\nexport const edwardsToMontgomery: typeof edwardsToMontgomeryPub = edwardsToMontgomeryPub;\n\n/** @deprecated use `ed25519.utils.toMontgomerySecret` */\nexport function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array {\n return ed25519.utils.toMontgomerySecret(ensureBytes('pub', edwardsPriv));\n}\n\n/** @deprecated use `ristretto255.Point` */\nexport const RistrettoPoint: typeof _RistrettoPoint = _RistrettoPoint;\n/** @deprecated use `import { ed25519_hasher } from '@noble/curves/ed25519.js';` */\nexport const hashToCurve: H2CMethod<bigint> = /* @__PURE__ */ (() => ed25519_hasher.hashToCurve)();\n/** @deprecated use `import { ed25519_hasher } from '@noble/curves/ed25519.js';` */\nexport const encodeToCurve: H2CMethod<bigint> = /* @__PURE__ */ (() =>\n ed25519_hasher.encodeToCurve)();\ntype RistHasher = (msg: Uint8Array, options: htfBasicOpts) => _RistrettoPoint;\n/** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\nexport const hashToRistretto255: RistHasher = /* @__PURE__ */ (() =>\n ristretto255_hasher.hashToCurve as RistHasher)();\n/** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\nexport const hash_to_ristretto255: RistHasher = /* @__PURE__ */ (() =>\n ristretto255_hasher.hashToCurve as RistHasher)();\n", "import {\n DerDecodeErrorCode,\n DerDecodeLengthMismatchErrorCode,\n DerEncodeErrorCode,\n InputError,\n} from './errors.ts';\nimport { uint8Equals } from './utils/buffer.ts';\n\nexport const encodeLenBytes = (len: number): number => {\n if (len <= 0x7f) {\n return 1;\n } else if (len <= 0xff) {\n return 2;\n } else if (len <= 0xffff) {\n return 3;\n } else if (len <= 0xffffff) {\n return 4;\n } else {\n throw InputError.fromCode(new DerEncodeErrorCode('Length too long (> 4 bytes)'));\n }\n};\n\nexport const encodeLen = (buf: Uint8Array, offset: number, len: number): number => {\n if (len <= 0x7f) {\n buf[offset] = len;\n return 1;\n } else if (len <= 0xff) {\n buf[offset] = 0x81;\n buf[offset + 1] = len;\n return 2;\n } else if (len <= 0xffff) {\n buf[offset] = 0x82;\n buf[offset + 1] = len >> 8;\n buf[offset + 2] = len;\n return 3;\n } else if (len <= 0xffffff) {\n buf[offset] = 0x83;\n buf[offset + 1] = len >> 16;\n buf[offset + 2] = len >> 8;\n buf[offset + 3] = len;\n return 4;\n } else {\n throw InputError.fromCode(new DerEncodeErrorCode('Length too long (> 4 bytes)'));\n }\n};\n\nexport const decodeLenBytes = (buf: Uint8Array, offset: number): number => {\n if (buf[offset] < 0x80) return 1;\n if (buf[offset] === 0x80) throw InputError.fromCode(new DerDecodeErrorCode('Invalid length 0'));\n if (buf[offset] === 0x81) return 2;\n if (buf[offset] === 0x82) return 3;\n if (buf[offset] === 0x83) return 4;\n throw InputError.fromCode(new DerDecodeErrorCode('Length too long (> 4 bytes)'));\n};\n\nexport const decodeLen = (buf: Uint8Array, offset: number): number => {\n const lenBytes = decodeLenBytes(buf, offset);\n if (lenBytes === 1) return buf[offset];\n else if (lenBytes === 2) return buf[offset + 1];\n else if (lenBytes === 3) return (buf[offset + 1] << 8) + buf[offset + 2];\n else if (lenBytes === 4)\n return (buf[offset + 1] << 16) + (buf[offset + 2] << 8) + buf[offset + 3];\n throw InputError.fromCode(new DerDecodeErrorCode('Length too long (> 4 bytes)'));\n};\n\n/**\n * A DER encoded `SEQUENCE(OID)` for DER-encoded-COSE\n */\nexport const DER_COSE_OID = Uint8Array.from([\n ...[0x30, 0x0c], // SEQUENCE\n ...[0x06, 0x0a], // OID with 10 bytes\n ...[0x2b, 0x06, 0x01, 0x04, 0x01, 0x83, 0xb8, 0x43, 0x01, 0x01], // DER encoded COSE\n]);\n\n/**\n * A DER encoded `SEQUENCE(OID)` for the Ed25519 algorithm\n */\nexport const ED25519_OID = Uint8Array.from([\n ...[0x30, 0x05], // SEQUENCE\n ...[0x06, 0x03], // OID with 3 bytes\n ...[0x2b, 0x65, 0x70], // id-Ed25519 OID\n]);\n\n/**\n * A DER encoded `SEQUENCE(OID)` for secp256k1 with the ECDSA algorithm\n */\nexport const SECP256K1_OID = Uint8Array.from([\n ...[0x30, 0x10], // SEQUENCE\n ...[0x06, 0x07], // OID with 7 bytes\n ...[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01], // OID ECDSA\n ...[0x06, 0x05], // OID with 5 bytes\n ...[0x2b, 0x81, 0x04, 0x00, 0x0a], // OID secp256k1\n]);\n\nexport const BLS12_381_G2_OID = Uint8Array.from([\n ...[0x30, 0x1d], // SEQUENCE, length 29 bytes\n // Algorithm OID\n ...[0x06, 0x0d],\n ...[0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xdc, 0x7c, 0x05, 0x03, 0x01, 0x02, 0x01],\n // Curve OID\n ...[0x06, 0x0c],\n ...[0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xdc, 0x7c, 0x05, 0x03, 0x02, 0x01],\n]);\n\n/**\n * Wraps the given `payload` in a DER encoding tagged with the given encoded `oid` like so:\n * `SEQUENCE(oid, BITSTRING(payload))`\n * @param payload The payload to encode as the bit string\n * @param oid The DER encoded (and SEQUENCE wrapped!) OID to tag the payload with\n */\nexport function wrapDER(payload: Uint8Array, oid: Uint8Array): Uint8Array {\n // The Bit String header needs to include the unused bit count byte in its length\n const bitStringHeaderLength = 2 + encodeLenBytes(payload.byteLength + 1);\n const len = oid.byteLength + bitStringHeaderLength + payload.byteLength;\n let offset = 0;\n const buf = new Uint8Array(1 + encodeLenBytes(len) + len);\n // Sequence\n buf[offset++] = 0x30;\n // Sequence Length\n offset += encodeLen(buf, offset, len);\n\n // OID\n buf.set(oid, offset);\n offset += oid.byteLength;\n\n // Bit String Header\n buf[offset++] = 0x03;\n offset += encodeLen(buf, offset, payload.byteLength + 1);\n // 0 padding\n buf[offset++] = 0x00;\n buf.set(new Uint8Array(payload), offset);\n\n return buf;\n}\n\n/**\n * Extracts a payload from the given `derEncoded` data, and checks that it was tagged with the given `oid`.\n *\n * `derEncoded = SEQUENCE(oid, BITSTRING(payload))`\n * @param derEncoded The DER encoded and tagged data\n * @param oid The DER encoded (and SEQUENCE wrapped!) expected OID\n * @returns The unwrapped payload\n */\nexport const unwrapDER = (derEncoded: Uint8Array, oid: Uint8Array): Uint8Array => {\n let offset = 0;\n const expect = (n: number, msg: string) => {\n if (buf[offset++] !== n) {\n throw InputError.fromCode(new DerDecodeErrorCode(`Expected ${msg} at offset ${offset}`));\n }\n };\n\n const buf = new Uint8Array(derEncoded);\n expect(0x30, 'sequence');\n offset += decodeLenBytes(buf, offset);\n\n if (!uint8Equals(buf.slice(offset, offset + oid.byteLength), oid)) {\n throw InputError.fromCode(new DerDecodeErrorCode('Not the expected OID.'));\n }\n offset += oid.byteLength;\n\n expect(0x03, 'bit string');\n const payloadLen = decodeLen(buf, offset) - 1; // Subtracting 1 to account for the 0 padding\n offset += decodeLenBytes(buf, offset);\n expect(0x00, '0 padding');\n const result = buf.slice(offset);\n if (payloadLen !== result.length) {\n throw InputError.fromCode(new DerDecodeLengthMismatchErrorCode(payloadLen, result.length));\n }\n return result;\n};\n", "import {\n type DerEncodedPublicKey,\n type KeyPair,\n type PublicKey,\n type Signature,\n SignIdentity,\n ED25519_OID,\n unwrapDER,\n wrapDER,\n} from '@dfinity/agent';\nimport { uint8Equals, uint8FromBufLike } from '@dfinity/candid';\nimport { ed25519 } from '@noble/curves/ed25519';\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils';\n\ndeclare type KeyLike = PublicKey | DerEncodedPublicKey | ArrayBuffer | ArrayBufferView;\n\nfunction isObject(value: unknown) {\n return value !== null && typeof value === 'object';\n}\n\nexport class Ed25519PublicKey implements PublicKey {\n /**\n * Construct Ed25519PublicKey from an existing PublicKey\n * @param {unknown} maybeKey - existing PublicKey, ArrayBuffer, DerEncodedPublicKey, or hex string\n * @returns {Ed25519PublicKey} Instance of Ed25519PublicKey\n */\n public static from(maybeKey: unknown): Ed25519PublicKey {\n if (typeof maybeKey === 'string') {\n const key = hexToBytes(maybeKey);\n return this.fromRaw(key);\n } else if (isObject(maybeKey)) {\n const key = maybeKey as KeyLike;\n if (isObject(key) && Object.hasOwnProperty.call(key, '__derEncodedPublicKey__')) {\n return this.fromDer(key as DerEncodedPublicKey);\n } else if (ArrayBuffer.isView(key)) {\n const view = key as ArrayBufferView;\n return this.fromRaw(uint8FromBufLike(view.buffer));\n } else if (key instanceof ArrayBuffer) {\n return this.fromRaw(uint8FromBufLike(key));\n } else if ('rawKey' in key && key.rawKey instanceof Uint8Array) {\n return this.fromRaw(key.rawKey);\n } else if ('derKey' in key) {\n return this.fromDer(key.derKey as DerEncodedPublicKey);\n } else if ('toDer' in key) {\n return this.fromDer(key.toDer());\n }\n }\n throw new Error('Cannot construct Ed25519PublicKey from the provided key.');\n }\n\n public static fromRaw(rawKey: Uint8Array): Ed25519PublicKey {\n return new Ed25519PublicKey(rawKey);\n }\n\n public static fromDer(derKey: DerEncodedPublicKey): Ed25519PublicKey {\n return new Ed25519PublicKey(this.derDecode(derKey));\n }\n\n // The length of Ed25519 public keys is always 32 bytes.\n private static RAW_KEY_LENGTH = 32;\n\n private static derEncode(publicKey: Uint8Array): DerEncodedPublicKey {\n const key = wrapDER(publicKey, ED25519_OID) as DerEncodedPublicKey;\n key.__derEncodedPublicKey__ = undefined;\n return key;\n }\n\n private static derDecode(key: DerEncodedPublicKey): Uint8Array {\n const unwrapped = unwrapDER(key, ED25519_OID);\n if (unwrapped.length !== this.RAW_KEY_LENGTH) {\n throw new Error('An Ed25519 public key must be exactly 32bytes long');\n }\n return unwrapped;\n }\n\n #rawKey: Uint8Array;\n\n public get rawKey(): Uint8Array {\n return this.#rawKey;\n }\n\n #derKey: DerEncodedPublicKey;\n\n public get derKey(): DerEncodedPublicKey {\n return this.#derKey;\n }\n\n // `fromRaw` and `fromDer` should be used for instantiation, not this constructor.\n private constructor(key: Uint8Array) {\n if (key.byteLength !== Ed25519PublicKey.RAW_KEY_LENGTH) {\n throw new Error('An Ed25519 public key must be exactly 32bytes long');\n }\n this.#rawKey = key;\n this.#derKey = Ed25519PublicKey.derEncode(key);\n }\n\n public toDer(): DerEncodedPublicKey {\n return this.derKey;\n }\n\n public toRaw(): Uint8Array {\n return this.rawKey;\n }\n}\n\n/**\n * Ed25519KeyIdentity is an implementation of SignIdentity that uses Ed25519 keys. This class is used to sign and verify messages for an agent.\n */\nexport class Ed25519KeyIdentity extends SignIdentity {\n /**\n * Generate a new Ed25519KeyIdentity.\n * @param seed a 32-byte seed for the private key. If not provided, a random seed will be generated.\n * @returns Ed25519KeyIdentity\n */\n public static generate(seed?: Uint8Array): Ed25519KeyIdentity {\n if (seed && seed.length !== 32) {\n throw new Error('Ed25519 Seed needs to be 32 bytes long.');\n }\n if (!seed) seed = ed25519.utils.randomPrivateKey();\n // Check if the seed is all zeros\n if (uint8Equals(seed, new Uint8Array(new Array(32).fill(0)))) {\n console.warn(\n 'Seed is all zeros. This is not a secure seed. Please provide a seed with sufficient entropy if this is a production environment.',\n );\n }\n const sk = new Uint8Array(32);\n for (let i = 0; i < 32; i++) {\n sk[i] = seed[i];\n }\n\n const pk = ed25519.getPublicKey(sk);\n return Ed25519KeyIdentity.fromKeyPair(pk, sk);\n }\n\n public static fromParsedJson(obj: JsonnableEd25519KeyIdentity): Ed25519KeyIdentity {\n const [publicKeyDer, privateKeyRaw] = obj;\n return new Ed25519KeyIdentity(\n Ed25519PublicKey.fromDer(hexToBytes(publicKeyDer) as DerEncodedPublicKey),\n hexToBytes(privateKeyRaw),\n );\n }\n\n public static fromJSON(json: string): Ed25519KeyIdentity {\n const parsed = JSON.parse(json);\n if (Array.isArray(parsed)) {\n if (typeof parsed[0] === 'string' && typeof parsed[1] === 'string') {\n return this.fromParsedJson([parsed[0], parsed[1]]);\n } else {\n throw new Error('Deserialization error: JSON must have at least 2 items.');\n }\n }\n throw new Error(`Deserialization error: Invalid JSON type for string: ${JSON.stringify(json)}`);\n }\n\n public static fromKeyPair(publicKey: Uint8Array, privateKey: Uint8Array): Ed25519KeyIdentity {\n return new Ed25519KeyIdentity(Ed25519PublicKey.fromRaw(publicKey), privateKey);\n }\n\n public static fromSecretKey(secretKey: Uint8Array): Ed25519KeyIdentity {\n const publicKey = ed25519.getPublicKey(secretKey);\n return Ed25519KeyIdentity.fromKeyPair(publicKey, secretKey);\n }\n\n #publicKey: Ed25519PublicKey;\n #privateKey: Uint8Array;\n\n // `fromRaw` and `fromDer` should be used for instantiation, not this constructor.\n protected constructor(publicKey: PublicKey, privateKey: Uint8Array) {\n super();\n this.#publicKey = Ed25519PublicKey.from(publicKey);\n this.#privateKey = privateKey;\n }\n\n /**\n * Serialize this key to JSON.\n */\n public toJSON(): JsonnableEd25519KeyIdentity {\n return [bytesToHex(this.#publicKey.toDer()), bytesToHex(this.#privateKey)];\n }\n\n /**\n * Return a copy of the key pair.\n */\n public getKeyPair(): KeyPair {\n return {\n secretKey: this.#privateKey,\n publicKey: this.#publicKey,\n };\n }\n\n /**\n * Return the public key.\n */\n public getPublicKey(): Required<PublicKey> {\n return this.#publicKey;\n }\n\n /**\n * Signs a blob of data, with this identity's private key.\n * @param challenge - challenge to sign with this identity's secretKey, producing a signature\n */\n public async sign(challenge: Uint8Array): Promise<Signature> {\n // Some implementations of Ed25519 private keys append a public key to the end of the private key. We only want the private key.\n const signature = ed25519.sign(challenge, this.#privateKey.slice(0, 32));\n // add { __signature__: void; } to the signature to make it compatible with the agent\n\n Object.defineProperty(signature, '__signature__', {\n enumerable: false,\n value: undefined,\n });\n\n return signature as Signature;\n }\n\n /**\n * Verify\n * @param sig - signature to verify\n * @param msg - message to verify\n * @param pk - public key\n * @returns - true if the signature is valid, false otherwise\n */\n public static verify(\n sig: ArrayBuffer | Uint8Array | string,\n msg: ArrayBuffer | Uint8Array | string,\n pk: ArrayBuffer | Uint8Array | string,\n ) {\n const [signature, message, publicKey] = [sig, msg, pk].map(x => {\n if (typeof x === 'string') {\n x = hexToBytes(x);\n }\n return uint8FromBufLike(x);\n });\n return ed25519.verify(signature, message, publicKey);\n }\n}\n\ntype PublicKeyHex = string;\ntype SecretKeyHex = string;\nexport type JsonnableEd25519KeyIdentity = [PublicKeyHex, SecretKeyHex];\n", "import {\n type DerEncodedPublicKey,\n type PublicKey,\n type Signature,\n SignIdentity,\n} from '@dfinity/agent';\nimport { uint8FromBufLike } from '@dfinity/candid';\n\n/**\n * Options used in a {@link ECDSAKeyIdentity}\n */\nexport type CryptoKeyOptions = {\n extractable?: boolean;\n keyUsages?: KeyUsage[];\n subtleCrypto?: SubtleCrypto;\n};\n\nexport class CryptoError extends Error {\n constructor(public readonly message: string) {\n super(message);\n Object.setPrototypeOf(this, CryptoError.prototype);\n }\n}\n\nexport interface DerCryptoKey extends CryptoKey {\n toDer: () => DerEncodedPublicKey;\n}\n\n/**\n * Utility method to ensure that a subtleCrypto implementation is provided or is available in the global context\n * @param subtleCrypto SubtleCrypto implementation\n * @returns subleCrypto\n */\nfunction _getEffectiveCrypto(subtleCrypto: CryptoKeyOptions['subtleCrypto']): SubtleCrypto {\n if (typeof global !== 'undefined' && global['crypto'] && global['crypto']['subtle']) {\n return global['crypto']['subtle'];\n }\n if (subtleCrypto) {\n return subtleCrypto;\n } else if (typeof crypto !== 'undefined' && crypto['subtle']) {\n return crypto.subtle;\n } else {\n throw new CryptoError(\n 'Global crypto was not available and none was provided. Please inlcude a SubtleCrypto implementation. See https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto',\n );\n }\n}\n\n/**\n * An identity interface that wraps an ECDSA keypair using the P-256 named curve. Supports DER-encoding and decoding for agent calls\n */\nexport class ECDSAKeyIdentity extends SignIdentity {\n /**\n * Generates a randomly generated identity for use in calls to the Internet Computer.\n * @param {CryptoKeyOptions} options optional settings\n * @param {CryptoKeyOptions['extractable']} options.extractable - whether the key should allow itself to be used. Set to false for maximum security.\n * @param {CryptoKeyOptions['keyUsages']} options.keyUsages - a list of key usages that the key can be used for\n * @param {CryptoKeyOptions['subtleCrypto']} options.subtleCrypto interface\n * @returns a {@link ECDSAKeyIdentity}\n */\n public static async generate(options?: CryptoKeyOptions): Promise<ECDSAKeyIdentity> {\n const { extractable = false, keyUsages = ['sign', 'verify'], subtleCrypto } = options ?? {};\n const effectiveCrypto = _getEffectiveCrypto(subtleCrypto);\n const keyPair = await effectiveCrypto.generateKey(\n {\n name: 'ECDSA',\n namedCurve: 'P-256',\n },\n extractable,\n keyUsages,\n );\n const derKey: DerEncodedPublicKey = uint8FromBufLike(\n await effectiveCrypto.exportKey('spki', keyPair.publicKey),\n );\n\n Object.assign(derKey, {\n __derEncodedPublicKey__: undefined,\n });\n\n return new this(keyPair, derKey, effectiveCrypto);\n }\n\n /**\n * generates an identity from a public and private key. Please ensure that you are generating these keys securely and protect the user's private key\n * @param keyPair a CryptoKeyPair\n * @param subtleCrypto - a SubtleCrypto interface in case one is not available globally\n * @returns an {@link ECDSAKeyIdentity}\n */\n public static async fromKeyPair(\n keyPair: CryptoKeyPair | { privateKey: CryptoKey; publicKey: CryptoKey },\n subtleCrypto?: SubtleCrypto,\n ): Promise<ECDSAKeyIdentity> {\n const effectiveCrypto = _getEffectiveCrypto(subtleCrypto);\n const derKey: DerEncodedPublicKey = uint8FromBufLike(\n await effectiveCrypto.exportKey('spki', keyPair.publicKey),\n );\n Object.assign(derKey, {\n __derEncodedPublicKey__: undefined,\n });\n return new ECDSAKeyIdentity(keyPair, derKey, effectiveCrypto);\n }\n\n protected _derKey: DerEncodedPublicKey;\n protected _keyPair: CryptoKeyPair;\n protected _subtleCrypto: SubtleCrypto;\n\n // `fromKeyPair` and `generate` should be used for instantiation, not this constructor.\n protected constructor(\n keyPair: CryptoKeyPair,\n derKey: DerEncodedPublicKey,\n subtleCrypto: SubtleCrypto,\n ) {\n super();\n this._keyPair = keyPair;\n this._derKey = derKey;\n this._subtleCrypto = subtleCrypto;\n }\n\n /**\n * Return the internally-used key pair.\n * @returns a CryptoKeyPair\n */\n public getKeyPair(): CryptoKeyPair {\n return this._keyPair;\n }\n\n /**\n * Return the public key.\n * @returns an {@link PublicKey & DerCryptoKey}\n */\n public getPublicKey(): PublicKey & DerCryptoKey {\n const derKey = this._derKey;\n const key: DerCryptoKey = Object.create(this._keyPair.publicKey);\n key.toDer = function () {\n return derKey;\n };\n\n return key;\n }\n\n /**\n * Signs a blob of data, with this identity's private key.\n * @param {Uint8Array} challenge - challenge to sign with this identity's secretKey, producing a signature\n * @returns {Promise<Signature>} signature\n */\n public async sign(challenge: Uint8Array): Promise<Signature> {\n const params: EcdsaParams = {\n name: 'ECDSA',\n hash: { name: 'SHA-256' },\n };\n const signature = uint8FromBufLike(\n await this._subtleCrypto.sign(params, this._keyPair.privateKey, challenge),\n );\n\n Object.assign(signature, {\n __signature__: undefined,\n });\n\n return signature as Signature;\n }\n}\n\nexport default ECDSAKeyIdentity;\n", "import { type Identity, type PublicKey } from '@dfinity/agent';\nimport { Principal } from '@dfinity/principal';\n\n/**\n * A partial delegated identity, representing a delegation chain and the public key that it targets\n */\nexport class PartialIdentity implements Identity {\n #inner: PublicKey;\n\n /**\n * The raw public key of this identity.\n */\n get rawKey(): Uint8Array | undefined {\n return this.#inner.rawKey;\n }\n\n /**\n * The DER-encoded public key of this identity.\n */\n get derKey(): Uint8Array | undefined {\n return this.#inner.derKey;\n }\n\n /**\n * The DER-encoded public key of this identity.\n */\n public toDer(): Uint8Array {\n return this.#inner.toDer();\n }\n\n /**\n * The inner {@link PublicKey} used by this identity.\n */\n public getPublicKey(): PublicKey {\n return this.#inner;\n }\n\n /**\n * The {@link Principal} of this identity.\n */\n public getPrincipal(): Principal {\n if (!this.#inner.rawKey) {\n throw new Error('Cannot get principal from a public key without a raw key.');\n }\n return Principal.fromUint8Array(new Uint8Array(this.#inner.rawKey));\n }\n\n /**\n * Required for the Identity interface, but cannot implemented for just a public key.\n */\n public transformRequest(): Promise<never> {\n return Promise.reject(\n 'Not implemented. You are attempting to use a partial identity to sign calls, but this identity only has access to the public key.To sign calls, use a DelegationIdentity instead.',\n );\n }\n\n constructor(inner: PublicKey) {\n this.#inner = inner;\n }\n}\n", "import {\n type DerEncodedPublicKey,\n type HttpAgentRequest,\n type PublicKey,\n requestIdOf,\n type Signature,\n SignIdentity,\n IC_REQUEST_DOMAIN_SEPARATOR,\n IC_REQUEST_AUTH_DELEGATION_DOMAIN_SEPARATOR,\n ToCborValue,\n} from '@dfinity/agent';\nimport { Principal } from '@dfinity/principal';\nimport { PartialIdentity } from './partial.ts';\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils';\n\n/**\n * Safe wrapper around bytesToHex that handles ArrayBuffer/Uint8Array type conversion.\n * Required because @noble/hashes v1.8+ strictly expects Uint8Array inputs.\n * @param data The binary data to convert to hexadecimal string (ArrayBuffer, Uint8Array, or ArrayLike<number>)\n */\nfunction safeBytesToHex(data: ArrayBuffer | Uint8Array | ArrayLike<number>): string {\n if (data instanceof Uint8Array) {\n return bytesToHex(data);\n }\n return bytesToHex(new Uint8Array(data));\n}\n\nfunction _parseBlob(value: unknown): Uint8Array {\n if (typeof value !== 'string' || value.length < 64) {\n throw new Error('Invalid public key.');\n }\n\n return hexToBytes(value);\n}\n\n/**\n * A single delegation object that is signed by a private key. This is constructed by\n * `DelegationChain.create()`.\n *\n * {@see DelegationChain}\n */\nexport class Delegation implements ToCborValue {\n constructor(\n public readonly pubkey: Uint8Array,\n public readonly expiration: bigint,\n public readonly targets?: Principal[],\n ) {}\n\n public toCborValue() {\n return {\n pubkey: this.pubkey,\n expiration: this.expiration,\n ...(this.targets && {\n targets: this.targets,\n }),\n };\n }\n\n public toJSON(): JsonnableDelegation {\n // every string should be hex and once-de-hexed,\n // discoverable what it is (e.g. de-hex to get JSON with a 'type' property, or de-hex to DER\n // with an OID). After de-hex, if it's not obvious what it is, it's an ArrayBuffer.\n return {\n expiration: this.expiration.toString(16),\n pubkey: safeBytesToHex(this.pubkey),\n ...(this.targets && { targets: this.targets.map(p => p.toHex()) }),\n };\n }\n}\n\n/**\n * Type of ReturnType<Delegation.toJSON>.\n * The goal here is to stringify all non-JSON-compatible types to some bytes representation we can\n * stringify as hex.\n * (Hex shouldn't be ambiguous ever, because you can encode as DER with semantic OIDs).\n */\ninterface JsonnableDelegation {\n // A BigInt of Nanoseconds since epoch as hex\n expiration: string;\n // Hexadecimal representation of the DER public key.\n pubkey: string;\n // Array of strings, where each string is hex of principal blob (*NOT* textual representation).\n targets?: string[];\n}\n\n/**\n * A signed delegation, which lends its identity to the public key in the delegation\n * object. This is constructed by `DelegationChain.create()`.\n *\n * {@see DelegationChain}\n */\nexport interface SignedDelegation {\n delegation: Delegation;\n signature: Signature;\n}\n\n/**\n * Sign a single delegation object for a period of time.\n * @param from The identity that lends its delegation.\n * @param to The identity that receives the delegation.\n * @param expiration An expiration date for this delegation.\n * @param targets Limit this delegation to the target principals.\n */\nasync function _createSingleDelegation(\n from: SignIdentity,\n to: PublicKey,\n expiration: Date,\n targets?: Principal[],\n): Promise<SignedDelegation> {\n const delegation: Delegation = new Delegation(\n to.toDer(),\n BigInt(+expiration) * BigInt(1000000), // In nanoseconds.\n targets,\n );\n // The signature is calculated by signing the concatenation of the domain separator\n // and the message.\n // Note: To ensure Safari treats this as a user gesture, ensure to not use async methods\n // besides the actualy webauthn functionality (such as `sign`). Safari will de-register\n // a user gesture if you await an async call thats not fetch, xhr, or setTimeout.\n const challenge = new Uint8Array([\n ...IC_REQUEST_AUTH_DELEGATION_DOMAIN_SEPARATOR,\n ...new Uint8Array(requestIdOf({ ...delegation })),\n ]);\n const signature = await from.sign(challenge);\n\n return {\n delegation,\n signature,\n };\n}\n\nexport interface JsonnableDelegationChain {\n publicKey: string;\n delegations: Array<{\n signature: string;\n delegation: {\n pubkey: string;\n expiration: string;\n targets?: string[];\n };\n }>;\n}\n\n/**\n * A chain of delegations. This is JSON Serializable.\n * This is the object to serialize and pass to a DelegationIdentity. It does not keep any\n * private keys.\n */\nexport class DelegationChain {\n /**\n * Create a delegation chain between two (or more) keys. By default, the expiration time\n * will be very short (15 minutes).\n *\n * To build a chain of more than 2 identities, this function needs to be called multiple times,\n * passing the previous delegation chain into the options argument. For example:\n * @example\n * const rootKey = createKey();\n * const middleKey = createKey();\n * const bottomeKey = createKey();\n *\n * const rootToMiddle = await DelegationChain.create(\n * root, middle.getPublicKey(), Date.parse('2100-01-01'),\n * );\n * const middleToBottom = await DelegationChain.create(\n * middle, bottom.getPublicKey(), Date.parse('2100-01-01'), { previous: rootToMiddle },\n * );\n *\n * // We can now use a delegation identity that uses the delegation above:\n * const identity = DelegationIdentity.fromDelegation(bottomKey, middleToBottom);\n * @param from The identity that will delegate.\n * @param to The identity that gets delegated. It can now sign messages as if it was the\n * identity above.\n * @param expiration The length the delegation is valid. By default, 15 minutes from calling\n * this function.\n * @param options A set of options for this delegation. expiration and previous\n * @param options.previous - Another DelegationChain that this chain should start with.\n * @param options.targets - targets that scope the delegation (e.g. Canister Principals)\n */\n public static async create(\n from: SignIdentity,\n to: PublicKey,\n expiration: Date = new Date(Date.now() + 15 * 60 * 1000),\n options: {\n previous?: DelegationChain;\n targets?: Principal[];\n } = {},\n ): Promise<DelegationChain> {\n const delegation = await _createSingleDelegation(from, to, expiration, options.targets);\n return new DelegationChain(\n [...(options.previous?.delegations || []), delegation],\n options.previous?.publicKey || from.getPublicKey().toDer(),\n );\n }\n\n /**\n * Creates a DelegationChain object from a JSON string.\n * @param json The JSON string to parse.\n */\n public static fromJSON(json: string | JsonnableDelegationChain): DelegationChain {\n const { publicKey, delegations } = typeof json === 'string' ? JSON.parse(json) : json;\n if (!Array.isArray(delegations)) {\n throw new Error('Invalid delegations.');\n }\n\n const parsedDelegations: SignedDelegation[] = delegations.map(signedDelegation => {\n const { delegation, signature } = signedDelegation;\n const { pubkey, expiration, targets } = delegation;\n if (targets !== undefined && !Array.isArray(targets)) {\n throw new Error('Invalid targets.');\n }\n\n return {\n delegation: new Delegation(\n _parseBlob(pubkey),\n BigInt('0x' + expiration), // expiration in JSON is an hexa string (See toJSON() below).\n targets &&\n targets.map((t: unknown) => {\n if (typeof t !== 'string') {\n throw new Error('Invalid target.');\n }\n return Principal.fromHex(t);\n }),\n ),\n signature: _parseBlob(signature) as Signature,\n };\n });\n\n return new this(parsedDelegations, _parseBlob(publicKey) as DerEncodedPublicKey);\n }\n\n /**\n * Creates a DelegationChain object from a list of delegations and a DER-encoded public key.\n * @param delegations The list of delegations.\n * @param publicKey The DER-encoded public key of the key-pair signing the first delegation.\n */\n public static fromDelegations(\n delegations: SignedDelegation[],\n publicKey: DerEncodedPublicKey,\n ): DelegationChain {\n return new this(delegations, publicKey);\n }\n\n protected constructor(\n public readonly delegations: SignedDelegation[],\n public readonly publicKey: DerEncodedPublicKey,\n ) {}\n\n public toJSON(): JsonnableDelegationChain {\n return {\n delegations: this.delegations.map(signedDelegation => {\n const { delegation, signature } = signedDelegation;\n const { targets } = delegation;\n return {\n delegation: {\n expiration: delegation.expiration.toString(16),\n pubkey: safeBytesToHex(delegation.pubkey),\n ...(targets && {\n targets: targets.map(t => t.toHex()),\n }),\n },\n signature: safeBytesToHex(signature),\n };\n }),\n publicKey: safeBytesToHex(this.publicKey),\n };\n }\n}\n\n/**\n * An Identity that adds delegation to a request. Everywhere in this class, the name\n * innerKey refers to the SignIdentity that is being used to sign the requests, while\n * originalKey is the identity that is being borrowed. More identities can be used\n * in the middle to delegate.\n */\nexport class DelegationIdentity extends SignIdentity {\n /**\n * Create a delegation without having access to delegateKey.\n * @param key The key used to sign the requests.\n * @param delegation A delegation object created using `createDelegation`.\n */\n public static fromDelegation(\n key: Pick<SignIdentity, 'sign'>,\n delegation: DelegationChain,\n ): DelegationIdentity {\n return new this(key, delegation);\n }\n\n protected constructor(\n private _inner: Pick<SignIdentity, 'sign'>,\n private _delegation: DelegationChain,\n ) {\n super();\n }\n\n public getDelegation(): DelegationChain {\n return this._delegation;\n }\n\n public getPublicKey(): PublicKey {\n return {\n derKey: this._delegation.publicKey,\n toDer: () => this._delegation.publicKey,\n };\n }\n public sign(blob: Uint8Array): Promise<Signature> {\n return this._inner.sign(blob);\n }\n\n public async transformRequest(request: HttpAgentRequest): Promise<unknown> {\n const { body, ...fields } = request;\n const requestId = await requestIdOf(body);\n return {\n ...fields,\n body: {\n content: body,\n sender_sig: await this.sign(\n new Uint8Array([...IC_REQUEST_DOMAIN_SEPARATOR, ...new Uint8Array(requestId)]),\n ),\n sender_delegation: this._delegation.delegations,\n sender_pubkey: this._delegation.publicKey,\n },\n };\n }\n}\n\n/**\n * A partial delegated identity, representing a delegation chain and the public key that it targets\n */\nexport class PartialDelegationIdentity extends PartialIdentity {\n #delegation: DelegationChain;\n\n /**\n * The Delegation Chain of this identity.\n */\n get delegation(): DelegationChain {\n return this.#delegation;\n }\n\n private constructor(inner: PublicKey, delegation: DelegationChain) {\n super(inner);\n this.#delegation = delegation;\n }\n\n /**\n * Create a {@link PartialDelegationIdentity} from a {@link PublicKey} and a {@link DelegationChain}.\n * @param key The {@link PublicKey} to delegate to.\n * @param delegation a {@link DelegationChain} targeting the inner key.\n */\n public static fromDelegation(key: PublicKey, delegation: DelegationChain) {\n return new PartialDelegationIdentity(key, delegation);\n }\n}\n\n/**\n * List of things to check for a delegation chain validity.\n */\nexport interface DelegationValidChecks {\n /**\n * Check that the scope is amongst the scopes that this delegation has access to.\n */\n scope?: Principal | string | Array<Principal | string>;\n}\n\n/**\n * Analyze a DelegationChain and validate that it's valid, ie. not expired and apply to the\n * scope.\n * @param chain The chain to validate.\n * @param checks Various checks to validate on the chain.\n */\nexport function isDelegationValid(chain: DelegationChain, checks?: DelegationValidChecks): boolean {\n // Verify that the no delegation is expired. If any are in the chain, returns false.\n for (const { delegation } of chain.delegations) {\n // prettier-ignore\n if (+new Date(Number(delegation.expiration / BigInt(1000000))) <= +Date.now()) {\n return false;\n }\n }\n\n // Check the scopes.\n const scopes: Principal[] = [];\n const maybeScope = checks?.scope;\n if (maybeScope) {\n if (Array.isArray(maybeScope)) {\n scopes.push(...maybeScope.map(s => (typeof s === 'string' ? Principal.fromText(s) : s)));\n } else {\n scopes.push(typeof maybeScope === 'string' ? Principal.fromText(maybeScope) : maybeScope);\n }\n }\n\n for (const s of scopes) {\n const scope = s.toText();\n for (const { delegation } of chain.delegations) {\n if (delegation.targets === undefined) {\n continue;\n }\n\n let none = true;\n for (const target of delegation.targets) {\n if (target.toText() === scope) {\n none = false;\n break;\n }\n }\n if (none) {\n return false;\n }\n }\n }\n\n return true;\n}\n", "type IdleCB = () => unknown;\n\nexport type IdleManagerOptions = {\n /**\n * Callback after the user has gone idle\n */\n onIdle?: IdleCB;\n /**\n * timeout in ms\n * @default 30 minutes [600_000]\n */\n idleTimeout?: number;\n /**\n * capture scroll events\n * @default false\n */\n captureScroll?: boolean;\n /**\n * scroll debounce time in ms\n * @default 100\n */\n scrollDebounce?: number;\n};\n\nconst events = ['mousedown', 'mousemove', 'keydown', 'touchstart', 'wheel'];\n\n/**\n * Detects if the user has been idle for a duration of `idleTimeout` ms, and calls `onIdle` and registered callbacks.\n * By default, the IdleManager will log a user out after 10 minutes of inactivity.\n * To override these defaults, you can pass an `onIdle` callback, or configure a custom `idleTimeout` in milliseconds\n */\nexport class IdleManager {\n callbacks: IdleCB[] = [];\n idleTimeout: IdleManagerOptions['idleTimeout'] = 10 * 60 * 1000;\n timeoutID?: number = undefined;\n\n /**\n * Creates an {@link IdleManager}\n * @param {IdleManagerOptions} options Optional configuration\n * @see {@link IdleManagerOptions}\n * @param options.onIdle Callback once user has been idle. Use to prompt for fresh login, and use `Actor.agentOf(your_actor).invalidateIdentity()` to protect the user\n * @param options.idleTimeout timeout in ms\n * @param options.captureScroll capture scroll events\n * @param options.scrollDebounce scroll debounce time in ms\n */\n public static create(\n options: {\n /**\n * Callback after the user has gone idle\n * @see {@link IdleCB}\n */\n onIdle?: () => unknown;\n /**\n * timeout in ms\n * @default 10 minutes [600_000]\n */\n idleTimeout?: number;\n /**\n * capture scroll events\n * @default false\n */\n captureScroll?: boolean;\n /**\n * scroll debounce time in ms\n * @default 100\n */\n scrollDebounce?: number;\n } = {},\n ): IdleManager {\n return new IdleManager(options);\n }\n\n /**\n * @protected\n * @param options {@link IdleManagerOptions}\n */\n protected constructor(options: IdleManagerOptions = {}) {\n const { onIdle, idleTimeout = 10 * 60 * 1000 } = options || {};\n\n this.callbacks = onIdle ? [onIdle] : [];\n this.idleTimeout = idleTimeout;\n\n const _resetTimer = this._resetTimer.bind(this);\n\n window.addEventListener('load', _resetTimer, true);\n\n events.forEach((name) => {\n document.addEventListener(name, _resetTimer, true);\n });\n\n const debounce = (func: (...args: unknown[]) => void, wait: number) => {\n let timeout: number | undefined;\n return (...args: unknown[]) => {\n const context = this;\n const later = () => {\n timeout = undefined;\n func.apply(context, args);\n };\n clearTimeout(timeout);\n timeout = window.setTimeout(later, wait);\n };\n };\n\n if (options?.captureScroll) {\n // debounce scroll events\n const scroll = debounce(_resetTimer, options?.scrollDebounce ?? 100);\n window.addEventListener('scroll', scroll, true);\n }\n\n _resetTimer();\n }\n\n /**\n * @param {IdleCB} callback function to be called when user goes idle\n */\n public registerCallback(callback: IdleCB): void {\n this.callbacks.push(callback);\n }\n\n /**\n * Cleans up the idle manager and its listeners\n */\n public exit(): void {\n clearTimeout(this.timeoutID);\n window.removeEventListener('load', this._resetTimer, true);\n\n const _resetTimer = this._resetTimer.bind(this);\n events.forEach((name) => {\n document.removeEventListener(name, _resetTimer, true);\n });\n this.callbacks.forEach((cb) => {\n cb();\n });\n }\n\n /**\n * Resets the timeouts during cleanup\n */\n _resetTimer(): void {\n const exit = this.exit.bind(this);\n window.clearTimeout(this.timeoutID);\n this.timeoutID = window.setTimeout(exit, this.idleTimeout);\n }\n}\n", "const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n", "import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);\n });\n }\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event.newVersion, event));\n }\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking) {\n db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));\n }\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event));\n }\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n", "import { type IDBPDatabase, openDB } from 'idb';\nimport { DB_VERSION, KEY_STORAGE_DELEGATION, KEY_STORAGE_KEY } from './storage.ts';\n\ntype Database = IDBPDatabase<unknown>;\ntype IDBValidKey = string | number | Date | BufferSource | IDBValidKey[];\nconst AUTH_DB_NAME = 'auth-client-db';\nconst OBJECT_STORE_NAME = 'ic-keyval';\n\nconst _openDbStore = async (\n dbName = AUTH_DB_NAME,\n storeName = OBJECT_STORE_NAME,\n version: number,\n) => {\n // Clear legacy stored delegations\n if (globalThis.localStorage?.getItem(KEY_STORAGE_DELEGATION)) {\n globalThis.localStorage.removeItem(KEY_STORAGE_DELEGATION);\n globalThis.localStorage.removeItem(KEY_STORAGE_KEY);\n }\n return await openDB(dbName, version, {\n upgrade: (database) => {\n if (database.objectStoreNames.contains(storeName)) {\n database.clear(storeName);\n }\n database.createObjectStore(storeName);\n },\n });\n};\n\nasync function _getValue<T>(\n db: Database,\n storeName: string,\n key: IDBValidKey,\n): Promise<T | undefined> {\n return await db.get(storeName, key);\n}\n\nasync function _setValue<T>(\n db: Database,\n storeName: string,\n key: IDBValidKey,\n value: T,\n): Promise<IDBValidKey> {\n return await db.put(storeName, value, key);\n}\n\nasync function _removeValue(db: Database, storeName: string, key: IDBValidKey): Promise<void> {\n return await db.delete(storeName, key);\n}\n\nexport type DBCreateOptions = {\n dbName?: string;\n storeName?: string;\n version?: number;\n};\n\n/**\n * Simple Key Value store\n * Defaults to `'auth-client-db'` with an object store of `'ic-keyval'`\n */\nexport class IdbKeyVal {\n /**\n * @param {DBCreateOptions} options - DBCreateOptions\n * @param {DBCreateOptions['dbName']} options.dbName name for the indexeddb database\n * @default\n * @param {DBCreateOptions['storeName']} options.storeName name for the indexeddb Data Store\n * @default\n * @param {DBCreateOptions['version']} options.version version of the database. Increment to safely upgrade\n */\n public static async create(options?: DBCreateOptions): Promise<IdbKeyVal> {\n const {\n dbName = AUTH_DB_NAME,\n storeName = OBJECT_STORE_NAME,\n version = DB_VERSION,\n } = options ?? {};\n const db = await _openDbStore(dbName, storeName, version);\n return new IdbKeyVal(db, storeName);\n }\n\n // Do not use - instead prefer create\n private constructor(\n private _db: Database,\n private _storeName: string,\n ) {}\n\n /**\n * Basic setter\n * @param {IDBValidKey} key string | number | Date | BufferSource | IDBValidKey[]\n * @param value value to set\n * @returns void\n */\n public async set<T>(key: IDBValidKey, value: T) {\n return await _setValue<T>(this._db, this._storeName, key, value);\n }\n /**\n * Basic getter\n * Pass in a type T for type safety if you know the type the value will have if it is found\n * @param {IDBValidKey} key string | number | Date | BufferSource | IDBValidKey[]\n * @returns `Promise<T | null>`\n * @example\n * await get<string>('exampleKey') -> 'exampleValue'\n */\n public async get<T>(key: IDBValidKey): Promise<T | null> {\n return (await _getValue<T>(this._db, this._storeName, key)) ?? null;\n }\n\n /**\n * Remove a key\n * @param key {@link IDBValidKey}\n * @returns void\n */\n public async remove(key: IDBValidKey) {\n return await _removeValue(this._db, this._storeName, key);\n }\n}\n", "import { type DBCreateOptions, IdbKeyVal } from './db.ts';\n\nexport const KEY_STORAGE_KEY = 'identity';\nexport const KEY_STORAGE_DELEGATION = 'delegation';\nexport const KEY_VECTOR = 'iv';\n// Increment if any fields are modified\nexport const DB_VERSION = 1;\n\nexport type StoredKey = string | CryptoKeyPair;\n\n/**\n * Interface for persisting user authentication data\n */\nexport interface AuthClientStorage {\n get(key: string): Promise<StoredKey | null>;\n\n set(key: string, value: StoredKey): Promise<void>;\n\n remove(key: string): Promise<void>;\n}\n\n/**\n * Legacy implementation of AuthClientStorage, for use where IndexedDb is not available\n */\nexport class LocalStorage implements AuthClientStorage {\n constructor(\n public readonly prefix = 'ic-',\n private readonly _localStorage?: Storage,\n ) {}\n\n public get(key: string): Promise<string | null> {\n return Promise.resolve(this._getLocalStorage().getItem(this.prefix + key));\n }\n\n public set(key: string, value: string): Promise<void> {\n this._getLocalStorage().setItem(this.prefix + key, value);\n return Promise.resolve();\n }\n\n public remove(key: string): Promise<void> {\n this._getLocalStorage().removeItem(this.prefix + key);\n return Promise.resolve();\n }\n\n private _getLocalStorage() {\n if (this._localStorage) {\n return this._localStorage;\n }\n\n const ls = globalThis.localStorage;\n if (!ls) {\n throw new Error('Could not find local storage.');\n }\n\n return ls;\n }\n}\n\n/**\n * IdbStorage is an interface for simple storage of string key-value pairs built on {@link IdbKeyVal}\n *\n * It replaces {@link LocalStorage}\n * @see implements {@link AuthClientStorage}\n */\nexport class IdbStorage implements AuthClientStorage {\n #options: DBCreateOptions;\n\n /**\n * @param options - DBCreateOptions\n * @param options.dbName - name for the indexeddb database\n * @param options.storeName - name for the indexeddb Data Store\n * @param options.version - version of the database. Increment to safely upgrade\n * @example\n * ```ts\n * const storage = new IdbStorage({ dbName: 'my-db', storeName: 'my-store', version: 2 });\n * ```\n */\n constructor(options?: DBCreateOptions) {\n this.#options = options ?? {};\n }\n\n // Initializes a KeyVal on first request\n private initializedDb: IdbKeyVal | undefined;\n get _db(): Promise<IdbKeyVal> {\n return new Promise((resolve, reject) => {\n if (this.initializedDb) {\n resolve(this.initializedDb);\n return;\n }\n IdbKeyVal.create(this.#options)\n .then((db) => {\n this.initializedDb = db;\n resolve(db);\n })\n .catch(reject);\n });\n }\n\n public async get<T = string>(key: string): Promise<T | null> {\n const db = await this._db;\n return await db.get<T>(key);\n // return (await db.get<string>(key)) ?? null;\n }\n\n public async set<T = string>(key: string, value: T): Promise<void> {\n const db = await this._db;\n await db.set(key, value);\n }\n\n public async remove(key: string): Promise<void> {\n const db = await this._db;\n await db.remove(key);\n }\n}\n", "import {\n AnonymousIdentity,\n type DerEncodedPublicKey,\n type Identity,\n type Signature,\n type SignIdentity,\n} from '@icp-sdk/core/agent';\nimport {\n Delegation,\n DelegationChain,\n DelegationIdentity,\n ECDSAKeyIdentity,\n Ed25519KeyIdentity,\n isDelegationValid,\n PartialDelegationIdentity,\n type PartialIdentity,\n} from '@icp-sdk/core/identity';\nimport type { Principal } from '@icp-sdk/core/principal';\nimport { IdleManager, type IdleManagerOptions } from './idle-manager.ts';\nimport {\n type AuthClientStorage,\n IdbStorage,\n KEY_STORAGE_DELEGATION,\n KEY_STORAGE_KEY,\n KEY_VECTOR,\n LocalStorage,\n type StoredKey,\n} from './storage.ts';\n\nconst NANOSECONDS_PER_SECOND = BigInt(1_000_000_000);\nconst SECONDS_PER_HOUR = BigInt(3_600);\nconst NANOSECONDS_PER_HOUR = NANOSECONDS_PER_SECOND * SECONDS_PER_HOUR;\n\nconst IDENTITY_PROVIDER_DEFAULT = 'https://identity.internetcomputer.org';\nconst IDENTITY_PROVIDER_ENDPOINT = '#authorize';\n\nconst DEFAULT_MAX_TIME_TO_LIVE = BigInt(8) * NANOSECONDS_PER_HOUR;\n\nconst ECDSA_KEY_LABEL = 'ECDSA';\nconst ED25519_KEY_LABEL = 'Ed25519';\ntype BaseKeyType = typeof ECDSA_KEY_LABEL | typeof ED25519_KEY_LABEL;\n\nconst INTERRUPT_CHECK_INTERVAL = 500;\n\nexport const ERROR_USER_INTERRUPT = 'UserInterrupt';\n\n/**\n * List of options for creating an {@link AuthClient}.\n */\nexport interface AuthClientCreateOptions {\n /**\n * An {@link SignIdentity} or {@link PartialIdentity} to authenticate via delegation.\n */\n identity?: SignIdentity | PartialIdentity;\n /**\n * Optional storage with get, set, and remove. Uses {@link IdbStorage} by default.\n * @see {@link AuthClientStorage}\n */\n storage?: AuthClientStorage;\n\n /**\n * Type to use for the base key.\n *\n * If you are using a custom storage provider that does not support CryptoKey storage,\n * you should use `Ed25519` as the key type, as it can serialize to a string.\n * @default 'ECDSA'\n */\n keyType?: BaseKeyType;\n\n /**\n * Options to handle idle timeouts\n * @default after 10 minutes, invalidates the identity\n */\n idleOptions?: IdleOptions;\n\n /**\n * Options to handle login, passed to the login method\n */\n loginOptions?: AuthClientLoginOptions;\n}\n\nexport interface IdleOptions extends IdleManagerOptions {\n /**\n * Disables idle functionality for {@link IdleManager}\n * @default false\n */\n disableIdle?: boolean;\n\n /**\n * Disables default idle behavior - call logout & reload window\n * @default false\n */\n disableDefaultIdleCallback?: boolean;\n}\n\nexport type OnSuccessFunc =\n | (() => void | Promise<void>)\n | ((message: InternetIdentityAuthResponseSuccess) => void | Promise<void>);\n\nexport type OnErrorFunc = (error?: string) => void | Promise<void>;\n\nexport interface AuthClientLoginOptions {\n /**\n * Identity provider\n * @default \"https://identity.internetcomputer.org\"\n */\n identityProvider?: string | URL;\n /**\n * Expiration of the authentication in nanoseconds\n * @default BigInt(8) hours * BigInt(3_600_000_000_000) nanoseconds\n */\n maxTimeToLive?: bigint;\n /**\n * If present, indicates whether or not the Identity Provider should allow the user to authenticate and/or register using a temporary key/PIN identity. Authenticating dapps may want to prevent users from using Temporary keys/PIN identities because Temporary keys/PIN identities are less secure than Passkeys (webauthn credentials) and because Temporary keys/PIN identities generally only live in a browser database (which may get cleared by the browser/OS).\n */\n allowPinAuthentication?: boolean;\n /**\n * Origin for Identity Provider to use while generating the delegated identity. For II, the derivation origin must authorize this origin by setting a record at `<derivation-origin>/.well-known/ii-alternative-origins`.\n * @see https://github.com/dfinity/internet-identity/blob/main/docs/internet-identity-spec.adoc\n */\n derivationOrigin?: string | URL;\n /**\n * Auth Window feature config string\n * @example \"toolbar=0,location=0,menubar=0,width=500,height=500,left=100,top=100\"\n */\n windowOpenerFeatures?: string;\n /**\n * Callback once login has completed\n */\n onSuccess?: OnSuccessFunc;\n /**\n * Callback in case authentication fails\n */\n onError?: OnErrorFunc;\n /**\n * Extra values to be passed in the login request during the authorize-ready phase\n */\n customValues?: Record<string, unknown>;\n}\n\ninterface InternetIdentityAuthRequest {\n kind: 'authorize-client';\n sessionPublicKey: Uint8Array;\n maxTimeToLive?: bigint;\n allowPinAuthentication?: boolean;\n derivationOrigin?: string;\n}\n\nexport interface InternetIdentityAuthResponseSuccess {\n kind: 'authorize-client-success';\n delegations: {\n delegation: {\n pubkey: Uint8Array;\n expiration: bigint;\n targets?: Principal[];\n };\n signature: Uint8Array;\n }[];\n userPublicKey: Uint8Array;\n authnMethod: 'passkey' | 'pin' | 'recovery';\n}\n\ninterface AuthReadyMessage {\n kind: 'authorize-ready';\n}\n\ninterface AuthResponseSuccess {\n kind: 'authorize-client-success';\n delegations: {\n delegation: {\n pubkey: Uint8Array;\n expiration: bigint;\n targets?: Principal[];\n };\n signature: Uint8Array;\n }[];\n userPublicKey: Uint8Array;\n authnMethod: 'passkey' | 'pin' | 'recovery';\n}\n\ninterface AuthResponseFailure {\n kind: 'authorize-client-failure';\n text: string;\n}\n\ntype IdentityServiceResponseMessage = AuthReadyMessage | AuthResponse;\ntype AuthResponse = AuthResponseSuccess | AuthResponseFailure;\n\n/**\n * Tool to manage authentication and identity\n * @see {@link AuthClient}\n */\nexport class AuthClient {\n /**\n * Create an AuthClient to manage authentication and identity\n * @param {AuthClientCreateOptions} options - Options for creating an {@link AuthClient}\n * @see {@link AuthClientCreateOptions}\n * @param options.identity Optional Identity to use as the base\n * @see {@link SignIdentity}\n * @param options.storage Storage mechanism for delegation credentials\n * @see {@link AuthClientStorage}\n * @param options.keyType Type of key to use for the base key\n * @param {IdleOptions} options.idleOptions Configures an {@link IdleManager}\n * @see {@link IdleOptions}\n * Default behavior is to clear stored identity and reload the page when a user goes idle, unless you set the disableDefaultIdleCallback flag or pass in a custom idle callback.\n * @example\n * const authClient = await AuthClient.create({\n * idleOptions: {\n * disableIdle: true\n * }\n * })\n */\n public static async create(options: AuthClientCreateOptions = {}): Promise<AuthClient> {\n const storage = options.storage ?? new IdbStorage();\n const keyType = options.keyType ?? ECDSA_KEY_LABEL;\n\n let key: null | SignIdentity | PartialIdentity = null;\n if (options.identity) {\n key = options.identity;\n } else {\n let maybeIdentityStorage = await storage.get(KEY_STORAGE_KEY);\n if (!maybeIdentityStorage) {\n // Attempt to migrate from localstorage\n try {\n const fallbackLocalStorage = new LocalStorage();\n const localChain = await fallbackLocalStorage.get(KEY_STORAGE_DELEGATION);\n const localKey = await fallbackLocalStorage.get(KEY_STORAGE_KEY);\n // not relevant for Ed25519\n if (localChain && localKey && keyType === ECDSA_KEY_LABEL) {\n console.log('Discovered an identity stored in localstorage. Migrating to IndexedDB');\n await storage.set(KEY_STORAGE_DELEGATION, localChain);\n await storage.set(KEY_STORAGE_KEY, localKey);\n\n maybeIdentityStorage = localChain;\n // clean up\n await fallbackLocalStorage.remove(KEY_STORAGE_DELEGATION);\n await fallbackLocalStorage.remove(KEY_STORAGE_KEY);\n }\n } catch (error) {\n console.error(`error while attempting to recover localstorage: ${error}`);\n }\n }\n if (maybeIdentityStorage) {\n try {\n if (typeof maybeIdentityStorage === 'object') {\n if (keyType === ED25519_KEY_LABEL && typeof maybeIdentityStorage === 'string') {\n key = Ed25519KeyIdentity.fromJSON(maybeIdentityStorage);\n } else {\n key = await ECDSAKeyIdentity.fromKeyPair(maybeIdentityStorage);\n }\n } else if (typeof maybeIdentityStorage === 'string') {\n // This is a legacy identity, which is a serialized Ed25519KeyIdentity.\n key = Ed25519KeyIdentity.fromJSON(maybeIdentityStorage);\n }\n } catch {\n // Ignore this, this means that the localStorage value isn't a valid Ed25519KeyIdentity or ECDSAKeyIdentity\n // serialization.\n }\n }\n }\n\n let identity: SignIdentity | PartialIdentity = new AnonymousIdentity() as PartialIdentity;\n let chain: null | DelegationChain = null;\n if (key) {\n try {\n const chainStorage = await storage.get(KEY_STORAGE_DELEGATION);\n if (typeof chainStorage === 'object' && chainStorage !== null) {\n throw new Error(\n 'Delegation chain is incorrectly stored. A delegation chain should be stored as a string.',\n );\n }\n\n if (options.identity) {\n identity = options.identity;\n } else if (chainStorage) {\n chain = DelegationChain.fromJSON(chainStorage);\n\n // Verify that the delegation isn't expired.\n if (!isDelegationValid(chain)) {\n await _deleteStorage(storage);\n key = null;\n } else {\n // If the key is a public key, then we create a PartialDelegationIdentity.\n if ('toDer' in key) {\n identity = PartialDelegationIdentity.fromDelegation(key, chain);\n // otherwise, we create a DelegationIdentity.\n } else {\n identity = DelegationIdentity.fromDelegation(key, chain);\n }\n }\n }\n } catch (e) {\n console.error(e);\n // If there was a problem loading the chain, delete the key.\n await _deleteStorage(storage);\n key = null;\n }\n }\n let idleManager: IdleManager | undefined;\n if (options.idleOptions?.disableIdle) {\n idleManager = undefined;\n }\n // if there is a delegation chain or provided identity, setup idleManager\n else if (chain || options.identity) {\n idleManager = IdleManager.create(options.idleOptions);\n }\n\n if (!key) {\n // Create a new key (whether or not one was in storage).\n if (keyType === ED25519_KEY_LABEL) {\n key = Ed25519KeyIdentity.generate();\n } else {\n if (options.storage && keyType === ECDSA_KEY_LABEL) {\n console.warn(\n `You are using a custom storage provider that may not support CryptoKey storage. If you are using a custom storage provider that does not support CryptoKey storage, you should use '${ED25519_KEY_LABEL}' as the key type, as it can serialize to a string`,\n );\n }\n key = await ECDSAKeyIdentity.generate();\n }\n await persistKey(storage, key);\n }\n\n return new AuthClient(identity, key, chain, storage, idleManager, options);\n }\n\n protected constructor(\n private _identity: Identity | PartialIdentity,\n private _key: SignIdentity | PartialIdentity,\n private _chain: DelegationChain | null,\n private _storage: AuthClientStorage,\n public idleManager: IdleManager | undefined,\n private _createOptions: AuthClientCreateOptions | undefined,\n // A handle on the IdP window.\n private _idpWindow?: Window,\n // The event handler for processing events from the IdP.\n private _eventHandler?: (event: MessageEvent) => void,\n ) {\n this._registerDefaultIdleCallback();\n }\n\n private _registerDefaultIdleCallback() {\n const idleOptions = this._createOptions?.idleOptions;\n /**\n * Default behavior is to clear stored identity and reload the page.\n * By either setting the disableDefaultIdleCallback flag or passing in a custom idle callback, we will ignore this config\n */\n if (!idleOptions?.onIdle && !idleOptions?.disableDefaultIdleCallback) {\n this.idleManager?.registerCallback(() => {\n this.logout();\n location.reload();\n });\n }\n }\n\n private async _handleSuccess(\n message: InternetIdentityAuthResponseSuccess,\n onSuccess?: OnSuccessFunc,\n ) {\n const delegations = message.delegations.map((signedDelegation) => {\n return {\n delegation: new Delegation(\n signedDelegation.delegation.pubkey,\n signedDelegation.delegation.expiration,\n signedDelegation.delegation.targets,\n ),\n signature: signedDelegation.signature as Signature,\n };\n });\n\n const delegationChain = DelegationChain.fromDelegations(\n delegations,\n message.userPublicKey as DerEncodedPublicKey,\n );\n\n const key = this._key;\n if (!key) {\n return;\n }\n\n this._chain = delegationChain;\n\n if ('toDer' in key) {\n this._identity = PartialDelegationIdentity.fromDelegation(key, this._chain);\n } else {\n this._identity = DelegationIdentity.fromDelegation(key, this._chain);\n }\n\n this._idpWindow?.close();\n const idleOptions = this._createOptions?.idleOptions;\n // create the idle manager on a successful login if we haven't disabled it\n // and it doesn't already exist.\n if (!this.idleManager && !idleOptions?.disableIdle) {\n this.idleManager = IdleManager.create(idleOptions);\n this._registerDefaultIdleCallback();\n }\n\n this._removeEventListener();\n delete this._idpWindow;\n\n if (this._chain) {\n await this._storage.set(KEY_STORAGE_DELEGATION, JSON.stringify(this._chain.toJSON()));\n }\n\n // Ensure the stored key in persistent storage matches the in-memory key that\n // was used to obtain the delegation. This avoids key/delegation mismatches\n // across multiple tabs overwriting each other's cached keys.\n await persistKey(this._storage, this._key);\n\n // onSuccess should be the last thing to do to avoid consumers\n // interfering by navigating or refreshing the page\n onSuccess?.(message);\n }\n\n public getIdentity(): Identity {\n return this._identity;\n }\n\n public async isAuthenticated(): Promise<boolean> {\n return (\n !this.getIdentity().getPrincipal().isAnonymous() &&\n this._chain !== null &&\n isDelegationValid(this._chain)\n );\n }\n\n /**\n * AuthClient Login - Opens up a new window to authenticate with Internet Identity\n * @param {AuthClientLoginOptions} options - Options for logging in, merged with the options set during creation if any. Note: we only perform a shallow merge for the `customValues` property.\n * @param options.identityProvider Identity provider\n * @param options.maxTimeToLive Expiration of the authentication in nanoseconds\n * @param options.allowPinAuthentication If present, indicates whether or not the Identity Provider should allow the user to authenticate and/or register using a temporary key/PIN identity. Authenticating dapps may want to prevent users from using Temporary keys/PIN identities because Temporary keys/PIN identities are less secure than Passkeys (webauthn credentials) and because Temporary keys/PIN identities generally only live in a browser database (which may get cleared by the browser/OS).\n * @param options.derivationOrigin Origin for Identity Provider to use while generating the delegated identity\n * @param options.windowOpenerFeatures Configures the opened authentication window\n * @param options.onSuccess Callback once login has completed\n * @param options.onError Callback in case authentication fails\n * @param options.customValues Extra values to be passed in the login request during the authorize-ready phase. Note: we only perform a shallow merge for the `customValues` property.\n * @example\n * const authClient = await AuthClient.create();\n * authClient.login({\n * identityProvider: 'http://<canisterID>.127.0.0.1:8000',\n * maxTimeToLive: BigInt (7) * BigInt(24) * BigInt(3_600_000_000_000), // 1 week\n * windowOpenerFeatures: \"toolbar=0,location=0,menubar=0,width=500,height=500,left=100,top=100\",\n * onSuccess: () => {\n * console.log('Login Successful!');\n * },\n * onError: (error) => {\n * console.error('Login Failed: ', error);\n * }\n * });\n */\n public async login(options?: AuthClientLoginOptions): Promise<void> {\n // Merge the passed options with the options set during creation\n const loginOptions = mergeLoginOptions(this._createOptions?.loginOptions, options);\n\n // Set default maxTimeToLive to 8 hours\n const maxTimeToLive = loginOptions?.maxTimeToLive ?? DEFAULT_MAX_TIME_TO_LIVE;\n\n // Create the URL of the IDP. (e.g. https://XXXX/#authorize)\n const identityProviderUrl = new URL(\n loginOptions?.identityProvider?.toString() || IDENTITY_PROVIDER_DEFAULT,\n );\n // Set the correct hash if it isn't already set.\n identityProviderUrl.hash = IDENTITY_PROVIDER_ENDPOINT;\n\n // If `login` has been called previously, then close/remove any previous windows\n // and event listeners.\n this._idpWindow?.close();\n this._removeEventListener();\n\n // Add an event listener to handle responses.\n this._eventHandler = this._getEventHandler(identityProviderUrl, {\n maxTimeToLive,\n ...loginOptions,\n });\n window.addEventListener('message', this._eventHandler);\n\n // Open a new window with the IDP provider.\n this._idpWindow =\n window.open(\n identityProviderUrl.toString(),\n 'idpWindow',\n loginOptions?.windowOpenerFeatures,\n ) ?? undefined;\n\n // Check if the _idpWindow is closed by user.\n const checkInterruption = (): void => {\n // The _idpWindow is opened and not yet closed by the client\n if (this._idpWindow) {\n if (this._idpWindow.closed) {\n this._handleFailure(ERROR_USER_INTERRUPT, loginOptions?.onError);\n } else {\n setTimeout(checkInterruption, INTERRUPT_CHECK_INTERVAL);\n }\n }\n };\n checkInterruption();\n }\n\n private _getEventHandler(identityProviderUrl: URL, options?: AuthClientLoginOptions) {\n return async (event: MessageEvent) => {\n if (event.origin !== identityProviderUrl.origin) {\n // Ignore any event that is not from the identity provider\n return;\n }\n\n const message = event.data as IdentityServiceResponseMessage;\n\n switch (message.kind) {\n case 'authorize-ready': {\n // IDP is ready. Send a message to request authorization.\n const request: InternetIdentityAuthRequest = {\n kind: 'authorize-client',\n sessionPublicKey: new Uint8Array(this._key?.getPublicKey().toDer()),\n maxTimeToLive: options?.maxTimeToLive,\n allowPinAuthentication: options?.allowPinAuthentication,\n derivationOrigin: options?.derivationOrigin?.toString(),\n // Pass any custom values to the IDP.\n ...options?.customValues,\n };\n this._idpWindow?.postMessage(request, identityProviderUrl.origin);\n break;\n }\n case 'authorize-client-success':\n // Create the delegation chain and store it.\n try {\n await this._handleSuccess(message, options?.onSuccess);\n } catch (err) {\n this._handleFailure((err as Error).message, options?.onError);\n }\n break;\n case 'authorize-client-failure':\n this._handleFailure(message.text, options?.onError);\n break;\n default:\n break;\n }\n };\n }\n\n private _handleFailure(errorMessage?: string, onError?: (error?: string) => void): void {\n this._idpWindow?.close();\n onError?.(errorMessage);\n this._removeEventListener();\n delete this._idpWindow;\n }\n\n private _removeEventListener() {\n if (this._eventHandler) {\n window.removeEventListener('message', this._eventHandler);\n }\n this._eventHandler = undefined;\n }\n\n public async logout(options: { returnTo?: string } = {}): Promise<void> {\n await _deleteStorage(this._storage);\n\n // Reset this auth client to a non-authenticated state.\n this._identity = new AnonymousIdentity();\n this._chain = null;\n\n if (options.returnTo) {\n try {\n window.history.pushState({}, '', options.returnTo);\n } catch {\n window.location.href = options.returnTo;\n }\n }\n }\n}\n\nasync function _deleteStorage(storage: AuthClientStorage) {\n await storage.remove(KEY_STORAGE_KEY);\n await storage.remove(KEY_STORAGE_DELEGATION);\n await storage.remove(KEY_VECTOR);\n}\n\nfunction mergeLoginOptions(\n loginOptions: AuthClientLoginOptions | undefined,\n otherLoginOptions: AuthClientLoginOptions | undefined,\n): AuthClientLoginOptions | undefined {\n if (!loginOptions && !otherLoginOptions) {\n return undefined;\n }\n\n const customValues =\n loginOptions?.customValues || otherLoginOptions?.customValues\n ? {\n ...loginOptions?.customValues,\n ...otherLoginOptions?.customValues,\n }\n : undefined;\n\n return {\n ...loginOptions,\n ...otherLoginOptions,\n customValues,\n };\n}\n\nfunction toStoredKey(key: SignIdentity | PartialIdentity): StoredKey {\n if (key instanceof ECDSAKeyIdentity) {\n return key.getKeyPair();\n }\n if (key instanceof Ed25519KeyIdentity) {\n return JSON.stringify(key.toJSON());\n }\n throw new Error('Unsupported key type');\n}\n\nasync function persistKey(\n storage: AuthClientStorage,\n key: SignIdentity | PartialIdentity,\n): Promise<void> {\n const serialized = toStoredKey(key);\n await storage.set(KEY_STORAGE_KEY, serialized);\n}\n", "// How long the delegation identity should remain valid?\n// e.g. BigInt(7 * 24 * 60 * 60 * 1000 * 1000 * 1000) = 7 days in nanoseconds\n// For Juno: 4 hours\nexport const DELEGATION_IDENTITY_EXPIRATION_IN_MILLISECONDS = 4 * 60 * 60 * 1000;\nexport const DELEGATION_IDENTITY_EXPIRATION = BigInt(\n DELEGATION_IDENTITY_EXPIRATION_IN_MILLISECONDS * 1000 * 1000\n);\n\n// We consider PIN authentication as \"insecure\" because users can easily lose their PIN if they do not register a passphrase, especially since Safari clears the browser cache every two weeks in cases of inactivity.\n// That's why we disable it by default.\nexport const ALLOW_PIN_AUTHENTICATION = false;\n\ninterface PopupSize {\n width: number;\n height: number;\n}\n\nexport const II_DESIGN_V1_POPUP: PopupSize = {width: 576, height: 576};\nexport const II_DESIGN_V2_POPUP: PopupSize = {width: 424, height: 576};\nexport const NFID_POPUP: PopupSize = {width: 505, height: 705};\n\nexport const INTERNET_COMPUTER_ORG = 'internetcomputer.org';\nexport const IC0_APP = 'ic0.app';\nexport const ID_AI = 'id.ai';\n\n// Worker\nexport const AUTH_TIMER_INTERVAL = 1000;\n", "export enum FromStringToTokenError {\n FractionalMoreThan8Decimals,\n InvalidFormat,\n FractionalTooManyDecimals,\n}\n", "export const E8S_PER_TOKEN = BigInt(100000000);\n", "import { E8S_PER_TOKEN } from \"../constants/constants\";\nimport { FromStringToTokenError } from \"../enums/token.enums\";\n\nconst DECIMALS_CONVERSION_SUPPORTED = 8;\n\n/**\n * Receives a string representing a number and returns the big int or error.\n *\n * @param amount - in string format\n * @returns bigint | FromStringToTokenError\n */\nexport const convertStringToE8s = (\n value: string,\n): bigint | FromStringToTokenError => {\n // replace exponential format (1e-4) with plain (0.0001)\n // doesn't support decimals for values >= ~1e16\n let amount = value.includes(\"e\")\n ? Number(value).toLocaleString(\"en\", {\n useGrouping: false,\n maximumFractionDigits: 20,\n })\n : value;\n\n // Remove all instances of \",\" and \"'\".\n amount = amount.trim().replace(/[,']/g, \"\");\n\n // Verify that the string is of the format 1234.5678\n const regexMatch = amount.match(/\\d*(\\.\\d*)?/);\n if (!regexMatch || regexMatch[0] !== amount) {\n return FromStringToTokenError.InvalidFormat;\n }\n\n const [integral, fractional] = amount.split(\".\");\n\n let e8s = BigInt(0);\n\n if (integral) {\n try {\n e8s += BigInt(integral) * E8S_PER_TOKEN;\n } catch {\n return FromStringToTokenError.InvalidFormat;\n }\n }\n\n if (fractional) {\n if (fractional.length > 8) {\n return FromStringToTokenError.FractionalMoreThan8Decimals;\n }\n try {\n e8s += BigInt(fractional.padEnd(8, \"0\"));\n } catch {\n return FromStringToTokenError.InvalidFormat;\n }\n }\n\n return e8s;\n};\n\n/**\n * Receives a string representing a number and returns the big int or error.\n *\n * @param amount - in string format\n * @returns bigint | FromStringToTokenError\n */\nconst convertStringToUlps = ({\n amount,\n decimals,\n}: {\n amount: string;\n decimals: number;\n}): bigint | FromStringToTokenError => {\n // Remove all instances of \",\" and \"'\".\n amount = amount.trim().replace(/[,']/g, \"\");\n\n // Verify that the string is of the format 1234.5678\n const regexMatch = amount.match(/\\d*(\\.\\d*)?/);\n if (!regexMatch || regexMatch[0] !== amount) {\n return FromStringToTokenError.InvalidFormat;\n }\n\n const [integral, fractional] = amount.split(\".\");\n\n let ulps = 0n;\n const ulpsPerToken = 10n ** BigInt(decimals);\n\n if (integral) {\n try {\n ulps += BigInt(integral) * ulpsPerToken;\n } catch {\n return FromStringToTokenError.InvalidFormat;\n }\n }\n\n if (fractional) {\n if (fractional.length > decimals) {\n return FromStringToTokenError.FractionalTooManyDecimals;\n }\n try {\n ulps += BigInt(fractional.padEnd(decimals, \"0\"));\n } catch {\n return FromStringToTokenError.InvalidFormat;\n }\n }\n\n return ulps;\n};\n\nexport interface Token {\n symbol: string;\n name: string;\n decimals: number;\n logo?: string;\n}\n\n// TODO: Remove this token and use the value from ICP ledger\nexport const ICPToken: Token = {\n symbol: \"ICP\",\n name: \"Internet Computer\",\n decimals: 8,\n};\n\n/**\n * Deprecated. Use TokenAmountV2 instead which supports decimals !== 8.\n *\n * Represents an amount of tokens.\n *\n * @param e8s - The amount of tokens in bigint.\n * @param token - The token type.\n */\nexport class TokenAmount {\n private constructor(\n protected e8s: bigint,\n public token: Token,\n ) {\n if (token.decimals !== 8) {\n throw new Error(\"Use TokenAmountV2 for number of decimals other than 8\");\n }\n }\n\n /**\n * Initialize from a bigint. Bigint are considered e8s.\n *\n * @param {amount: bigint; token?: Token;} params\n * @param {bigint} params.amount The amount in bigint format.\n * @param {Token} params.token The token type.\n */\n public static fromE8s({\n amount,\n token,\n }: {\n amount: bigint;\n token: Token;\n }): TokenAmount {\n return new TokenAmount(amount, token);\n }\n\n /**\n * Initialize from a string. Accepted formats:\n *\n * 1234567.8901\n * 1'234'567.8901\n * 1,234,567.8901\n *\n * @param {amount: string; token?: Token;} params\n * @param {string} params.amount The amount in string format.\n * @param {Token} params.token The token type.\n */\n public static fromString({\n amount,\n token,\n }: {\n amount: string;\n token: Token;\n }): TokenAmount | FromStringToTokenError {\n // If parsing the number fails because of the number of decimals, we still\n // want the error to be about the number of decimals and not about the\n // parsing.\n if (token.decimals !== 8) {\n throw new Error(\"Use TokenAmountV2 for number of decimals other than 8\");\n }\n const e8s = convertStringToE8s(amount);\n\n if (typeof e8s === \"bigint\") {\n return new TokenAmount(e8s, token);\n }\n return e8s;\n }\n\n /**\n * Initialize from a number.\n *\n * 1 integer is considered E8S_PER_TOKEN\n *\n * @param {amount: number; token?: Token;} params\n * @param {string} params.amount The amount in number format.\n * @param {Token} params.token The token type.\n */\n public static fromNumber({\n amount,\n token,\n }: {\n amount: number;\n token: Token;\n }): TokenAmount {\n const tokenAmount = TokenAmount.fromString({\n amount: amount.toString(),\n token,\n });\n if (tokenAmount instanceof TokenAmount) {\n return tokenAmount;\n }\n if (tokenAmount === FromStringToTokenError.FractionalMoreThan8Decimals) {\n throw new Error(`Number ${amount} has more than 8 decimals`);\n }\n\n // This should never happen\n throw new Error(`Invalid number ${amount}`);\n }\n\n /**\n *\n * @returns The amount of e8s.\n */\n public toE8s(): bigint {\n return this.e8s;\n }\n}\n\n/**\n * Represents an amount of tokens.\n *\n * @param upls - The amount of tokens in units in the last place. If the token\n * supports N decimals, 10^N ulp = 1 token.\n * @param token - The token type.\n */\nexport class TokenAmountV2 {\n private constructor(\n protected ulps: bigint,\n public token: Token,\n ) {}\n\n /**\n * Initialize from a bigint. Bigint are considered ulps.\n *\n * @param {amount: bigint; token?: Token;} params\n * @param {bigint} params.amount The amount in bigint format.\n * @param {Token} params.token The token type.\n */\n public static fromUlps({\n amount,\n token,\n }: {\n amount: bigint;\n token: Token;\n }): TokenAmountV2 {\n return new TokenAmountV2(amount, token);\n }\n\n /**\n * Initialize from a string. Accepted formats:\n *\n * 1234567.8901\n * 1'234'567.8901\n * 1,234,567.8901\n *\n * @param {amount: string; token?: Token;} params\n * @param {string} params.amount The amount in string format.\n * @param {Token} params.token The token type.\n */\n public static fromString({\n amount,\n token,\n }: {\n amount: string;\n token: Token;\n }): TokenAmountV2 | FromStringToTokenError {\n const ulps = convertStringToUlps({ amount, decimals: token.decimals });\n\n if (typeof ulps === \"bigint\") {\n return new TokenAmountV2(ulps, token);\n }\n return ulps;\n }\n\n /**\n * Initialize from a number.\n *\n * 1 integer is considered 10^{token.decimals} ulps\n *\n * @param {amount: number; token?: Token;} params\n * @param {string} params.amount The amount in number format.\n * @param {Token} params.token The token type.\n */\n public static fromNumber({\n amount,\n token,\n }: {\n amount: number;\n token: Token;\n }): TokenAmountV2 {\n const tokenAmount = TokenAmountV2.fromString({\n amount: amount.toFixed(\n Math.min(DECIMALS_CONVERSION_SUPPORTED, token.decimals),\n ),\n token,\n });\n if (tokenAmount instanceof TokenAmountV2) {\n return tokenAmount;\n }\n if (tokenAmount === FromStringToTokenError.FractionalTooManyDecimals) {\n throw new Error(\n `Number ${amount} has more than ${token.decimals} decimals`,\n );\n }\n\n // This should never happen\n throw new Error(`Invalid number ${amount}`);\n }\n\n /**\n *\n * @returns The amount of ulps.\n */\n public toUlps(): bigint {\n return this.ulps;\n }\n\n /**\n *\n * @returns The amount of ulps in e8s precision\n */\n public toE8s(): bigint {\n if (this.token.decimals < 8) {\n return this.ulps * 10n ** BigInt(8 - this.token.decimals);\n }\n if (this.token.decimals === 8) {\n return this.ulps;\n }\n return this.ulps / 10n ** BigInt(this.token.decimals - 8);\n }\n}\n", "import type { Principal } from \"@icp-sdk/core/principal\";\nimport type { QueryParams } from \"../types/query.params\";\n\nexport abstract class Canister<T> {\n protected constructor(\n private readonly id: Principal,\n protected readonly service: T,\n protected readonly certifiedService: T,\n ) {}\n\n get canisterId(): Principal {\n return this.id;\n }\n\n protected caller = ({ certified = true }: QueryParams): T =>\n certified ? this.certifiedService : this.service;\n}\n", "/**\n * Checks if a given argument is null or undefined.\n *\n * @template T - The type of the argument.\n * @param {T | undefined | null} argument - The argument to check.\n * @returns {argument is undefined | null} `true` if the argument is null or undefined; otherwise, `false`.\n */\nexport const isNullish = <T>(\n argument: T | undefined | null,\n): argument is undefined | null => argument === null || argument === undefined;\n\n/**\n * Checks if a given argument is neither null nor undefined.\n *\n * @template T - The type of the argument.\n * @param {T | undefined | null} argument - The argument to check.\n * @returns {argument is NonNullable<T>} `true` if the argument is not null or undefined; otherwise, `false`.\n */\nexport const nonNullish = <T>(\n argument: T | undefined | null,\n): argument is NonNullable<T> => !isNullish(argument);\n\n/**\n * Checks if a given value is not null, not undefined, and not an empty string.\n *\n * @param {string | undefined | null} value - The value to check.\n * @returns {boolean} `true` if the value is not null, not undefined, and not an empty string; otherwise, `false`.\n */\nexport const notEmptyString = (\n value: string | undefined | null,\n): value is string => nonNullish(value) && value !== \"\";\n\n/**\n * Checks if a given value is null, undefined, or an empty string.\n *\n * @param {string | undefined | null} value - The value to check.\n * @returns {value is undefined | null | \"\"} Type predicate indicating if the value is null, undefined, or an empty string.\n */\nexport const isEmptyString = (\n value: string | undefined | null,\n): value is undefined | null | \"\" => !notEmptyString(value);\n", "import type { QueryAndUpdateParams } from \"../types/query-and-update.params\";\nimport { isNullish } from \"../utils/nullish.utils\";\n\n/**\n * This service performs a query (not-certified) call and/or an update (certified) call, and handles the results.\n *\n * It is useful because it can do both type of calls for security reasons.\n * For example, malicious nodes can forge transactions and balance when calling an Index canister, if no update is performed to certify the results.\n *\n * Furthermore, it can handle the results of the calls in different ways:\n * - `query` only performs a query call.\n * - `update` only performs an update call.\n * - `query_and_update` performs both calls.\n *\n * The resolution can be:\n * - `all_settled` waits for all calls to settle.\n * - `race` waits for the first call to settle (typically, `query` is the fastest one).\n *\n * Once the call(s) are done, the response is handled by the `onLoad` callback.\n * However, if an error occurs, it is handled by the error callbacks, if provided: one for the query call and one for the update call.\n *\n * @param {QueryAndUpdateParams<R, E>} params The parameters to perform the request.\n * @param {QueryAndUpdateRequest<R>} params.request The request to perform.\n * @param {QueryAndUpdateOnResponse<R>} params.onLoad The callback to handle the response of the request.\n * @param {QueryAndUpdateOnQueryError<E>} [params.onQueryError] The callback to handle the error of the `query` request.\n * @param {QueryAndUpdateOnUpdateError<E>} [params.onUpdateError] The callback to handle the error of the `update` request.\n * @param {QueryAndUpdateStrategy} [params.strategy=\"query_and_update\"] The strategy to use. Default is `query_and_update`.\n * @param {QueryAndUpdateIdentity} params.identity The identity to use for the request.\n * @param {QueryAndUpdatePromiseResolution} [params.resolution=\"race\"] The resolution to use. Default is `race`.\n *\n * @template R The type of the response.\n * @template E The type of the error.\n *\n * @returns A promise that resolves when the request is done.\n */\nexport const queryAndUpdate = async <R, E = unknown>({\n request,\n onLoad,\n onQueryError,\n onUpdateError,\n strategy = \"query_and_update\",\n identity,\n resolution = \"race\",\n}: QueryAndUpdateParams<R, E>): Promise<void> => {\n let certifiedDone = false;\n\n const queryOrUpdate = (certified: boolean) =>\n request({ certified, identity })\n .then((response) => {\n if (certifiedDone) {\n return;\n }\n\n onLoad({ certified, response });\n })\n .catch((error: E) => {\n if (!certified) {\n onQueryError?.({ error, identity });\n }\n\n if (certifiedDone) {\n return;\n }\n\n if (isNullish(onUpdateError)) {\n return;\n }\n\n console.error(error);\n\n if (!certified) {\n return;\n }\n\n onUpdateError({ error, identity });\n })\n .finally(() => (certifiedDone = certifiedDone || certified));\n\n const requests: Array<Promise<void>> =\n strategy === \"query\"\n ? [queryOrUpdate(false)]\n : strategy === \"update\"\n ? [queryOrUpdate(true)]\n : [queryOrUpdate(false), queryOrUpdate(true)];\n\n await (resolution === \"all_settled\"\n ? Promise.allSettled(requests)\n : Promise.race(requests));\n};\n", "import {\n Actor,\n type ActorConfig,\n type ActorSubclass,\n type Agent,\n} from \"@icp-sdk/core/agent\";\nimport type { IDL } from \"@icp-sdk/core/candid\";\nimport type { Principal } from \"@icp-sdk/core/principal\";\nimport type { CanisterOptions } from \"../types/canister.options\";\nimport { defaultAgent } from \"./agent.utils\";\n\ntype RequiredCanisterOptions<T> = Required<\n Pick<CanisterOptions<T>, \"canisterId\">\n> &\n Omit<CanisterOptions<T>, \"canisterId\">;\n\nexport const createServices = <T>({\n options: {\n canisterId,\n serviceOverride,\n certifiedServiceOverride,\n agent: agentOption,\n callTransform,\n queryTransform,\n },\n idlFactory,\n certifiedIdlFactory,\n}: {\n options: RequiredCanisterOptions<T> &\n Pick<ActorConfig, \"queryTransform\" | \"callTransform\">;\n idlFactory: IDL.InterfaceFactory;\n certifiedIdlFactory: IDL.InterfaceFactory;\n}): {\n service: ActorSubclass<T>;\n certifiedService: ActorSubclass<T>;\n agent: Agent;\n canisterId: Principal;\n} => {\n const agent: Agent = agentOption ?? defaultAgent();\n\n const service: ActorSubclass<T> =\n serviceOverride ??\n Actor.createActor<T>(idlFactory, {\n agent,\n canisterId,\n callTransform,\n queryTransform,\n });\n\n const certifiedService: ActorSubclass<T> =\n certifiedServiceOverride ??\n Actor.createActor<T>(certifiedIdlFactory, {\n agent,\n canisterId,\n callTransform,\n queryTransform,\n });\n\n return { service, certifiedService, agent, canisterId };\n};\n", "import {\n AnonymousIdentity,\n HttpAgent,\n type Agent,\n type Identity,\n} from \"@icp-sdk/core/agent\";\nimport type { CreateAgentParams } from \"../types/agent.utils\";\nimport { isNullish, nonNullish } from \"./nullish.utils\";\n\n/**\n * Get a default agent that connects to mainnet with the anonymous identity.\n * @returns The default agent to use\n */\nexport const defaultAgent = (): Agent =>\n HttpAgent.createSync({\n host: \"https://icp-api.io\",\n identity: new AnonymousIdentity(),\n });\n\n/**\n * Create an agent for a given identity\n *\n * @param {CreateAgentParams} params The parameters to create a new HTTP agent\n * @param {Identity} params.identity A mandatory identity to use for the agent\n * @param {string} params.host An optional host to connect to, particularly useful for local development\n * @param {boolean} params.fetchRootKey Fetch root key for certificate validation during local development or on testnet\n * @param {boolean} params.verifyQuerySignatures Check for signatures in the state tree signed by the node that replies to queries - i.e. certify responses.\n * @param {number} params.retryTimes Set the number of retries the agent should perform before error.\n */\nexport const createAgent = async ({\n identity,\n host,\n fetchRootKey = false,\n verifyQuerySignatures = false,\n retryTimes,\n}: CreateAgentParams): Promise<HttpAgent> =>\n await HttpAgent.create({\n identity,\n ...(nonNullish(host) && { host }),\n verifyQuerySignatures,\n ...(nonNullish(retryTimes) && { retryTimes }),\n shouldFetchRootKey: fetchRootKey,\n });\n\nexport type AgentManagerConfig = Pick<\n CreateAgentParams,\n \"fetchRootKey\" | \"host\"\n>;\n\n/**\n * AgentManager class manages HttpAgent instances for different identities.\n *\n * It caches agents by identity to optimise resource usage and avoid unnecessary agent creation.\n * Provides functionality to create new agents, retrieve cached agents, and clear the cache when needed.\n */\nexport class AgentManager {\n private agents: Record<string, HttpAgent> | undefined | null = undefined;\n\n private constructor(private readonly config: AgentManagerConfig) {}\n\n /**\n * Static factory method to create a new AgentManager instance.\n *\n * This method serves as an alternative to directly using the private constructor,\n * making it more convenient to create instances of `AgentManager` using a simple and clear method.\n *\n * @param {AgentManagerConfig} config - Configuration options for the AgentManager instance.\n * @param {boolean} config.fetchRootKey - Whether to fetch the root key for certificate validation.\n * @param {string} config.host - The host to connect to.\n * @returns {AgentManager} A new instance of `AgentManager`.\n */\n public static create(config: AgentManagerConfig): AgentManager {\n return new AgentManager(config);\n }\n\n /**\n * Get or create an HTTP agent for a given identity.\n *\n * If the agent for the specified identity has been created and cached, it is retrieved from the cache.\n * If no agent exists for the identity, a new one is created, cached, and then returned.\n *\n * @param {Identity} identity - The identity to be used to create the agent.\n * @returns {Promise<HttpAgent>} The HttpAgent associated with the given identity.\n */\n public getAgent = async ({\n identity,\n }: {\n identity: Identity;\n }): Promise<HttpAgent> => {\n const key = identity.getPrincipal().toText();\n\n if (isNullish(this.agents) || isNullish(this.agents[key])) {\n const agent = await createAgent({\n identity,\n fetchRootKey: this.config.fetchRootKey,\n host: this.config.host,\n verifyQuerySignatures: true,\n });\n\n this.agents = {\n ...(this.agents ?? {}),\n [key]: agent,\n };\n\n return agent;\n }\n\n return this.agents[key];\n };\n\n /**\n * Clear the cache of HTTP agents.\n *\n * This method removes all cached agents, forcing new agent creation on the next request for any identity.\n * Useful when identities have changed or if you want to reset all active connections.\n */\n public clearAgents = (): void => {\n this.agents = null;\n };\n}\n", "export class InvalidPercentageError extends Error {}\nexport class NullishError extends Error {}\n\nexport const assertNonNullish: <T>(\n value: T,\n message?: string,\n // eslint-disable-next-line local-rules/prefer-object-params\n) => asserts value is NonNullable<T> = <T>(\n value: T,\n message?: string,\n): void => {\n if (value === null || value === undefined) {\n throw new NullishError(message);\n }\n};\n\n// eslint-disable-next-line local-rules/prefer-object-params\nexport const asNonNullish = <T>(value: T, message?: string): NonNullable<T> => {\n assertNonNullish(value, message);\n return value;\n};\n\nexport const assertPercentageNumber = (percentage: number) => {\n if (percentage < 0 || percentage > 100) {\n throw new InvalidPercentageError(\n `${percentage} is not a valid percentage number.`,\n );\n }\n};\n\n/**\n * Utility to enforce exhaustiveness checks in TypeScript.\n *\n * This function should only be called in branches of a `switch` or conditional\n * that should be unreachable if the union type has been fully handled.\n *\n * By typing the parameter as `never`, the compiler will emit an error if\n * a new variant is added to the union but not covered in the logic.\n *\n * @param _ - A value that should be of type `never`. If this is not the case,\n * the TypeScript compiler will flag a type error.\n * @param message - Optional custom error message to include in the thrown error.\n * @throws {Error} Always throws when invoked at runtime.\n *\n */\n// eslint-disable-next-line local-rules/prefer-object-params\nexport const assertNever = (_: never, message?: string): never => {\n throw new Error(message);\n};\n", "import { assertNonNullish } from \"./asserts.utils\";\n\nexport const uint8ArrayToBigInt = (array: Uint8Array): bigint => {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n if (typeof view.getBigUint64 === \"function\") {\n return view.getBigUint64(0);\n }\n const high = BigInt(view.getUint32(0));\n const low = BigInt(view.getUint32(4));\n\n return (high << BigInt(32)) + low;\n};\n\nexport const bigIntToUint8Array = (value: bigint): Uint8Array => {\n const buffer = new ArrayBuffer(8);\n const view = new DataView(buffer);\n if (typeof view.setBigUint64 === \"function\") {\n view.setBigUint64(0, value);\n } else {\n const high = Number(value >> BigInt(32));\n const low = Number(value & BigInt(0xffffffff));\n\n view.setUint32(0, high);\n view.setUint32(4, low);\n }\n\n return new Uint8Array(buffer);\n};\n\nexport const numberToUint8Array = (value: number): Uint8Array => {\n const view = new DataView(new ArrayBuffer(8));\n for (let index = 7; index >= 0; --index) {\n view.setUint8(index, value % 256);\n value = value >> 8;\n }\n return new Uint8Array(view.buffer);\n};\n\nexport const arrayBufferToUint8Array = (buffer: ArrayBuffer): Uint8Array =>\n new Uint8Array(buffer);\n\nexport const uint8ArrayToArrayOfNumber = (array: Uint8Array): Array<number> =>\n Array.from(array);\n\nexport const arrayOfNumberToUint8Array = (numbers: Array<number>): Uint8Array =>\n new Uint8Array(numbers);\n\nexport const asciiStringToByteArray = (text: string): Array<number> =>\n Array.from(text).map((c) => c.charCodeAt(0));\n\nexport const hexStringToUint8Array = (hexString: string): Uint8Array => {\n const matches = hexString.match(/.{1,2}/g);\n\n assertNonNullish(matches, \"Invalid hex string.\");\n\n return Uint8Array.from(matches.map((byte) => parseInt(byte, 16)));\n};\n\n/**\n * Compare two Uint8Arrays for byte-level equality.\n *\n * @param {Object} params\n * @param {Uint8Array} params.a - First Uint8Array to compare.\n * @param {Uint8Array} params.b - Second Uint8Array to compare.\n * @returns {boolean} True if both arrays have the same length and identical contents.\n */\nexport const uint8ArraysEqual = ({ a, b }: { a: Uint8Array; b: Uint8Array }) =>\n a.length === b.length && a.every((byte, i) => byte === b[i]);\n\nexport const uint8ArrayToHexString = (bytes: Uint8Array | number[]) => {\n if (!(bytes instanceof Uint8Array)) {\n bytes = Uint8Array.from(bytes);\n }\n return bytes.reduce(\n (str, byte) => str + byte.toString(16).padStart(2, \"0\"),\n \"\",\n );\n};\n\nexport const candidNumberArrayToBigInt = (array: number[]): bigint => {\n let result = 0n;\n for (let i = array.length - 1; i >= 0; i--) {\n result = (result << 32n) + BigInt(array[i]);\n }\n return result;\n};\n", "import { assertNonNullish } from \"./asserts.utils\";\n\nconst ALPHABET = \"abcdefghijklmnopqrstuvwxyz234567\";\n\n// Build a lookup table for decoding.\nconst LOOKUP_TABLE: Record<string, number> = Object.create(null);\nfor (let i = 0; i < ALPHABET.length; i++) {\n LOOKUP_TABLE[ALPHABET[i]] = i;\n}\n\n// Add aliases for rfc4648.\nLOOKUP_TABLE[\"0\"] = LOOKUP_TABLE.o;\nLOOKUP_TABLE[\"1\"] = LOOKUP_TABLE.i;\n\n/**\n * Encode an Uint8Array to a base32 string.\n *\n * @param input The input array to encode.\n * @returns A Base32 string encoding the input.\n */\nexport const encodeBase32 = (input: Uint8Array): string => {\n // How many bits will we skip from the first byte.\n let skip = 0;\n // 5 high bits, carry from one byte to the next.\n let bits = 0;\n\n // The output string in base32.\n let output = \"\";\n\n const encodeByte = (byte: number): number => {\n if (skip < 0) {\n // we have a carry from the previous byte\n bits |= byte >> -skip;\n } else {\n // no carry\n bits = (byte << skip) & 248;\n }\n\n if (skip > 3) {\n // Not enough data to produce a character, get us another one\n skip -= 8;\n return 1;\n }\n\n if (skip < 4) {\n // produce a character\n output += ALPHABET[bits >> 3];\n skip += 5;\n }\n\n return 0;\n };\n\n for (let i = 0; i < input.length; ) {\n i += encodeByte(input[i]);\n }\n\n return output + (skip < 0 ? ALPHABET[bits >> 3] : \"\");\n};\n\n/**\n * Decode a base32 string to Uint8Array.\n *\n * @param input The input string to decode.\n * @param input The base32 encoded string to decode.\n */\nexport const decodeBase32 = (input: string): Uint8Array => {\n // how many bits we have from the previous character.\n let skip = 0;\n // current byte we're producing.\n let byte = 0;\n\n const output = new Uint8Array(((input.length * 4) / 3) | 0);\n let o = 0;\n\n const decodeChar = (char: string) => {\n // Consume a character from the stream, store\n // the output in this.output. As before, better\n // to use update().\n let val = LOOKUP_TABLE[char.toLowerCase()];\n assertNonNullish(val, `Invalid character: ${JSON.stringify(char)}`);\n\n // move to the high bits\n val <<= 3;\n byte |= val >>> skip;\n skip += 5;\n\n if (skip >= 8) {\n // We have enough bytes to produce an output\n output[o++] = byte;\n skip -= 8;\n\n if (skip > 0) {\n byte = (val << (5 - skip)) & 255;\n } else {\n byte = 0;\n }\n }\n };\n\n for (const c of input) {\n decodeChar(c);\n }\n\n return output.slice(0, o);\n};\n", "/**\n * Converts a Uint8Array (binary data) to a base64 encoded string.\n *\n * @param {Uint8Array} uint8Array - The Uint8Array containing binary data to be encoded.\n * @returns {string} - The base64 encoded string representation of the binary data.\n */\nexport const uint8ArrayToBase64 = (uint8Array: Uint8Array): string =>\n btoa(String.fromCharCode(...new Uint8Array(uint8Array)));\n\n/**\n * Converts a base64 encoded string to a Uint8Array (binary data).\n *\n * @param {string} base64String - The base64 encoded string to be decoded.\n * @returns {Uint8Array} - The Uint8Array representation of the decoded binary data.\n */\nexport const base64ToUint8Array = (base64String: string): Uint8Array =>\n Uint8Array.from(atob(base64String), (c) => c.charCodeAt(0));\n", "// This file is translated to JavaScript from\n// https://lxp32.github.io/docs/a-simple-example-crc32-calculation/\nconst lookUpTable: Uint32Array = new Uint32Array([\n 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,\n 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,\n 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,\n 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,\n 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,\n 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,\n 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,\n 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,\n 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,\n 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,\n 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,\n 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,\n 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,\n 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,\n 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,\n 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,\n 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,\n 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,\n 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,\n 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,\n 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,\n 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,\n 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,\n 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,\n 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,\n 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,\n 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,\n 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,\n 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,\n 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,\n 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,\n 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,\n 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,\n 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,\n 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,\n 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,\n 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,\n 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,\n 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,\n 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,\n 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,\n 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,\n 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,\n]);\n\nconst crc32 = (bytes: Uint8Array): number => {\n let crc = -1;\n\n for (let i = 0; i < bytes.length; i++) {\n const byte = bytes[i];\n const t = (byte ^ crc) & 0xff;\n crc = lookUpTable[t] ^ (crc >>> 8);\n }\n\n return (crc ^ -1) >>> 0;\n};\n\nexport const bigEndianCrc32 = (bytes: Uint8Array): Uint8Array => {\n const checksumArrayBuf = new ArrayBuffer(4);\n const view = new DataView(checksumArrayBuf);\n view.setUint32(0, crc32(bytes), false);\n return new Uint8Array(checksumArrayBuf);\n};\n", "import { Principal } from \"@icp-sdk/core/principal\";\nimport { nonNullish } from \"./nullish.utils\";\n\nconst JSON_KEY_BIGINT = \"__bigint__\";\nconst JSON_KEY_PRINCIPAL = \"__principal__\";\nconst JSON_KEY_UINT8ARRAY = \"__uint8array__\";\n\n/**\n * A custom replacer for `JSON.stringify` that converts specific types not natively supported\n * by the API into JSON-compatible formats.\n *\n * Supported conversions:\n * - `BigInt` \u2192 `{ \"__bigint__\": string }`\n * - `Principal` \u2192 `{ \"__principal__\": string }`\n * - `Uint8Array` \u2192 `{ \"__uint8array__\": number[] }`\n *\n * @param {string} _key - Ignored. Only provided for API compatibility.\n * @param {unknown} value - The value to transform before stringification.\n * @returns {unknown} The transformed value if it matches a known type, otherwise the original value.\n */\n// eslint-disable-next-line local-rules/prefer-object-params\nexport const jsonReplacer = (_key: string, value: unknown): unknown => {\n if (typeof value === \"bigint\") {\n return { [JSON_KEY_BIGINT]: `${value}` };\n }\n\n if (nonNullish(value) && Principal.isPrincipal(value)) {\n // isPrincipal asserts if a value is a Principal, but does not assert if the object\n // contains functions such as toText(). That's why we construct a new object.\n return { [JSON_KEY_PRINCIPAL]: Principal.from(value).toText() };\n }\n\n if (nonNullish(value) && value instanceof Uint8Array) {\n return { [JSON_KEY_UINT8ARRAY]: Array.from(value) };\n }\n\n return value;\n};\n\n/**\n * A custom reviver for `JSON.parse` that reconstructs specific types from their JSON-encoded representations.\n *\n * This reverses the transformations applied by `jsonReplacer`, restoring the original types.\n *\n * Supported conversions:\n * - `{ \"__bigint__\": string }` \u2192 `BigInt`\n * - `{ \"__principal__\": string }` \u2192 `Principal`\n * - `{ \"__uint8array__\": number[] }` \u2192 `Uint8Array`\n *\n * @param {string} _key - Ignored but provided for API compatibility.\n * @param {unknown} value - The parsed value to transform.\n * @returns {unknown} The reconstructed value if it matches a known type, otherwise the original value.\n */\n// eslint-disable-next-line local-rules/prefer-object-params\nexport const jsonReviver = (_key: string, value: unknown): unknown => {\n const mapValue = <T>(key: string): T => (value as Record<string, T>)[key];\n\n if (\n nonNullish(value) &&\n typeof value === \"object\" &&\n JSON_KEY_BIGINT in value\n ) {\n return BigInt(mapValue(JSON_KEY_BIGINT));\n }\n\n if (\n nonNullish(value) &&\n typeof value === \"object\" &&\n JSON_KEY_PRINCIPAL in value\n ) {\n return Principal.fromText(mapValue(JSON_KEY_PRINCIPAL));\n }\n\n if (\n nonNullish(value) &&\n typeof value === \"object\" &&\n JSON_KEY_UINT8ARRAY in value\n ) {\n return Uint8Array.from(mapValue(JSON_KEY_UINT8ARRAY));\n }\n\n return value;\n};\n", "import { uint8ArrayToHexString } from \"./arrays.utils\";\nimport { jsonReplacer } from \"./json.utils\";\n\n/**\n * Generates a SHA-256 hash from the given object.\n *\n * The object is first stringified using a custom `jsonReplacer`, then\n * hashed using the SubtleCrypto API. The resulting hash is returned as a hex string.\n *\n * @template T - The type of the input object.\n * @param {T} params - The object to hash.\n * @returns {Promise<string>} A promise that resolves to the hex string of the SHA-256 hash.\n */\nexport const hashObject = async <T extends object>(\n params: T,\n): Promise<string> => {\n const jsonString = JSON.stringify(params, jsonReplacer);\n\n return await hashText(jsonString);\n};\n\n/**\n * Generates a SHA-256 hash from a plain text string.\n *\n * The string is UTF-8 encoded and hashed using the SubtleCrypto API.\n * The resulting hash is returned as a hexadecimal string.\n *\n * @param {string} text - The text to hash.\n * @returns {Promise<string>} A promise that resolves to the hex string of the SHA-256 hash.\n */\nexport const hashText = async (text: string): Promise<string> => {\n const dataBuffer = new TextEncoder().encode(text);\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", dataBuffer);\n\n return uint8ArrayToHexString(new Uint8Array(hashBuffer));\n};\n", "const SECONDS_IN_MINUTE = 60;\nconst MINUTES_IN_HOUR = 60;\nconst HOURS_IN_DAY = 24;\nconst DAYS_IN_NON_LEAP_YEAR = 365;\n\nexport interface I18nSecondsToDuration {\n year: string;\n year_plural: string;\n month: string;\n month_plural: string;\n day: string;\n day_plural: string;\n hour: string;\n hour_plural: string;\n minute: string;\n minute_plural: string;\n second: string;\n second_plural: string;\n}\n\nconst EN_TIME: I18nSecondsToDuration = {\n year: \"year\",\n year_plural: \"years\",\n month: \"month\",\n month_plural: \"months\",\n day: \"day\",\n day_plural: \"days\",\n hour: \"hour\",\n hour_plural: \"hours\",\n minute: \"minute\",\n minute_plural: \"minutes\",\n second: \"second\",\n second_plural: \"seconds\",\n};\n\n/**\n * Convert seconds to a human-readable duration, such as \"6 days, 10 hours.\"\n * @param {Object} options - The options object.\n * @param {bigint} options.seconds - The number of seconds to convert.\n * @param {I18nSecondsToDuration} [options.i18n] - The i18n object for customizing language and units. Defaults to English.\n * @returns {string} The human-readable duration string.\n */\nexport const secondsToDuration = ({\n seconds,\n i18n = EN_TIME,\n}: {\n seconds: bigint;\n i18n?: I18nSecondsToDuration;\n}): string => {\n let minutes = seconds / BigInt(SECONDS_IN_MINUTE);\n\n let hours = minutes / BigInt(MINUTES_IN_HOUR);\n minutes -= hours * BigInt(MINUTES_IN_HOUR);\n\n let days = hours / BigInt(HOURS_IN_DAY);\n hours -= days * BigInt(HOURS_IN_DAY);\n\n const years = fullYearsInDays(days);\n days -= daysInYears(years);\n\n const periods = [\n createLabel({ labelKey: \"year\", amount: years }),\n createLabel({ labelKey: \"day\", amount: days }),\n createLabel({ labelKey: \"hour\", amount: hours }),\n createLabel({ labelKey: \"minute\", amount: minutes }),\n ...(seconds > BigInt(0) && seconds < BigInt(60)\n ? [createLabel({ labelKey: \"second\", amount: seconds })]\n : []),\n ];\n\n return periods\n .filter(({ amount }) => amount > 0)\n .slice(0, 2)\n .map(\n (labelInfo) =>\n `${labelInfo.amount} ${\n labelInfo.amount === 1\n ? i18n[labelInfo.labelKey]\n : i18n[`${labelInfo.labelKey}_plural`]\n }`,\n )\n .join(\", \");\n};\n\nconst fullYearsInDays = (days: bigint): bigint => {\n // Use integer division.\n let years = days / BigInt(DAYS_IN_NON_LEAP_YEAR);\n while (daysInYears(years) > days) {\n years--;\n }\n return years;\n};\n\nconst daysInYears = (years: bigint): bigint => {\n // Use integer division.\n const leapDays = years / BigInt(4);\n return years * BigInt(DAYS_IN_NON_LEAP_YEAR) + leapDays;\n};\n\ntype LabelKey = \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\" | \"second\";\ninterface LabelInfo {\n labelKey: LabelKey;\n amount: number;\n}\nconst createLabel = ({\n labelKey,\n amount,\n}: {\n labelKey: LabelKey;\n amount: bigint;\n}): LabelInfo => ({\n labelKey,\n amount: Number(amount),\n});\n\nconst NANOSECONDS_PER_MILLISECOND = 1_000_000n;\n\n/**\n * Returns the current timestamp in nanoseconds as a `bigint`.\n *\n * @returns {bigint} The current timestamp in nanoseconds.\n */\nexport const nowInBigIntNanoSeconds = (): bigint =>\n BigInt(Date.now()) * NANOSECONDS_PER_MILLISECOND;\n\n/**\n * Converts a given `Date` object to a timestamp in nanoseconds as a `bigint`.\n *\n * @param {Date} date - The `Date` object to convert.\n * @returns {bigint} The timestamp in nanoseconds.\n */\nexport const toBigIntNanoSeconds = (date: Date): bigint =>\n BigInt(date.getTime()) * NANOSECONDS_PER_MILLISECOND;\n", "/**\n * Creates a debounced version of the provided function.\n *\n * The debounced function postpones its execution until after a certain amount of time\n * has elapsed since the last time it was invoked. This is useful for limiting the rate\n * at which a function is called (e.g. in response to user input or events).\n *\n * @param {Function} func - The function to debounce. It will only be called after no new calls happen within the specified timeout.\n * @param {number} [timeout=300] - The debounce delay in milliseconds. Defaults to 300ms if not provided or invalid.\n * @returns {(args: unknown[]) => void} A debounced version of the original function.\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type, local-rules/prefer-object-params\nexport const debounce = (func: Function, timeout?: number) => {\n let timer: NodeJS.Timer | undefined;\n\n return (...args: unknown[]) => {\n const next = () => func(...args);\n\n if (timer) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore TypeScript global and window confusion even if we are using @types/node\n clearTimeout(timer);\n }\n\n timer = setTimeout(\n next,\n timeout !== undefined && timeout > 0 ? timeout : 300,\n );\n };\n};\n", "import type { Nullable, NullishNullable } from \"../types/did.utils\";\nimport { assertNonNullish } from \"./asserts.utils\";\nimport { nonNullish } from \"./nullish.utils\";\n\n/**\n * Converts a value into a Candid-style variant representation of an optional value.\n *\n * @template T The type of the value.\n * @param {T | null | undefined} value - The value to convert into a Candid-style variant.\n * @returns {Nullable<T>} A Candid-style variant representation: an empty array for `null` and `undefined` or an array with the value.\n */\nexport const toNullable = <T>(value?: T | null): Nullable<T> =>\n nonNullish(value) ? [value] : [];\n\n/**\n * Extracts the value from a Candid-style variant representation of an optional value.\n *\n * @template T The type of the value.\n * @param {Nullable<T>} value - A Candid-style variant representing an optional value.\n * @returns {T | undefined} The extracted value, or `undefined` if the array is empty.\n */\nexport const fromNullable = <T>(value: Nullable<T>): T | undefined =>\n value?.[0];\n\n/**\n * Extracts the value from a Candid-style variant representation of an optional value,\n * ensuring the value is defined. Throws an error if the array is empty or the value is nullish.\n *\n * @template T The type of the value.\n * @param {Nullable<T>} value - A Candid-style variant representing an optional value.\n * @returns {T} The extracted value.\n * @throws {Error} If the array is empty or the value is nullish.\n */\nexport const fromDefinedNullable = <T>(value: Nullable<T>): T => {\n const result = fromNullable(value);\n\n assertNonNullish(result);\n\n return result;\n};\n\n/**\n * Extracts the value from a nullish Candid-style variant representation.\n *\n * @template T The type of the value.\n * @param {NullishNullable<T>} value - A Candid-style variant or `undefined`.\n * @returns {T | undefined} The extracted value, or `undefined` if the input is nullish or the array is empty.\n */\nexport const fromNullishNullable = <T>(\n value: NullishNullable<T>,\n): T | undefined => fromNullable(value ?? []);\n", "import type { Principal } from \"@icp-sdk/core/principal\";\n\n/**\n * Convert a principal to a Uint8Array 32 length.\n * e.g. Useful to convert a canister ID when topping up cycles with the Cmc canister\n * @param principal The principal that needs to be converted to Subaccount\n */\nexport const principalToSubAccount = (principal: Principal): Uint8Array => {\n const bytes: Uint8Array = principal.toUint8Array();\n const subAccount: Uint8Array = new Uint8Array(32);\n subAccount[0] = bytes.length;\n subAccount.set(bytes, 1);\n return subAccount;\n};\n", "const AMOUNT_VERSION_PARTS = 3;\nconst addZeros = ({\n nums,\n amountZeros,\n}: {\n nums: number[];\n amountZeros: number;\n}): number[] =>\n amountZeros > nums.length\n ? [...nums, ...[...Array(amountZeros - nums.length).keys()].map(() => 0)]\n : nums;\n\nconst convertToNumber = (versionStringPart: string): number => {\n if (!Number.isNaN(Number(versionStringPart))) {\n return Number(versionStringPart);\n }\n const strippedVersion = versionStringPart.split(\"\").reduce((acc, char) => {\n if (Number.isNaN(Number(char))) {\n return acc;\n }\n return acc + char;\n }, \"\");\n return Number(strippedVersion);\n};\n/**\n * Returns true if the current version is smaller than the minVersion, false if equal or bigger.\n * Tags after patch version are ignored, e.g. 1.0.0-beta.1 is considered equal to 1.0.0.\n *\n * @param {Object} params\n * @param {string} params.minVersion Ex: \"1.0.0\"\n * @param {string} params.currentVersion Ex: \"2.0.0\"\n * @returns boolean\n */\nexport const smallerVersion = ({\n minVersion,\n currentVersion,\n}: {\n minVersion: string;\n currentVersion: string;\n}): boolean => {\n const minVersionStandarized = addZeros({\n nums: minVersion.split(\".\").map(convertToNumber),\n amountZeros: AMOUNT_VERSION_PARTS,\n }).join(\".\");\n const currentVersionStandarized = addZeros({\n nums: currentVersion.split(\".\").map(convertToNumber),\n amountZeros: AMOUNT_VERSION_PARTS,\n }).join(\".\");\n // Versions need to have the same number of parts to be comparable\n // Source: https://stackoverflow.com/a/65687141\n return (\n currentVersionStandarized.localeCompare(minVersionStandarized, undefined, {\n numeric: true,\n sensitivity: \"base\",\n }) < 0\n );\n};\n", "import {isNullish} from '@dfinity/utils';\nimport {\n AuthClient,\n IdbStorage,\n KEY_STORAGE_DELEGATION,\n KEY_STORAGE_KEY\n} from '@icp-sdk/auth/client';\nimport type {DelegationChain, ECDSAKeyIdentity} from '@icp-sdk/core/identity';\n\nexport class AuthClientStore {\n static #instance: AuthClientStore | undefined;\n\n #authClient: AuthClient | undefined | null;\n\n private constructor() {}\n\n static getInstance(): AuthClientStore {\n if (isNullish(this.#instance)) {\n this.#instance = new AuthClientStore();\n }\n\n return this.#instance;\n }\n\n createAuthClient = async (): Promise<AuthClient> => {\n this.#authClient = await AuthClient.create({\n idleOptions: {\n disableIdle: true,\n disableDefaultIdleCallback: true\n }\n });\n\n return this.#authClient;\n };\n\n safeCreateAuthClient = async (): Promise<AuthClient> => {\n // Since AgentJS persists the identity key in IndexedDB by default,\n // it can be tampered with and affect the next login with Internet Identity or NFID.\n // To ensure each session starts clean and safe, we clear the stored keys before creating a new AuthClient\n // in case the user is not authenticated.\n const storage = new IdbStorage();\n await storage.remove(KEY_STORAGE_KEY);\n\n return await this.createAuthClient();\n };\n\n getAuthClient = (): AuthClient | undefined | null => this.#authClient;\n\n logout = async (): Promise<void> => {\n await this.#authClient?.logout();\n\n // Reset local object otherwise next sign in (sign in - sign out - sign in) might not work out - i.e. agent-js might not recreate the delegation or identity if not resetted\n // Technically we do not need this since we recreate the agent below. We just keep it to make the reset explicit.\n this.#authClient = null;\n };\n\n setAuthClientStorage = async ({\n delegationChain,\n sessionKey\n }: {\n delegationChain: DelegationChain;\n sessionKey: ECDSAKeyIdentity;\n }) => {\n const storage = new IdbStorage();\n\n await Promise.all([\n storage.set(KEY_STORAGE_KEY, sessionKey.getKeyPair()),\n storage.set(KEY_STORAGE_DELEGATION, JSON.stringify(delegationChain.toJSON()))\n ]);\n };\n}\n", "import {IdbStorage, KEY_STORAGE_DELEGATION} from '@icp-sdk/auth/client';\nimport {DelegationChain, isDelegationValid} from '@icp-sdk/core/identity';\nimport {AUTH_TIMER_INTERVAL} from '../constants/auth.constants';\nimport {AuthClientStore} from '../stores/auth-client.store';\nimport type {PostMessage, PostMessageDataRequest} from '../types/post-message';\n\nexport const onAuthMessage = ({data}: MessageEvent<PostMessage<PostMessageDataRequest>>) => {\n const {msg} = data;\n\n switch (msg) {\n case 'junoStartAuthTimer':\n startTimer();\n return;\n case 'junoStopAuthTimer':\n stopTimer();\n }\n};\n\nlet timer: NodeJS.Timeout | undefined = undefined;\n\n/**\n * The timer is executed only if user has signed in\n */\nexport const startTimer = () =>\n (timer = setInterval(async () => await onTimerSignOut(), AUTH_TIMER_INTERVAL));\n\nexport const stopTimer = () => {\n if (!timer) {\n return;\n }\n\n clearInterval(timer);\n timer = undefined;\n};\n\n/**\n * \u2139\uFE0F Exported for test purpose only.\n */\nexport const onTimerSignOut = async () => {\n const [auth, chain] = await Promise.all([checkAuthentication(), checkDelegationChain()]);\n\n // Both identity and delegation are alright, so all good\n if (auth && chain.valid && chain.delegation !== null) {\n emitExpirationTime(chain.delegation);\n return;\n }\n\n logout();\n};\n\n/**\n * If user is not authenticated - i.e. no identity or anonymous and there is no valid delegation chain, then identity is not valid\n *\n * @returns true if authenticated\n */\nconst checkAuthentication = async (): Promise<boolean> => {\n const authClient = await AuthClientStore.getInstance().createAuthClient();\n return authClient.isAuthenticated();\n};\n\n/**\n * If there is no delegation or if not valid, then delegation is not valid.\n *\n * @returns Object true if delegation is valid and delegation\n */\nconst checkDelegationChain = async (): Promise<{\n valid: boolean;\n delegation: DelegationChain | null;\n}> => {\n const idbStorage: IdbStorage = new IdbStorage();\n const delegationChain: string | null = await idbStorage.get(KEY_STORAGE_DELEGATION);\n\n const delegation = delegationChain !== null ? DelegationChain.fromJSON(delegationChain) : null;\n\n return {\n valid: delegation !== null && isDelegationValid(delegation),\n delegation\n };\n};\n\nconst logout = () => {\n // Clear timer to not emit sign-out multiple times\n stopTimer();\n\n postMessage({msg: 'junoSignOutAuthTimer'});\n};\n\nconst emitExpirationTime = (delegation: DelegationChain) => {\n const expirationTime: bigint | undefined = delegation.delegations[0]?.delegation.expiration;\n\n // That would be unexpected here because the delegation has just been tested and is valid\n if (expirationTime === undefined) {\n return;\n }\n\n // 1_000_000 as NANO_SECONDS_IN_MILLISECOND. Constant not imported to not break prod build.\n const authRemainingTime =\n new Date(Number(expirationTime / BigInt(1_000_000))).getTime() - Date.now();\n\n postMessage({\n msg: 'junoDelegationRemainingTime',\n data: {\n authRemainingTime\n }\n });\n};\n", "import type {PostMessage, PostMessageDataRequest} from '../auth/types/post-message';\nimport {onAuthMessage} from '../auth/workers/auth.worker';\n\nonmessage = (params: MessageEvent<PostMessage<PostMessageDataRequest>>) => {\n onAuthMessage(params);\n};\n"],
5
- "mappings": "mBAAA,IAAMA,GAAW,mCAGXC,GAAsC,OAAO,OAAO,IAAI,EAC9D,QAASC,EAAI,EAAGA,EAAIF,GAAS,OAAQE,IACnCD,GAAYD,GAASE,CAAC,CAAC,EAAIA,EAI7BD,GAAY,CAAG,EAAIA,GAAY,EAC/BA,GAAY,CAAG,EAAIA,GAAY,EAMzB,SAAUE,GAAaC,EAAiB,CAE5C,IAAIC,EAAO,EAEPC,EAAO,EAGPC,EAAS,GAEb,SAASC,EAAWC,EAAY,CAS9B,OARIJ,EAAO,EAETC,GAAQG,GAAQ,CAACJ,EAGjBC,EAAQG,GAAQJ,EAAQ,IAGtBA,EAAO,GAETA,GAAQ,EACD,IAGLA,EAAO,IAETE,GAAUP,GAASM,GAAQ,CAAC,EAC5BD,GAAQ,GAGH,EACT,CAEA,QAASH,EAAI,EAAGA,EAAIE,EAAM,QACxBF,GAAKM,EAAWJ,EAAMF,CAAC,CAAC,EAG1B,OAAOK,GAAUF,EAAO,EAAIL,GAASM,GAAQ,CAAC,EAAI,GACpD,CAKM,SAAUI,GAAaN,EAAa,CAExC,IAAIC,EAAO,EAEPI,EAAO,EAELF,EAAS,IAAI,WAAaH,EAAM,OAAS,EAAK,EAAK,CAAC,EACtD,EAAI,EAER,SAASO,EAAWC,EAAY,CAI9B,IAAIC,EAAMZ,GAAYW,EAAK,YAAW,CAAE,EACxC,GAAIC,IAAQ,OACV,MAAM,IAAI,MAAM,sBAAsB,KAAK,UAAUD,CAAI,CAAC,EAAE,EAI9DC,IAAQ,EACRJ,GAAQI,IAAQR,EAChBA,GAAQ,EAEJA,GAAQ,IAEVE,EAAO,GAAG,EAAIE,E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AAC,EAGvF,GAAIH,GAAQC,EAAM,OAASA,EAAM,aAAe,KAAM,CACpDG,GAAmBH,EAAM,UAAU,EACnC,MACF,CAEAI,GAAO,CACT,EAOMH,GAAsB,UACP,MAAMI,GAAgB,YAAY,EAAE,iBAAiB,GACtD,gBAAgB,EAQ9BH,GAAuB,SAGvB,CAEJ,IAAMI,EAAiC,MADR,IAAIC,EAAW,EACU,IAAIC,CAAsB,EAE5EC,EAAaH,IAAoB,KAAOI,GAAgB,SAASJ,CAAe,EAAI,KAE1F,MAAO,CACL,MAAOG,IAAe,MAAQE,GAAkBF,CAAU,EAC1D,WAAAA,CACF,CACF,EAEML,GAAS,IAAM,CAEnBT,GAAU,EAEV,YAAY,CAAC,IAAK,sBAAsB,CAAC,CAC3C,EAEMQ,GAAsBM,GAAgC,CAC1D,IAAMG,EAAqCH,EAAW,YAAY,CAAC,GAAG,WAAW,WAGjF,GAAIG,IAAmB,OACrB,OAIF,IAAMC,EACJ,IAAI,KAAK,OAAOD,EAAiB,OAAO,GAAS,CAAC,CAAC,EAAE,QAAQ,EAAI,KAAK,IAAI,EAE5E,YAAY,CACV,IAAK,8BACL,KAAM,CACJ,kBAAAC,CACF,CACF,CAAC,CACH,ECtGA,UAAaC,GAA8D,CACzEC,GAAcD,CAAM,CACtB",
6
- "names": ["alphabet", "lookupTable", "i", "base32Encode", "input", "skip", "bits", "output", "encodeByte", "byte", "base32Decode", "decodeChar", "char", "val", "c", "lookUpTable", "getCrc32", "buf", "crc", "i", "t", "crypto", "isBytes", "a", "anumber", "n", "abytes", "b", "lengths", "aexists", "instance", "checkFinished", "aoutput", "out", "abytes", "min", "clean", "arrays", "i", "createView", "arr", "rotr", "word", "shift", "hasHexBuiltin", "hexes", "_", "i", "bytesToHex", "bytes", "abytes", "hex", "asciis", "asciiToBase16", "ch", "hexToBytes", "hl", "al", "array", "ai", "hi", "n1", "n2", "char", "utf8ToBytes", "str", "toBytes", "data", "utf8ToBytes", "abytes", "concatBytes", "arrays", "sum", "i", "a", "abytes", "res", "pad", "Hash", "createHasher", "hashCons", "hashC", "msg", "toBytes", "tmp", "randomBytes", "bytesLength", "crypto", "setBigUint64", "view", "byteOffset", "value", "isLE", "_32n", "_u32_max", "wh", "wl", "h", "l", "Chi", "a", "b", "c", "Maj", "HashMD", "Hash", "blockLen", "outputLen", "padOffset", "createView", "data", "aexists", "toBytes", "abytes", "buffer", "len", "pos", "take", "dataView", "out", "aoutput", "clean", "i", "oview", "outLen", "state", "res", "to", "length", "finished", "destroyed", "SHA256_IV", "SHA224_IV", "SHA512_IV", "U32_MASK64", "_32n", "fromBig", "n", "le", "split", "lst", "len", "Ah", "Al", "i", "h", "l", "shrSH", "h", "_l", "s", "shrSL", "l", "rotrSH", "rotrSL", "rotrBH", "rotrBL", "add", "Ah", "Al", "Bh", "Bl", "l", "add3L", "Cl", "add3H", "low", "Ch", "add4L", "Dl", "add4H", "Dh", "add5L", "El", "add5H", "Eh", "SHA256_K", "SHA256_W", "SHA256", "HashMD", "outputLen", "SHA256_IV", "A", "B", "C", "D", "E", "F", "G", "H", "view", "offset", "i", "W15", "W2", "s0", "rotr", "s1", "sigma1", "T1", "Chi", "T2", "Maj", "clean", "SHA224", "SHA224_IV", "K512", "split", "n", "SHA512_Kh", "SHA512_Kl", "SHA512_W_H", "SHA512_W_L", "SHA512", "SHA512_IV", "Ah", "Al", "Bh", "Bl", "Ch", "Cl", "Dh", "Dl", "Eh", "El", "Fh", "Fl", "Gh", "Gl", "Hh", "Hl", "W15h", "W15l", "s0h", "rotrSH", "shrSH", "s0l", "rotrSL", "shrSL", "W2h", "W2l", "s1h", "rotrBH", "s1l", "rotrBL", "SUMl", "add4L", "SUMh", "add4H", "sigma1h", "sigma1l", "CHIh", "CHIl", "T1ll", "add5L", "T1h", "add5H", "T1l", "sigma0h", "sigma0l", "MAJh", "MAJl", "add", "All", "add3L", "add3H", "sha256", "createHasher", "SHA256", "sha224", "SHA224", "sha512", "SHA512", "JSON_KEY_PRINCIPAL", "SELF_AUTHENTICATING_SUFFIX", "ANONYMOUS_SUFFIX", "MANAGEMENT_CANISTER_PRINCIPAL_TEXT_STR", "Principal", "_Principal", "publicKey", "sha", "sha224", "other", "hex", "hexToBytes", "text", "maybePrincipal", "obj", "canisterIdNoDash", "arr", "base32Decode", "principal", "_arr", "bytesToHex", "checksumArrayBuf", "getCrc32", "checksum", "array", "matches", "base32Encode", "i", "cmp", "ErrorKindEnum", "ErrorCode", "isCertified", "errorMessage", "bytesToHex", "AgentError", "_AgentError", "code", "kind", "ErrorKind", "InputError", "_InputError", "ErrorKind", "code", "ErrorKindEnum", "DerDecodeLengthMismatchErrorCode", "_DerDecodeLengthMismatchErrorCode", "ErrorCode", "expectedLength", "actualLength", "DerDecodeErrorCode", "_DerDecodeErrorCode", "error", "DerEncodeErrorCode", "_DerEncodeErrorCode", "HashValueErrorCode", "_HashValueErrorCode", "ErrorCode", "value", "UNREACHABLE_ERROR", "PipeArrayBuffer", "checkPoint", "buffer", "length", "uint8FromBufLike", "num", "result", "buf", "offset", "amount", "b", "v", "bufLike", "compare", "u1", "u2", "i", "uint8Equals", "ilog2", "n", "nBig", "lebEncode", "value", "byteLength", "ilog2", "pipe", "PipeArrayBuffer", "i", "uint8FromBufLike", "bufLike", "uint8Equals", "a", "b", "i", "hashValue", "value", "hashString", "sha256", "lebEncode", "uint8FromBufLike", "vals", "concatBytes", "hashOfMap", "InputError", "HashValueErrorCode", "encoded", "requestIdOf", "request", "map", "sorted", "key", "hashedKey", "hashedValue", "k1", "k2", "compare", "concatenated", "x", "IC_REQUEST_DOMAIN_SEPARATOR", "IC_RESPONSE_DOMAIN_SEPARATOR", "IC_REQUEST_AUTH_DELEGATION_DOMAIN_SEPARATOR", "SignIdentity", "Principal", "request", "body", "fields", "requestId", "requestIdOf", "concatBytes", "IC_REQUEST_DOMAIN_SEPARATOR", "AnonymousIdentity", "_0n", "_1n", "_abool2", "value", "title", "prefix", "_abytes2", "length", "bytes", "isBytes", "len", "needsLen", "ofLen", "got", "hexToNumber", "hex", "_0n", "bytesToNumberBE", "bytes", "bytesToHex", "bytesToNumberLE", "abytes", "numberToBytesBE", "n", "len", "hexToBytes", "numberToBytesLE", "ensureBytes", "title", "hex", "expectedLength", "res", "hexToBytes", "e", "isBytes", "len", "equalBytes", "a", "b", "diff", "i", "copyBytes", "bytes", "isPosBig", "n", "_0n", "inRange", "min", "max", "aInRange", "title", "bitLen", "len", "_1n", "bitMask", "n", "_1n", "_validateObject", "object", "fields", "optFields", "checkField", "fieldName", "expectedType", "isOpt", "val", "current", "k", "v", "notImplemented", "memoized", "fn", "map", "arg", "args", "computed", "_0n", "_1n", "_2n", "_3n", "_4n", "_5n", "_7n", "_8n", "_9n", "_16n", "mod", "a", "b", "result", "pow2", "x", "power", "modulo", "res", "_0n", "invert", "number", "a", "mod", "b", "y", "_1n", "u", "v", "q", "r", "m", "n", "assertIsSquare", "Fp", "root", "sqrt3mod4", "p1div4", "_4n", "sqrt5mod8", "p5div8", "_5n", "_8n", "n2", "_2n", "nv", "sqrt9mod16", "P", "Fp_", "Field", "tn", "tonelliShanks", "c1", "c2", "c3", "c4", "_7n", "_16n", "tv1", "tv2", "tv3", "tv4", "e1", "e2", "e3", "_3n", "Q", "S", "Z", "_Fp", "FpLegendre", "cc", "Q1div2", "M", "c", "t", "R", "i", "t_tmp", "exponent", "FpSqrt", "_9n", "isNegativeLE", "num", "FIELD_FIELDS", "validateField", "field", "initial", "opts", "map", "val", "_validateObject", "FpPow", "p", "d", "FpInvertBatch", "nums", "passZero", "inverted", "multipliedAcc", "acc", "invertedAcc", "FpLegendre", "Fp", "n", "p1mod2", "_1n", "_2n", "powered", "yes", "zero", "no", "nLength", "n", "nBitLength", "anumber", "_nBitLength", "nByteLength", "Field", "ORDER", "bitLenOrOpts", "isLE", "opts", "_0n", "_nbitLength", "_sqrt", "modFromBytes", "allowedLengths", "_opts", "BITS", "BYTES", "sqrtP", "f", "bitMask", "_1n", "num", "mod", "lhs", "rhs", "power", "FpPow", "invert", "FpSqrt", "numberToBytesLE", "numberToBytesBE", "bytes", "skipValidation", "padded", "scalar", "bytesToNumberLE", "bytesToNumberBE", "lst", "FpInvertBatch", "a", "b", "c", "_0n", "_1n", "negateCt", "condition", "item", "neg", "normalizeZ", "c", "points", "invertedZs", "FpInvertBatch", "p", "i", "validateW", "W", "bits", "calcWOpts", "scalarBits", "windows", "windowSize", "maxNumber", "mask", "bitMask", "shiftBy", "calcOffsets", "n", "window", "wOpts", "wbits", "nextN", "offsetStart", "offset", "isZero", "isNeg", "isNegF", "validateMSMPoints", "validateMSMScalars", "scalars", "field", "s", "pointPrecomputes", "pointWindowSizes", "getW", "P", "assert0", "wNAF", "Point", "elm", "d", "point", "base", "precomputes", "f", "wo", "offsetF", "acc", "transform", "comp", "scalar", "prev", "pippenger", "c", "fieldN", "points", "scalars", "validateMSMPoints", "validateMSMScalars", "plength", "slength", "zero", "wbits", "bitLen", "windowSize", "MASK", "bitMask", "buckets", "lastBits", "sum", "i", "j", "scalar", "resI", "sumI", "createField", "order", "field", "isLE", "validateField", "Field", "_createCurveFields", "type", "CURVE", "curveOpts", "FpFnLE", "p", "val", "_0n", "Fp", "Fn", "params", "_0n", "_1n", "_2n", "_8n", "isEdValidXY", "Fp", "CURVE", "x", "y", "x2", "y2", "left", "right", "edwards", "params", "extraOpts", "validated", "_createCurveFields", "Fn", "cofactor", "_validateObject", "MASK", "modP", "n", "uvRatio", "u", "v", "acoord", "title", "banZero", "min", "aInRange", "aextpoint", "other", "Point", "toAffineMemo", "memoized", "p", "iz", "X", "Y", "Z", "is0", "zz", "assertValidMemo", "a", "d", "T", "X2", "Y2", "Z2", "Z4", "aX2", "XY", "ZT", "bytes", "zip215", "len", "copyBytes", "_abytes2", "_abool2", "normed", "lastByte", "bytesToNumberLE", "max", "isValid", "isXOdd", "isLastByteOdd", "ensureBytes", "windowSize", "isLazy", "wnaf", "X1", "Y1", "Z1", "X1Z2", "X2Z1", "Y1Z2", "Y2Z1", "A", "B", "C", "D", "x1y1", "E", "G", "F", "H", "X3", "Y3", "T3", "Z3", "T1", "T2", "scalar", "f", "normalizeZ", "acc", "invertedZ", "bytesToHex", "points", "scalars", "pippenger", "wNAF", "PrimeEdwardsPoint", "ep", "_bytes", "notImplemented", "_hex", "eddsa", "cHash", "eddsaOpts", "prehash", "BASE", "randomBytes", "adjustScalarBytes", "domain", "data", "ctx", "phflag", "modN_LE", "hash", "getPrivateScalar", "key", "lengths", "hashed", "head", "prefix", "getExtendedPublicKey", "secretKey", "point", "pointBytes", "getPublicKey", "hashDomainToScalar", "context", "msgs", "msg", "concatBytes", "sign", "options", "r", "R", "k", "s", "rs", "verifyOpts", "verify", "sig", "publicKey", "mid", "SB", "_size", "randomSecretKey", "seed", "keygen", "utils", "isValidSecretKey", "isBytes", "isValidPublicKey", "size", "is25519", "_eddsa_legacy_opts_to_new", "c", "Field", "curveOpts", "_eddsa_new_output_to_legacy", "twistedEdwards", "EDDSA", "_0n", "_1n", "_2n", "_3n", "_5n", "_8n", "ed25519_CURVE_p", "ed25519_CURVE", "ed25519_pow_2_252_3", "x", "_10n", "_20n", "_40n", "_80n", "P", "b2", "b4", "pow2", "b5", "b10", "b20", "b40", "b80", "b160", "b240", "b250", "adjustScalarBytes", "bytes", "ED25519_SQRT_M1", "uvRatio", "u", "v", "v3", "mod", "v7", "pow", "vx2", "root1", "root2", "useRoot1", "useRoot2", "noRoot", "isNegativeLE", "Fp", "Field", "Fn", "ed25519Defaults", "sha512", "ed25519", "twistedEdwards", "SQRT_M1", "ED25519_SQRT_M1", "SQRT_AD_MINUS_ONE", "INVSQRT_A_MINUS_D", "ONE_MINUS_D_SQ", "D_MINUS_ONE_SQ", "invertSqrt", "number", "uvRatio", "_1n", "MAX_255B", "bytes255ToNumberLE", "bytes", "ed25519", "bytesToNumberLE", "calcElligatorRistrettoMap", "r0", "d", "ed25519_CURVE", "P", "ed25519_CURVE_p", "mod", "n", "Fp", "r", "Ns", "c", "D", "Ns_D_is_sq", "s", "s_", "isNegativeLE", "Nt", "s2", "W0", "W1", "W2", "W3", "ristretto255_map", "abytes", "r1", "R1", "r2", "R2", "_RistrettoPoint", "__RistrettoPoint", "PrimeEdwardsPoint", "ep", "ap", "other", "hex", "ensureBytes", "a", "equalBytes", "u1", "u2", "u1_2", "u2_2", "v", "isValid", "I", "Dx", "Dy", "x", "y", "t", "_0n", "points", "scalars", "pippenger", "X", "Y", "Z", "T", "u2sq", "invsqrt", "D1", "D2", "zInv", "_x", "_y", "X1", "Y1", "X2", "Y2", "one", "two", "Fn", "encodeLenBytes", "len", "InputError", "DerEncodeErrorCode", "encodeLen", "buf", "offset", "decodeLenBytes", "DerDecodeErrorCode", "decodeLen", "lenBytes", "DER_COSE_OID", "ED25519_OID", "SECP256K1_OID", "BLS12_381_G2_OID", "wrapDER", "payload", "oid", "bitStringHeaderLength", "unwrapDER", "derEncoded", "expect", "n", "msg", "uint8Equals", "payloadLen", "result", "DerDecodeLengthMismatchErrorCode", "isObject", "value", "Ed25519PublicKey", "_Ed25519PublicKey", "maybeKey", "key", "hexToBytes", "view", "uint8FromBufLike", "rawKey", "derKey", "publicKey", "wrapDER", "ED25519_OID", "unwrapped", "unwrapDER", "#rawKey", "#derKey", "Ed25519KeyIdentity", "_Ed25519KeyIdentity", "SignIdentity", "seed", "ed25519", "uint8Equals", "sk", "i", "pk", "obj", "publicKeyDer", "privateKeyRaw", "json", "parsed", "privateKey", "secretKey", "#publicKey", "#privateKey", "bytesToHex", "challenge", "signature", "sig", "msg", "message", "x", "CryptoError", "_CryptoError", "message", "_getEffectiveCrypto", "subtleCrypto", "ECDSAKeyIdentity", "_ECDSAKeyIdentity", "SignIdentity", "options", "extractable", "keyUsages", "effectiveCrypto", "keyPair", "derKey", "uint8FromBufLike", "key", "challenge", "params", "signature", "PartialIdentity", "#inner", "Principal", "inner", "safeBytesToHex", "data", "bytesToHex", "_parseBlob", "value", "hexToBytes", "Delegation", "pubkey", "expiration", "targets", "p", "_createSingleDelegation", "from", "to", "delegation", "challenge", "IC_REQUEST_AUTH_DELEGATION_DOMAIN_SEPARATOR", "requestIdOf", "signature", "DelegationChain", "_DelegationChain", "options", "json", "publicKey", "delegations", "parsedDelegations", "signedDelegation", "t", "Principal", "DelegationIdentity", "SignIdentity", "key", "_inner", "_delegation", "blob", "request", "body", "fields", "requestId", "IC_REQUEST_DOMAIN_SEPARATOR", "PartialDelegationIdentity", "_PartialDelegationIdentity", "PartialIdentity", "#delegation", "inner", "isDelegationValid", "chain", "checks", "scopes", "maybeScope", "s", "scope", "none", "target", "events", "IdleManager", "_IdleManager", "options", "onIdle", "idleTimeout", "_resetTimer", "name", "debounce", "func", "wait", "timeout", "args", "context", "later", "scroll", "callback", "cb", "exit", "instanceOfAny", "object", "constructors", "c", "idbProxyableTypes", "cursorAdvanceMethods", "getIdbProxyableTypes", "getCursorAdvanceMethods", "cursorRequestMap", "transactionDoneMap", "transactionStoreNamesMap", "transformCache", "reverseTransformCache", "promisifyRequest", "request", "promise", "resolve", "reject", "unlisten", "success", "error", "wrap", "value", "cacheDonePromiseForTransaction", "tx", "done", "complete", "idbProxyTraps", "target", "prop", "receiver", "replaceTraps", "callback", "wrapFunction", "func", "storeNames", "args", "unwrap", "transformCachableValue", "newValue", "openDB", "name", "version", "blocked", "upgrade", "blocking", "terminated", "request", "openPromise", "wrap", "event", "db", "readMethods", "writeMethods", "cachedMethods", "getMethod", "target", "prop", "targetFuncName", "useIndex", "isWrite", "method", "storeName", "args", "tx", "replaceTraps", "oldTraps", "receiver", "AUTH_DB_NAME", "OBJECT_STORE_NAME", "_openDbStore", "dbName", "storeName", "version", "KEY_STORAGE_DELEGATION", "KEY_STORAGE_KEY", "openDB", "database", "_getValue", "db", "key", "_setValue", "value", "_removeValue", "IdbKeyVal", "_IdbKeyVal", "_db", "_storeName", "options", "DB_VERSION", "KEY_STORAGE_KEY", "KEY_STORAGE_DELEGATION", "KEY_VECTOR", "DB_VERSION", "LocalStorage", "prefix", "_localStorage", "key", "value", "ls", "IdbStorage", "#options", "options", "resolve", "reject", "IdbKeyVal", "db", "NANOSECONDS_PER_SECOND", "SECONDS_PER_HOUR", "NANOSECONDS_PER_HOUR", "IDENTITY_PROVIDER_DEFAULT", "IDENTITY_PROVIDER_ENDPOINT", "DEFAULT_MAX_TIME_TO_LIVE", "ECDSA_KEY_LABEL", "ED25519_KEY_LABEL", "INTERRUPT_CHECK_INTERVAL", "ERROR_USER_INTERRUPT", "AuthClient", "_AuthClient", "_identity", "_key", "_chain", "_storage", "idleManager", "_createOptions", "_idpWindow", "_eventHandler", "options", "storage", "IdbStorage", "keyType", "key", "maybeIdentityStorage", "KEY_STORAGE_KEY", "fallbackLocalStorage", "LocalStorage", "localChain", "KEY_STORAGE_DELEGATION", "localKey", "error", "Ed25519KeyIdentity", "ECDSAKeyIdentity", "identity", "AnonymousIdentity", "chain", "chainStorage", "DelegationChain", "isDelegationValid", "PartialDelegationIdentity", "DelegationIdentity", "_deleteStorage", "e", "IdleManager", "persistKey", "idleOptions", "message", "onSuccess", "delegations", "signedDelegation", "Delegation", "delegationChain", "loginOptions", "mergeLoginOptions", "maxTimeToLive", "identityProviderUrl", "checkInterruption", "event", "request", "err", "errorMessage", "onError", "KEY_VECTOR", "otherLoginOptions", "customValues", "toStoredKey", "serialized", "DELEGATION_IDENTITY_EXPIRATION", "AUTH_TIMER_INTERVAL", "FromStringToTokenError", "E8S_PER_TOKEN", "isNullish", "argument", "ALPHABET", "LOOKUP_TABLE", "i", "lookUpTable", "AuthClientStore", "_AuthClientStore", "#instance", "#authClient", "u", "AuthClient", "IdbStorage", "KEY_STORAGE_KEY", "delegationChain", "sessionKey", "storage", "KEY_STORAGE_DELEGATION", "onAuthMessage", "data", "msg", "startTimer", "stopTimer", "timer", "onTimerSignOut", "AUTH_TIMER_INTERVAL", "auth", "chain", "checkAuthentication", "checkDelegationChain", "emitExpirationTime", "logout", "AuthClientStore", "delegationChain", "IdbStorage", "KEY_STORAGE_DELEGATION", "delegation", "DelegationChain", "isDelegationValid", "expirationTime", "authRemainingTime", "params", "onAuthMessage"]
3
+ "sources": ["../../../../node_modules/@icp-sdk/core/src/principal/utils/base32.ts", "../../../../node_modules/@icp-sdk/core/src/principal/utils/getCrc.ts", "../../../../node_modules/@noble/hashes/src/crypto.ts", "../../../../node_modules/@noble/hashes/src/utils.ts", "../../../../node_modules/@noble/hashes/src/_md.ts", "../../../../node_modules/@noble/hashes/src/_u64.ts", "../../../../node_modules/@noble/hashes/src/sha2.ts", "../../../../node_modules/@icp-sdk/core/src/principal/principal.ts", "../../../../node_modules/@icp-sdk/core/src/agent/errors.ts", "../../../../node_modules/@icp-sdk/core/src/candid/utils/buffer.ts", "../../../../node_modules/@icp-sdk/core/src/candid/utils/bigint-math.ts", "../../../../node_modules/@icp-sdk/core/src/candid/utils/leb128.ts", "../../../../node_modules/@icp-sdk/core/src/agent/utils/buffer.ts", "../../../../node_modules/@icp-sdk/core/src/agent/request_id.ts", "../../../../node_modules/@icp-sdk/core/src/agent/constants.ts", "../../../../node_modules/@icp-sdk/core/src/agent/auth.ts", "../../../../node_modules/@noble/curves/src/utils.ts", "../../../../node_modules/@noble/curves/src/abstract/modular.ts", "../../../../node_modules/@noble/curves/src/abstract/curve.ts", "../../../../node_modules/@noble/curves/src/abstract/edwards.ts", "../../../../node_modules/@noble/curves/src/ed25519.ts", "../../../../node_modules/@icp-sdk/core/src/agent/der.ts", "../../../../node_modules/@icp-sdk/core/src/identity/identity/ed25519.ts", "../../../../node_modules/@icp-sdk/core/src/identity/identity/ecdsa.ts", "../../../../node_modules/@icp-sdk/core/src/identity/identity/partial.ts", "../../../../node_modules/@icp-sdk/core/src/identity/identity/delegation.ts", "../../../../node_modules/@icp-sdk/auth/src/client/idle-manager.ts", "../../../../node_modules/idb/build/wrap-idb-value.js", "../../../../node_modules/idb/build/index.js", "../../../../node_modules/@icp-sdk/auth/src/client/db.ts", "../../../../node_modules/@icp-sdk/auth/src/client/storage.ts", "../../../../node_modules/@icp-sdk/auth/src/client/auth-client.ts", "../../src/auth/constants/auth.constants.ts", "../../../../node_modules/@dfinity/utils/src/enums/token.enums.ts", "../../../../node_modules/@dfinity/utils/src/constants/constants.ts", "../../../../node_modules/@dfinity/utils/src/parser/token.ts", "../../../../node_modules/@dfinity/utils/src/services/canister.ts", "../../../../node_modules/@dfinity/utils/src/utils/nullish.utils.ts", "../../../../node_modules/@dfinity/utils/src/services/query.ts", "../../../../node_modules/@dfinity/utils/src/utils/actor.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/agent.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/asserts.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/arrays.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/base32.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/base64.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/crc.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/json.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/crypto.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/date.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/debounce.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/did.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/principal.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/version.utils.ts", "../../src/auth/stores/auth-client.store.ts", "../../src/auth/workers/auth.worker.ts", "../../src/workers/auth.worker.ts"],
4
+ "sourcesContent": ["const alphabet = 'abcdefghijklmnopqrstuvwxyz234567';\n\n// Build a lookup table for decoding.\nconst lookupTable: Record<string, number> = Object.create(null);\nfor (let i = 0; i < alphabet.length; i++) {\n lookupTable[alphabet[i]] = i;\n}\n\n// Add aliases for rfc4648.\nlookupTable['0'] = lookupTable.o;\nlookupTable['1'] = lookupTable.i;\n\n/**\n * @param input The Uint8Array to encode.\n * @returns A Base32 string encoding the input.\n */\nexport function base32Encode(input: Uint8Array): string {\n // How many bits will we skip from the first byte.\n let skip = 0;\n // 5 high bits, carry from one byte to the next.\n let bits = 0;\n\n // The output string in base32.\n let output = '';\n\n function encodeByte(byte: number) {\n if (skip < 0) {\n // we have a carry from the previous byte\n bits |= byte >> -skip;\n } else {\n // no carry\n bits = (byte << skip) & 248;\n }\n\n if (skip > 3) {\n // Not enough data to produce a character, get us another one\n skip -= 8;\n return 1;\n }\n\n if (skip < 4) {\n // produce a character\n output += alphabet[bits >> 3];\n skip += 5;\n }\n\n return 0;\n }\n\n for (let i = 0; i < input.length; ) {\n i += encodeByte(input[i]);\n }\n\n return output + (skip < 0 ? alphabet[bits >> 3] : '');\n}\n\n/**\n * @param input The base32 encoded string to decode.\n */\nexport function base32Decode(input: string): Uint8Array {\n // how many bits we have from the previous character.\n let skip = 0;\n // current byte we're producing.\n let byte = 0;\n\n const output = new Uint8Array(((input.length * 4) / 3) | 0);\n let o = 0;\n\n function decodeChar(char: string) {\n // Consume a character from the stream, store\n // the output in this.output. As before, better\n // to use update().\n let val = lookupTable[char.toLowerCase()];\n if (val === undefined) {\n throw new Error(`Invalid character: ${JSON.stringify(char)}`);\n }\n\n // move to the high bits\n val <<= 3;\n byte |= val >>> skip;\n skip += 5;\n\n if (skip >= 8) {\n // We have enough bytes to produce an output\n output[o++] = byte;\n skip -= 8;\n\n if (skip > 0) {\n byte = (val << (5 - skip)) & 255;\n } else {\n byte = 0;\n }\n }\n }\n\n for (const c of input) {\n decodeChar(c);\n }\n\n return output.slice(0, o);\n}\n", "// This file is translated to JavaScript from\n// https://lxp32.github.io/docs/a-simple-example-crc32-calculation/\nconst lookUpTable: Uint32Array = new Uint32Array([\n 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,\n 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,\n 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,\n 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,\n 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,\n 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,\n 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,\n 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,\n 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,\n 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,\n 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,\n 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,\n 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,\n 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,\n 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,\n 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,\n 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,\n 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,\n 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,\n 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,\n 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,\n 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,\n 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,\n 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,\n 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,\n 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,\n 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,\n 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,\n 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,\n 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,\n 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,\n 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,\n]);\n\n/**\n * Calculate the CRC32 of a Uint8Array.\n * @param buf The Uint8Array to calculate the CRC32 of.\n */\nexport function getCrc32(buf: Uint8Array): number {\n let crc = -1;\n\n for (let i = 0; i < buf.length; i++) {\n const byte = buf[i];\n const t = (byte ^ crc) & 0xff;\n crc = lookUpTable[t] ^ (crc >>> 8);\n }\n\n return (crc ^ -1) >>> 0;\n}\n", "/**\n * Internal webcrypto alias.\n * We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n * See utils.ts for details.\n * @module\n */\ndeclare const globalThis: Record<string, any> | undefined;\nexport const crypto: any =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\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\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\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\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) 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/**\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 (): Promise<void> => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== 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 as T1 & T2;\n}\n\n/** Hash interface. */\nexport type IHash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\n\n/** For runtime check if class implements interface */\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n abstract clone(): T;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\n/** Hash function */\nexport type CHash = ReturnType<typeof createHasher>;\n/** Hash function with output */\nexport type CHashO = ReturnType<typeof createOptHasher>;\n/** XOF with output */\nexport type CHashXO = ReturnType<typeof createXOFer>;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher<T extends Hash<T>>(\n hashCons: () => Hash<T>\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash<T>;\n} {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function createOptHasher<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): Hash<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\n\nexport function createXOFer<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): HashXOF<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\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", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { type Input, Hash, abytes, aexists, aoutput, clean, createView, toBytes } from './utils.ts';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD<T extends HashMD<T>> extends Hash<T> {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n super();\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: Input): this {\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) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n", "/**\n * Internal helpers for u64. 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);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false): Uint32Array[] {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));\n\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(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n", "/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [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.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, rotr } from './utils.ts';\n\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\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD<SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n\n constructor(outputLen: number = 32) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\nexport class SHA224 extends SHA256 {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// 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\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\nexport class SHA512 extends HashMD<SHA512> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor(outputLen: number = 64) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // 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 protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nexport class SHA384 extends SHA512 {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\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\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]);\n\nexport class SHA512_224 extends SHA512 {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\nexport class SHA512_256 extends SHA512 {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634.\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: CHash = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash = /* @__PURE__ */ createHasher(() => new SHA224());\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash = /* @__PURE__ */ createHasher(() => new SHA384());\n\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: CHash = /* @__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: CHash = /* @__PURE__ */ createHasher(() => new SHA512_224());\n", "import { base32Decode, base32Encode } from './utils/base32.ts';\nimport { getCrc32 } from './utils/getCrc.ts';\nimport { sha224 } from '@noble/hashes/sha2';\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils';\n\nexport const JSON_KEY_PRINCIPAL = '__principal__';\nconst SELF_AUTHENTICATING_SUFFIX = 2;\nconst ANONYMOUS_SUFFIX = 4;\n\nconst MANAGEMENT_CANISTER_PRINCIPAL_TEXT_STR = 'aaaaa-aa';\n\nexport type JsonnablePrincipal = {\n [JSON_KEY_PRINCIPAL]: string;\n};\n\nexport class Principal {\n public static anonymous(): Principal {\n return new this(new Uint8Array([ANONYMOUS_SUFFIX]));\n }\n\n /**\n * Utility method, returning the principal representing the management canister, decoded from the hex string `'aaaaa-aa'`\n * @returns {Principal} principal of the management canister\n */\n public static managementCanister(): Principal {\n return this.fromText(MANAGEMENT_CANISTER_PRINCIPAL_TEXT_STR);\n }\n\n public static selfAuthenticating(publicKey: Uint8Array): Principal {\n const sha = sha224(publicKey);\n return new this(new Uint8Array([...sha, SELF_AUTHENTICATING_SUFFIX]));\n }\n\n public static from(other: unknown): Principal {\n if (typeof other === 'string') {\n return Principal.fromText(other);\n } else if (Object.getPrototypeOf(other) === Uint8Array.prototype) {\n return new Principal(other as Uint8Array);\n } else if (Principal.isPrincipal(other)) {\n return new Principal(other._arr);\n }\n\n throw new Error(`Impossible to convert ${JSON.stringify(other)} to Principal.`);\n }\n\n public static fromHex(hex: string): Principal {\n return new this(hexToBytes(hex));\n }\n\n public static fromText(text: string): Principal {\n let maybePrincipal = text;\n // If formatted as JSON string, parse it first\n if (text.includes(JSON_KEY_PRINCIPAL)) {\n const obj = JSON.parse(text);\n if (JSON_KEY_PRINCIPAL in obj) {\n maybePrincipal = obj[JSON_KEY_PRINCIPAL];\n }\n }\n\n const canisterIdNoDash = maybePrincipal.toLowerCase().replace(/-/g, '');\n\n let arr = base32Decode(canisterIdNoDash);\n arr = arr.slice(4, arr.length);\n\n const principal = new this(arr);\n if (principal.toText() !== maybePrincipal) {\n throw new Error(\n `Principal \"${principal.toText()}\" does not have a valid checksum (original value \"${maybePrincipal}\" may not be a valid Principal ID).`,\n );\n }\n\n return principal;\n }\n\n public static fromUint8Array(arr: Uint8Array): Principal {\n return new this(arr);\n }\n\n public static isPrincipal(other: unknown): other is Principal {\n return (\n other instanceof Principal ||\n (typeof other === 'object' &&\n other !== null &&\n '_isPrincipal' in other &&\n (other as { _isPrincipal: boolean })['_isPrincipal'] === true &&\n '_arr' in other &&\n (other as { _arr: Uint8Array })['_arr'] instanceof Uint8Array)\n );\n }\n\n public readonly _isPrincipal = true;\n\n protected constructor(private _arr: Uint8Array) {}\n\n public isAnonymous(): boolean {\n return this._arr.byteLength === 1 && this._arr[0] === ANONYMOUS_SUFFIX;\n }\n\n public toUint8Array(): Uint8Array {\n return this._arr;\n }\n\n public toHex(): string {\n return bytesToHex(this._arr).toUpperCase();\n }\n\n public toText(): string {\n const checksumArrayBuf = new ArrayBuffer(4);\n const view = new DataView(checksumArrayBuf);\n view.setUint32(0, getCrc32(this._arr));\n const checksum = new Uint8Array(checksumArrayBuf);\n\n const array = new Uint8Array([...checksum, ...this._arr]);\n\n const result = base32Encode(array);\n const matches = result.match(/.{1,5}/g);\n if (!matches) {\n // This should only happen if there's no character, which is unreachable.\n throw new Error();\n }\n return matches.join('-');\n }\n\n public toString(): string {\n return this.toText();\n }\n\n /**\n * Serializes to JSON\n * @returns {JsonnablePrincipal} a JSON object with a single key, {@link JSON_KEY_PRINCIPAL}, whose value is the principal as a string\n */\n public toJSON(): JsonnablePrincipal {\n return { [JSON_KEY_PRINCIPAL]: this.toText() };\n }\n\n /**\n * Utility method taking a Principal to compare against. Used for determining canister ranges in certificate verification\n * @param {Principal} other - a {@link Principal} to compare\n * @returns {'lt' | 'eq' | 'gt'} `'lt' | 'eq' | 'gt'` a string, representing less than, equal to, or greater than\n */\n public compareTo(other: Principal): 'lt' | 'eq' | 'gt' {\n for (let i = 0; i < Math.min(this._arr.length, other._arr.length); i++) {\n if (this._arr[i] < other._arr[i]) return 'lt';\n else if (this._arr[i] > other._arr[i]) return 'gt';\n }\n // Here, at least one principal is a prefix of the other principal (they could be the same)\n if (this._arr.length < other._arr.length) return 'lt';\n if (this._arr.length > other._arr.length) return 'gt';\n return 'eq';\n }\n\n /**\n * Utility method checking whether a provided Principal is less than or equal to the current one using the {@link Principal.compareTo} method\n * @param other a {@link Principal} to compare\n * @returns {boolean} boolean\n */\n public ltEq(other: Principal): boolean {\n const cmp = this.compareTo(other);\n return cmp == 'lt' || cmp == 'eq';\n }\n\n /**\n * Utility method checking whether a provided Principal is greater than or equal to the current one using the {@link Principal.compareTo} method\n * @param other a {@link Principal} to compare\n * @returns {boolean} boolean\n */\n public gtEq(other: Principal): boolean {\n const cmp = this.compareTo(other);\n return cmp == 'gt' || cmp == 'eq';\n }\n}\n", "import { Principal } from '#principal';\nimport {\n type HttpDetailsResponse,\n type NodeSignature,\n type ReplicaRejectCode,\n} from './agent/api.ts';\nimport { type RequestId } from './request_id.ts';\nimport { type RequestStatusResponseStatus } from './agent/http/index.ts';\nimport { type Expiry } from './agent/http/transforms.ts';\nimport { type HttpHeaderField } from './agent/http/types.ts';\nimport { LookupPathStatus, LookupSubtreeStatus } from './certificate.ts';\nimport { bytesToHex } from '@noble/hashes/utils';\n\nexport enum ErrorKindEnum {\n Trust = 'Trust',\n Protocol = 'Protocol',\n Reject = 'Reject',\n Transport = 'Transport',\n External = 'External',\n Limit = 'Limit',\n Input = 'Input',\n Unknown = 'Unknown',\n}\n\nexport type RequestContext = {\n requestId?: RequestId;\n senderPubKey: Uint8Array;\n senderSignature: Uint8Array;\n ingressExpiry: Expiry;\n};\n\nexport type CallContext = {\n canisterId: Principal;\n methodName: string;\n httpDetails: HttpDetailsResponse;\n};\n\nabstract class ErrorCode {\n public requestContext?: RequestContext;\n public callContext?: CallContext;\n\n constructor(public readonly isCertified: boolean = false) {}\n\n public abstract toErrorMessage(): string;\n\n public toString(): string {\n let errorMessage = this.toErrorMessage();\n if (this.requestContext) {\n errorMessage +=\n `\\nRequest context:\\n` +\n ` Request ID (hex): ${this.requestContext.requestId ? bytesToHex(this.requestContext.requestId) : 'undefined'}\\n` +\n ` Sender pubkey (hex): ${bytesToHex(this.requestContext.senderPubKey)}\\n` +\n ` Sender signature (hex): ${bytesToHex(this.requestContext.senderSignature)}\\n` +\n ` Ingress expiry: ${this.requestContext.ingressExpiry.toString()}`;\n }\n if (this.callContext) {\n errorMessage +=\n `\\nCall context:\\n` +\n ` Canister ID: ${this.callContext.canisterId.toText()}\\n` +\n ` Method name: ${this.callContext.methodName}\\n` +\n ` HTTP details: ${JSON.stringify(this.callContext.httpDetails, null, 2)}`;\n }\n return errorMessage;\n }\n}\n\n/**\n * An error that happens in the Agent. This is the root of all errors and should be used\n * everywhere in the Agent code (this package).\n *\n * To know if the error is certified, use the `isCertified` getter.\n */\nexport class AgentError extends Error {\n public name = 'AgentError';\n // override the Error.cause property\n public readonly cause: { code: ErrorCode; kind: ErrorKindEnum };\n\n get code(): ErrorCode {\n return this.cause.code;\n }\n set code(code: ErrorCode) {\n this.cause.code = code;\n }\n\n get kind(): ErrorKindEnum {\n return this.cause.kind;\n }\n set kind(kind: ErrorKindEnum) {\n this.cause.kind = kind;\n }\n\n /**\n * Reads the `isCertified` property of the underlying error code.\n * @returns `true` if the error is certified, `false` otherwise.\n */\n get isCertified(): boolean {\n return this.code.isCertified;\n }\n\n constructor(code: ErrorCode, kind: ErrorKindEnum) {\n super(code.toString());\n this.cause = { code, kind };\n Object.setPrototypeOf(this, AgentError.prototype);\n }\n\n public hasCode<C extends ErrorCode>(code: new (...args: never[]) => C): boolean {\n return this.code instanceof code;\n }\n\n public toString(): string {\n return `${this.name} (${this.kind}): ${this.message}`;\n }\n}\n\nclass ErrorKind extends AgentError {\n public static fromCode<C extends ErrorCode, E extends ErrorKind>(\n this: new (code: C) => E,\n code: C,\n ): E {\n return new this(code);\n }\n}\n\nexport class TrustError extends ErrorKind {\n public name = 'TrustError';\n\n constructor(code: ErrorCode) {\n super(code, ErrorKindEnum.Trust);\n Object.setPrototypeOf(this, TrustError.prototype);\n }\n}\n\nexport class ProtocolError extends ErrorKind {\n public name = 'ProtocolError';\n\n constructor(code: ErrorCode) {\n super(code, ErrorKindEnum.Protocol);\n Object.setPrototypeOf(this, ProtocolError.prototype);\n }\n}\n\nexport class RejectError extends ErrorKind {\n public name = 'RejectError';\n\n constructor(code: ErrorCode) {\n super(code, ErrorKindEnum.Reject);\n Object.setPrototypeOf(this, RejectError.prototype);\n }\n}\n\nexport class TransportError extends ErrorKind {\n public name = 'TransportError';\n\n constructor(code: ErrorCode) {\n super(code, ErrorKindEnum.Transport);\n Object.setPrototypeOf(this, TransportError.prototype);\n }\n}\n\nexport class ExternalError extends ErrorKind {\n public name = 'ExternalError';\n\n constructor(code: ErrorCode) {\n super(code, ErrorKindEnum.External);\n Object.setPrototypeOf(this, ExternalError.prototype);\n }\n}\n\nexport class LimitError extends ErrorKind {\n public name = 'LimitError';\n\n constructor(code: ErrorCode) {\n super(code, ErrorKindEnum.Limit);\n Object.setPrototypeOf(this, LimitError.prototype);\n }\n}\n\nexport class InputError extends ErrorKind {\n public name = 'InputError';\n\n constructor(code: ErrorCode) {\n super(code, ErrorKindEnum.Input);\n Object.setPrototypeOf(this, InputError.prototype);\n }\n}\n\nexport class UnknownError extends ErrorKind {\n public name = 'UnknownError';\n\n constructor(code: ErrorCode) {\n super(code, ErrorKindEnum.Unknown);\n Object.setPrototypeOf(this, UnknownError.prototype);\n }\n}\n\nexport class CertificateVerificationErrorCode extends ErrorCode {\n public name = 'CertificateVerificationErrorCode';\n\n constructor(\n public readonly reason: string,\n public readonly error?: unknown,\n ) {\n super();\n Object.setPrototypeOf(this, CertificateVerificationErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n let errorMessage = this.reason;\n if (this.error) {\n errorMessage += `: ${formatUnknownError(this.error)}`;\n }\n return `Certificate verification error: \"${errorMessage}\"`;\n }\n}\n\nexport class CertificateTimeErrorCode extends ErrorCode {\n public name = 'CertificateTimeErrorCode';\n\n constructor(\n public readonly maxAgeInMinutes: number,\n public readonly certificateTime: Date,\n public readonly currentTime: Date,\n public readonly timeDiffMsecs: number,\n public readonly ageType: 'past' | 'future',\n ) {\n super();\n Object.setPrototypeOf(this, CertificateTimeErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Certificate is signed more than ${this.maxAgeInMinutes} minutes in the ${this.ageType}. Certificate time: ${this.certificateTime.toISOString()} Current time: ${this.currentTime.toISOString()} Clock drift: ${this.timeDiffMsecs}ms`;\n }\n}\n\nexport class CertificateHasTooManyDelegationsErrorCode extends ErrorCode {\n public name = 'CertificateHasTooManyDelegationsErrorCode';\n\n constructor() {\n super();\n Object.setPrototypeOf(this, CertificateHasTooManyDelegationsErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return 'Certificate has too many delegations';\n }\n}\n\nexport class CertificateNotAuthorizedErrorCode extends ErrorCode {\n public name = 'CertificateNotAuthorizedErrorCode';\n\n constructor(\n public readonly canisterId: Principal,\n public readonly subnetId: Principal,\n ) {\n super();\n Object.setPrototypeOf(this, CertificateNotAuthorizedErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `The certificate contains a delegation that does not include the canister ${this.canisterId.toText()} in the canister_ranges field. Subnet ID: ${this.subnetId.toText()}`;\n }\n}\n\nexport class CertificateNotAuthorizedForSubnetErrorCode extends ErrorCode {\n public name = 'CertificateNotAuthorizedForSubnetErrorCode';\n\n constructor(public readonly subnetId: Principal) {\n super();\n Object.setPrototypeOf(this, CertificateNotAuthorizedForSubnetErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `The certificate is not authorized for subnet ${this.subnetId.toText()}`;\n }\n}\n\nexport class LookupErrorCode extends ErrorCode {\n public name = 'LookupErrorCode';\n\n constructor(\n public readonly message: string,\n public readonly lookupStatus: LookupPathStatus | LookupSubtreeStatus,\n ) {\n super();\n Object.setPrototypeOf(this, LookupErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `${this.message}. Lookup status: ${this.lookupStatus}`;\n }\n}\n\nexport class MalformedLookupFoundValueErrorCode extends ErrorCode {\n public name = 'MalformedLookupFoundValueErrorCode';\n\n constructor(public readonly message: string) {\n super();\n Object.setPrototypeOf(this, MalformedLookupFoundValueErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return this.message;\n }\n}\n\nexport class MissingLookupValueErrorCode extends ErrorCode {\n public name = 'MissingLookupValueErrorCode';\n\n constructor(public readonly message: string) {\n super();\n Object.setPrototypeOf(this, MissingLookupValueErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return this.message;\n }\n}\n\nexport class DerKeyLengthMismatchErrorCode extends ErrorCode {\n public name = 'DerKeyLengthMismatchErrorCode';\n\n constructor(\n public readonly expectedLength: number,\n public readonly actualLength: number,\n ) {\n super();\n Object.setPrototypeOf(this, DerKeyLengthMismatchErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `BLS DER-encoded public key must be ${this.expectedLength} bytes long, but is ${this.actualLength} bytes long`;\n }\n}\n\nexport class DerPrefixMismatchErrorCode extends ErrorCode {\n public name = 'DerPrefixMismatchErrorCode';\n\n constructor(\n public readonly expectedPrefix: Uint8Array,\n public readonly actualPrefix: Uint8Array,\n ) {\n super();\n Object.setPrototypeOf(this, DerPrefixMismatchErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `BLS DER-encoded public key is invalid. Expected the following prefix: ${bytesToHex(this.expectedPrefix)}, but got ${bytesToHex(this.actualPrefix)}`;\n }\n}\n\nexport class DerDecodeLengthMismatchErrorCode extends ErrorCode {\n public name = 'DerDecodeLengthMismatchErrorCode';\n\n constructor(\n public readonly expectedLength: number,\n public readonly actualLength: number,\n ) {\n super();\n Object.setPrototypeOf(this, DerDecodeLengthMismatchErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `DER payload mismatch: Expected length ${this.expectedLength}, actual length: ${this.actualLength}`;\n }\n}\n\nexport class DerDecodeErrorCode extends ErrorCode {\n public name = 'DerDecodeErrorCode';\n\n constructor(public readonly error: string) {\n super();\n Object.setPrototypeOf(this, DerDecodeErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Failed to decode DER: ${this.error}`;\n }\n}\n\nexport class DerEncodeErrorCode extends ErrorCode {\n public name = 'DerEncodeErrorCode';\n\n constructor(public readonly error: string) {\n super();\n Object.setPrototypeOf(this, DerEncodeErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Failed to encode DER: ${this.error}`;\n }\n}\n\nexport class CborDecodeErrorCode extends ErrorCode {\n public name = 'CborDecodeErrorCode';\n\n constructor(\n public readonly error: unknown,\n public readonly input: Uint8Array,\n ) {\n super();\n Object.setPrototypeOf(this, CborDecodeErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Failed to decode CBOR: ${formatUnknownError(this.error)}, input: ${bytesToHex(this.input)}`;\n }\n}\n\nexport class CborEncodeErrorCode extends ErrorCode {\n public name = 'CborEncodeErrorCode';\n\n constructor(\n public readonly error: unknown,\n public readonly value: unknown,\n ) {\n super();\n Object.setPrototypeOf(this, CborEncodeErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Failed to encode CBOR: ${formatUnknownError(this.error)}, input: ${this.value}`;\n }\n}\n\nexport class HexDecodeErrorCode extends ErrorCode {\n public name = 'HexDecodeErrorCode';\n\n constructor(public readonly error: string) {\n super();\n Object.setPrototypeOf(this, HexDecodeErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Failed to decode hex: ${this.error}`;\n }\n}\n\nexport class TimeoutWaitingForResponseErrorCode extends ErrorCode {\n public name = 'TimeoutWaitingForResponseErrorCode';\n\n constructor(\n public readonly message: string,\n public readonly requestId?: RequestId,\n public readonly status?: RequestStatusResponseStatus,\n ) {\n super();\n Object.setPrototypeOf(this, TimeoutWaitingForResponseErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n let errorMessage = `${this.message}\\n`;\n if (this.requestId) {\n errorMessage += ` Request ID: ${bytesToHex(this.requestId)}\\n`;\n }\n if (this.status) {\n errorMessage += ` Request status: ${this.status}\\n`;\n }\n return errorMessage;\n }\n}\n\nexport class CertificateOutdatedErrorCode extends ErrorCode {\n public name = 'CertificateOutdatedErrorCode';\n\n constructor(\n public readonly maxIngressExpiryInMinutes: number,\n public readonly requestId: RequestId,\n public readonly retryTimes?: number,\n ) {\n super();\n Object.setPrototypeOf(this, CertificateOutdatedErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n let errorMessage = `Certificate is stale (over ${this.maxIngressExpiryInMinutes} minutes). Is the computer's clock synchronized?\\n Request ID: ${bytesToHex(this.requestId)}\\n`;\n if (this.retryTimes !== undefined) {\n errorMessage += ` Retried ${this.retryTimes} times.`;\n }\n return errorMessage;\n }\n}\n\nexport class CertifiedRejectErrorCode extends ErrorCode {\n public name = 'CertifiedRejectErrorCode';\n\n constructor(\n public readonly requestId: RequestId,\n public readonly rejectCode: ReplicaRejectCode,\n public readonly rejectMessage: string,\n public readonly rejectErrorCode: string | undefined,\n ) {\n super(true);\n Object.setPrototypeOf(this, CertifiedRejectErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return (\n `The replica returned a rejection error:\\n` +\n ` Request ID: ${bytesToHex(this.requestId)}\\n` +\n ` Reject code: ${this.rejectCode}\\n` +\n ` Reject text: ${this.rejectMessage}\\n` +\n ` Error code: ${this.rejectErrorCode}\\n`\n );\n }\n}\n\nexport class UncertifiedRejectErrorCode extends ErrorCode {\n public name = 'UncertifiedRejectErrorCode';\n\n constructor(\n public readonly requestId: RequestId,\n public readonly rejectCode: ReplicaRejectCode,\n public readonly rejectMessage: string,\n public readonly rejectErrorCode: string | undefined,\n public readonly signatures: NodeSignature[] | undefined,\n ) {\n super();\n Object.setPrototypeOf(this, UncertifiedRejectErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return (\n `The replica returned a rejection error:\\n` +\n ` Request ID: ${bytesToHex(this.requestId)}\\n` +\n ` Reject code: ${this.rejectCode}\\n` +\n ` Reject text: ${this.rejectMessage}\\n` +\n ` Error code: ${this.rejectErrorCode}\\n`\n );\n }\n}\n\nexport class UncertifiedRejectUpdateErrorCode extends ErrorCode {\n public name = 'UncertifiedRejectUpdateErrorCode';\n\n constructor(\n public readonly requestId: RequestId,\n public readonly rejectCode: ReplicaRejectCode,\n public readonly rejectMessage: string,\n public readonly rejectErrorCode: string | undefined,\n ) {\n super();\n Object.setPrototypeOf(this, UncertifiedRejectUpdateErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return (\n `The replica returned a rejection error:\\n` +\n ` Request ID: ${bytesToHex(this.requestId)}\\n` +\n ` Reject code: ${this.rejectCode}\\n` +\n ` Reject text: ${this.rejectMessage}\\n` +\n ` Error code: ${this.rejectErrorCode}\\n`\n );\n }\n}\n\nexport class RequestStatusDoneNoReplyErrorCode extends ErrorCode {\n public name = 'RequestStatusDoneNoReplyErrorCode';\n\n constructor(public readonly requestId: RequestId) {\n super();\n Object.setPrototypeOf(this, RequestStatusDoneNoReplyErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return (\n `Call was marked as done but we never saw the reply:\\n` +\n ` Request ID: ${bytesToHex(this.requestId)}\\n`\n );\n }\n}\n\nexport class MissingRootKeyErrorCode extends ErrorCode {\n public name = 'MissingRootKeyErrorCode';\n\n constructor(public readonly shouldFetchRootKey?: boolean) {\n super();\n Object.setPrototypeOf(this, MissingRootKeyErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n if (this.shouldFetchRootKey === undefined) {\n return 'Agent is missing root key';\n }\n return `Agent is missing root key and the shouldFetchRootKey value is set to ${this.shouldFetchRootKey}. The root key should only be unknown if you are in local development. Otherwise you should avoid fetching and use the default IC Root Key or the known root key of your environment.`;\n }\n}\n\nexport class HashValueErrorCode extends ErrorCode {\n public name = 'HashValueErrorCode';\n\n constructor(public readonly value: unknown) {\n super();\n Object.setPrototypeOf(this, HashValueErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Attempt to hash a value of unsupported type: ${this.value}`;\n }\n}\n\nexport class HttpDefaultFetchErrorCode extends ErrorCode {\n public name = 'HttpDefaultFetchErrorCode';\n\n constructor(public readonly error: string) {\n super();\n Object.setPrototypeOf(this, HttpDefaultFetchErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return this.error;\n }\n}\n\nexport class IdentityInvalidErrorCode extends ErrorCode {\n public name = 'IdentityInvalidErrorCode';\n\n constructor() {\n super();\n Object.setPrototypeOf(this, IdentityInvalidErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return \"This identity has expired due this application's security policy. Please refresh your authentication.\";\n }\n}\n\nexport class IngressExpiryInvalidErrorCode extends ErrorCode {\n public name = 'IngressExpiryInvalidErrorCode';\n\n constructor(\n public readonly message: string,\n public readonly providedIngressExpiryInMinutes: number,\n ) {\n super();\n Object.setPrototypeOf(this, IngressExpiryInvalidErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `${this.message}. Provided ingress expiry time is ${this.providedIngressExpiryInMinutes} minutes.`;\n }\n}\n\nexport class CreateHttpAgentErrorCode extends ErrorCode {\n public name = 'CreateHttpAgentErrorCode';\n\n constructor() {\n super();\n Object.setPrototypeOf(this, CreateHttpAgentErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return 'Failed to create agent from provided agent';\n }\n}\n\nexport class MalformedSignatureErrorCode extends ErrorCode {\n public name = 'MalformedSignatureErrorCode';\n\n constructor(public readonly error: string) {\n super();\n Object.setPrototypeOf(this, MalformedSignatureErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Query response contained a malformed signature: ${this.error}`;\n }\n}\n\nexport class MissingSignatureErrorCode extends ErrorCode {\n public name = 'MissingSignatureErrorCode';\n\n constructor() {\n super();\n Object.setPrototypeOf(this, MissingSignatureErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return 'Query response did not contain any node signatures';\n }\n}\n\nexport class MalformedPublicKeyErrorCode extends ErrorCode {\n public name = 'MalformedPublicKeyErrorCode';\n\n constructor() {\n super();\n Object.setPrototypeOf(this, MalformedPublicKeyErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return 'Read state response contained a malformed public key';\n }\n}\n\nexport class QuerySignatureVerificationFailedErrorCode extends ErrorCode {\n public name = 'QuerySignatureVerificationFailedErrorCode';\n\n constructor(public readonly nodeId: string) {\n super();\n Object.setPrototypeOf(this, QuerySignatureVerificationFailedErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Query signature verification failed. Node ID: ${this.nodeId}`;\n }\n}\n\nexport class UnexpectedErrorCode extends ErrorCode {\n public name = 'UnexpectedErrorCode';\n\n constructor(public readonly error: unknown) {\n super();\n Object.setPrototypeOf(this, UnexpectedErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Unexpected error: ${formatUnknownError(this.error)}`;\n }\n}\n\nexport class HashTreeDecodeErrorCode extends ErrorCode {\n public name = 'HashTreeDecodeErrorCode';\n\n constructor(public readonly error: string) {\n super();\n Object.setPrototypeOf(this, HashTreeDecodeErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Failed to decode certificate: ${this.error}`;\n }\n}\n\nexport class HttpErrorCode extends ErrorCode {\n public name = 'HttpErrorCode';\n\n constructor(\n public readonly status: number,\n public readonly statusText: string,\n public readonly headers: HttpHeaderField[],\n public readonly bodyText?: string,\n ) {\n super();\n Object.setPrototypeOf(this, HttpErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n let errorMessage =\n 'HTTP request failed:\\n' +\n ` Status: ${this.status} (${this.statusText})\\n` +\n ` Headers: ${JSON.stringify(this.headers)}\\n`;\n if (this.bodyText) {\n errorMessage += ` Body: ${this.bodyText}\\n`;\n }\n return errorMessage;\n }\n}\n\nexport class HttpV4ApiNotSupportedErrorCode extends ErrorCode {\n public name = 'HttpV4ApiNotSupportedErrorCode';\n\n constructor() {\n super();\n Object.setPrototypeOf(this, HttpV4ApiNotSupportedErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return 'HTTP request failed: v4 API is not supported';\n }\n}\n\nexport class HttpFetchErrorCode extends ErrorCode {\n public name = 'HttpFetchErrorCode';\n\n constructor(public readonly error: unknown) {\n super();\n Object.setPrototypeOf(this, HttpFetchErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Failed to fetch HTTP request: ${formatUnknownError(this.error)}`;\n }\n}\n\nexport class MissingCanisterIdErrorCode extends ErrorCode {\n public name = 'MissingCanisterIdErrorCode';\n\n constructor(public readonly receivedCanisterId: unknown) {\n super();\n Object.setPrototypeOf(this, MissingCanisterIdErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Canister ID is required, but received ${typeof this.receivedCanisterId} instead. If you are using automatically generated declarations, this may be because your application is not setting the canister ID in process.env correctly.`;\n }\n}\n\nexport class InvalidReadStateRequestErrorCode extends ErrorCode {\n public name = 'InvalidReadStateRequestErrorCode';\n\n constructor(public readonly request: unknown) {\n super();\n Object.setPrototypeOf(this, InvalidReadStateRequestErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Invalid read state request: ${this.request}`;\n }\n}\n\nexport class ExpiryJsonDeserializeErrorCode extends ErrorCode {\n public name = 'ExpiryJsonDeserializeErrorCode';\n\n constructor(public readonly error: string) {\n super();\n Object.setPrototypeOf(this, ExpiryJsonDeserializeErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Failed to deserialize expiry: ${this.error}`;\n }\n}\n\nexport class InvalidRootKeyErrorCode extends ErrorCode {\n public name = 'InvalidRootKeyErrorCode';\n\n constructor(\n public readonly rootKey: Uint8Array,\n public readonly expectedLength: number,\n ) {\n super();\n Object.setPrototypeOf(this, InvalidRootKeyErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Invalid root key. Expected length: ${this.expectedLength}, actual length: ${this.rootKey.length}`;\n }\n}\n\nexport class MissingCookieErrorCode extends ErrorCode {\n public name = 'MissingCookieErrorCode';\n\n constructor(public readonly expectedCookieName: string) {\n super();\n Object.setPrototypeOf(this, MissingCookieErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Cookie '${this.expectedCookieName}' not found`;\n }\n}\n\nexport class EmptyCookieErrorCode extends ErrorCode {\n public name = 'EmptyCookieErrorCode';\n\n constructor(public readonly expectedCookieName: string) {\n super();\n Object.setPrototypeOf(this, EmptyCookieErrorCode.prototype);\n }\n\n public toErrorMessage(): string {\n return `Cookie '${this.expectedCookieName}' is empty`;\n }\n}\n\nfunction formatUnknownError(error: unknown): string {\n if (error instanceof Error) {\n return error.stack ?? error.message;\n }\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n}\n\n/**\n * Special error used to indicate that a code path is unreachable.\n *\n * For internal use only.\n */\nexport const UNREACHABLE_ERROR = new Error('unreachable');\n", "/**\n * Concatenate multiple Uint8Arrays.\n * @param uint8Arrays The Uint8Arrays to concatenate.\n */\nexport function concat(...uint8Arrays: Uint8Array[]): Uint8Array {\n const result = new Uint8Array(uint8Arrays.reduce((acc, curr) => acc + curr.byteLength, 0));\n let index = 0;\n for (const b of uint8Arrays) {\n result.set(b, index);\n index += b.byteLength;\n }\n return result;\n}\n\n/**\n * A class that abstracts a pipe-like Uint8Array.\n */\nexport class PipeArrayBuffer {\n /**\n * The reading view. It's a sliding window as we read and write, pointing to the buffer.\n * @private\n */\n private _view: Uint8Array;\n\n /**\n * Save a checkpoint of the reading view (for backtracking)\n */\n public save(): Uint8Array {\n return this._view;\n }\n\n /**\n * Restore a checkpoint of the reading view (for backtracking)\n * @param checkPoint a previously saved checkpoint\n */\n public restore(checkPoint: Uint8Array) {\n if (!(checkPoint instanceof Uint8Array)) {\n throw new Error('Checkpoint must be a Uint8Array');\n }\n this._view = checkPoint;\n }\n\n /**\n * The actual buffer containing the bytes.\n * @private\n */\n private _buffer: Uint8Array;\n\n /**\n * Creates a new instance of a pipe\n * @param buffer an optional buffer to start with\n * @param length an optional amount of bytes to use for the length.\n */\n constructor(buffer?: Uint8Array, length = buffer?.byteLength || 0) {\n if (buffer && !(buffer instanceof Uint8Array)) {\n try {\n buffer = uint8FromBufLike(buffer);\n } catch {\n throw new Error('Buffer must be a Uint8Array');\n }\n }\n if (length < 0 || !Number.isInteger(length)) {\n throw new Error('Length must be a non-negative integer');\n }\n if (buffer && length > buffer.byteLength) {\n throw new Error('Length cannot exceed buffer length');\n }\n this._buffer = buffer || new Uint8Array(0);\n this._view = new Uint8Array(this._buffer.buffer, 0, length);\n }\n\n get buffer(): Uint8Array {\n // Return a copy of the buffer.\n return this._view.slice();\n }\n\n get byteLength(): number {\n return this._view.byteLength;\n }\n\n /**\n * Read `num` number of bytes from the front of the pipe.\n * @param num The number of bytes to read.\n */\n public read(num: number): Uint8Array {\n const result = this._view.subarray(0, num);\n this._view = this._view.subarray(num);\n return result.slice();\n }\n\n public readUint8(): number | undefined {\n if (this._view.byteLength === 0) {\n return undefined;\n }\n const result = this._view[0];\n this._view = this._view.subarray(1);\n return result;\n }\n\n /**\n * Write a buffer to the end of the pipe.\n * @param buf The bytes to write.\n */\n public write(buf: Uint8Array): void {\n if (!(buf instanceof Uint8Array)) {\n throw new Error('Buffer must be a Uint8Array');\n }\n const offset = this._view.byteLength;\n if (this._view.byteOffset + this._view.byteLength + buf.byteLength >= this._buffer.byteLength) {\n // Alloc grow the view to include the new bytes.\n this.alloc(buf.byteLength);\n } else {\n // Update the view to include the new bytes.\n this._view = new Uint8Array(\n this._buffer.buffer,\n this._view.byteOffset,\n this._view.byteLength + buf.byteLength,\n );\n }\n\n this._view.set(buf, offset);\n }\n\n /**\n * Whether or not there is more data to read from the buffer\n */\n public get end(): boolean {\n return this._view.byteLength === 0;\n }\n\n /**\n * Allocate a fixed amount of memory in the buffer. This does not affect the view.\n * @param amount A number of bytes to add to the buffer.\n */\n public alloc(amount: number) {\n if (amount <= 0 || !Number.isInteger(amount)) {\n throw new Error('Amount must be a positive integer');\n }\n // Add a little bit of exponential growth.\n const b = new Uint8Array(((this._buffer.byteLength + amount) * 1.2) | 0);\n const v = new Uint8Array(b.buffer, 0, this._view.byteLength + amount);\n v.set(this._view);\n this._buffer = b;\n this._view = v;\n }\n}\n\n/**\n * Returns a true Uint8Array from an ArrayBufferLike object.\n * @param bufLike a buffer-like object\n * @returns Uint8Array\n */\nexport function uint8FromBufLike(\n bufLike:\n | ArrayBuffer\n | Uint8Array\n | DataView\n | ArrayBufferView\n | ArrayBufferLike\n | [number]\n | number[]\n | { buffer: ArrayBuffer },\n): Uint8Array {\n if (!bufLike) {\n throw new Error('Input cannot be null or undefined');\n }\n\n if (bufLike instanceof Uint8Array) {\n return bufLike;\n }\n if (bufLike instanceof ArrayBuffer) {\n return new Uint8Array(bufLike);\n }\n if (Array.isArray(bufLike)) {\n return new Uint8Array(bufLike);\n }\n if ('buffer' in bufLike) {\n return uint8FromBufLike(bufLike.buffer);\n }\n return new Uint8Array(bufLike);\n}\n\n/**\n *\n * @param u1 uint8Array 1\n * @param u2 uint8Array 2\n * @returns number - negative if u1 < u2, positive if u1 > u2, 0 if u1 === u2\n */\nexport function compare(u1: Uint8Array, u2: Uint8Array): number {\n if (u1.byteLength !== u2.byteLength) {\n return u1.byteLength - u2.byteLength;\n }\n for (let i = 0; i < u1.length; i++) {\n if (u1[i] !== u2[i]) {\n return u1[i] - u2[i];\n }\n }\n return 0;\n}\n\n/**\n * Checks two uint8Arrays for equality.\n * @param u1 uint8Array 1\n * @param u2 uint8Array 2\n * @returns boolean\n */\nexport function uint8Equals(u1: Uint8Array, u2: Uint8Array): boolean {\n return compare(u1, u2) === 0;\n}\n\n/**\n * Helpers to convert a Uint8Array to a DataView.\n * @param uint8 Uint8Array\n * @returns DataView\n */\nexport function uint8ToDataView(uint8: Uint8Array): DataView {\n if (!(uint8 instanceof Uint8Array)) {\n throw new Error('Input must be a Uint8Array');\n }\n return new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);\n}\n", "/**\n * Equivalent to `Math.log2(n)` with support for `BigInt` values\n * @param n bigint or integer\n * @returns integer\n */\nexport function ilog2(n: bigint | number): number {\n const nBig = BigInt(n);\n if (n <= 0) {\n throw new RangeError('Input must be positive');\n }\n return nBig.toString(2).length - 1;\n}\n\n/**\n * Equivalent to `2 ** n` with support for `BigInt` values\n * (necessary for browser preprocessors which replace the `**` operator with `Math.pow`)\n * @param n bigint or integer\n * @returns bigint\n */\nexport function iexp2(n: bigint | number): bigint {\n const nBig = BigInt(n);\n if (n < 0) {\n throw new RangeError('Input must be non-negative');\n }\n return BigInt(1) << nBig;\n}\n", "// Note: this file uses buffer-pipe, which on Node only, uses the Node Buffer\n// implementation, which isn't compatible with the NPM buffer package\n// which we use everywhere else. This means that we have to transform\n// one into the other, hence why every function that returns a Buffer\n// actually return `new Buffer(pipe.buffer)`.\n// TODO: The best solution would be to have our own buffer type around\n// Uint8Array which is standard.\nimport { PipeArrayBuffer as Pipe } from './buffer.ts';\nimport { ilog2 } from './bigint-math.ts';\n\nfunction eob(): never {\n throw new Error('unexpected end of buffer');\n}\n\n/**\n *\n * @param pipe Pipe from buffer-pipe\n * @param num number\n * @returns Uint8Array\n */\nexport function safeRead(pipe: Pipe, num: number): Uint8Array {\n if (pipe.byteLength < num) {\n eob();\n }\n return pipe.read(num);\n}\n\n/**\n * @param pipe - PipeArrayBuffer simulating buffer-pipe api\n */\nexport function safeReadUint8(pipe: Pipe): number {\n const byte = pipe.readUint8();\n if (byte === undefined) {\n eob();\n }\n return byte;\n}\n\n/**\n * Encode a positive number (or bigint) into a Buffer. The number will be floored to the\n * nearest integer.\n * @param value The number to encode.\n */\nexport function lebEncode(value: bigint | number): Uint8Array {\n if (typeof value === 'number') {\n value = BigInt(value);\n }\n\n if (value < BigInt(0)) {\n throw new Error('Cannot leb encode negative values.');\n }\n\n const byteLength = (value === BigInt(0) ? 0 : ilog2(value)) + 1;\n const pipe = new Pipe(new Uint8Array(byteLength), 0);\n while (true) {\n const i = Number(value & BigInt(0x7f));\n value /= BigInt(0x80);\n if (value === BigInt(0)) {\n pipe.write(new Uint8Array([i]));\n break;\n } else {\n pipe.write(new Uint8Array([i | 0x80]));\n }\n }\n\n return pipe.buffer;\n}\n\n/**\n * Decode a leb encoded buffer into a bigint. The number will always be positive (does not\n * support signed leb encoding).\n * @param pipe A Buffer containing the leb encoded bits.\n */\nexport function lebDecode(pipe: Pipe): bigint {\n let weight = BigInt(1);\n let value = BigInt(0);\n let byte;\n\n do {\n byte = safeReadUint8(pipe);\n value += BigInt(byte & 0x7f).valueOf() * weight;\n weight *= BigInt(128);\n } while (byte >= 0x80);\n\n return value;\n}\n\n/**\n * Encode a number (or bigint) into a Buffer, with support for negative numbers. The number\n * will be floored to the nearest integer.\n * @param value The number to encode.\n */\nexport function slebEncode(value: bigint | number): Uint8Array {\n if (typeof value === 'number') {\n value = BigInt(value);\n }\n\n const isNeg = value < BigInt(0);\n if (isNeg) {\n value = -value - BigInt(1);\n }\n const byteLength = (value === BigInt(0) ? 0 : ilog2(value)) + 1;\n const pipe = new Pipe(new Uint8Array(byteLength), 0);\n while (true) {\n const i = getLowerBytes(value);\n value /= BigInt(0x80);\n\n // prettier-ignore\n if ( ( isNeg && value === BigInt(0) && (i & 0x40) !== 0)\n || (!isNeg && value === BigInt(0) && (i & 0x40) === 0)) {\n pipe.write(new Uint8Array([i]));\n break;\n } else {\n pipe.write(new Uint8Array([i | 0x80]));\n }\n }\n\n function getLowerBytes(num: bigint): number {\n const bytes = num % BigInt(0x80);\n if (isNeg) {\n // We swap the bits here again, and remove 1 to do two's complement.\n return Number(BigInt(0x80) - bytes - BigInt(1));\n } else {\n return Number(bytes);\n }\n }\n return pipe.buffer;\n}\n\n/**\n * Decode a leb encoded buffer into a bigint. The number is decoded with support for negative\n * signed-leb encoding.\n * @param pipe A Buffer containing the signed leb encoded bits.\n */\nexport function slebDecode(pipe: Pipe): bigint {\n // Get the size of the buffer, then cut a buffer of that size.\n const pipeView = new Uint8Array(pipe.buffer);\n let len = 0;\n for (; len < pipeView.byteLength; len++) {\n if (pipeView[len] < 0x80) {\n // If it's a positive number, we reuse lebDecode.\n if ((pipeView[len] & 0x40) === 0) {\n return lebDecode(pipe);\n }\n break;\n }\n }\n\n const bytes = new Uint8Array(safeRead(pipe, len + 1));\n let value = BigInt(0);\n for (let i = bytes.byteLength - 1; i >= 0; i--) {\n value = value * BigInt(0x80) + BigInt(0x80 - (bytes[i] & 0x7f) - 1);\n }\n return -value - BigInt(1);\n}\n\n/**\n *\n * @param value bigint or number\n * @param byteLength number\n * @returns Uint8Array\n */\nexport function writeUIntLE(value: bigint | number, byteLength: number): Uint8Array {\n if (BigInt(value) < BigInt(0)) {\n throw new Error('Cannot write negative values.');\n }\n return writeIntLE(value, byteLength);\n}\n\n/**\n *\n * @param value - bigint or number\n * @param byteLength - number\n * @returns Uint8Array\n */\nexport function writeIntLE(value: bigint | number, byteLength: number): Uint8Array {\n value = BigInt(value);\n\n const pipe = new Pipe(new Uint8Array(Math.min(1, byteLength)), 0);\n let i = 0;\n let mul = BigInt(256);\n let sub = BigInt(0);\n let byte = Number(value % mul);\n pipe.write(new Uint8Array([byte]));\n while (++i < byteLength) {\n if (value < 0 && sub === BigInt(0) && byte !== 0) {\n sub = BigInt(1);\n }\n byte = Number((value / mul - sub) % BigInt(256));\n pipe.write(new Uint8Array([byte]));\n mul *= BigInt(256);\n }\n\n return pipe.buffer;\n}\n\n/**\n *\n * @param pipe Pipe from buffer-pipe\n * @param byteLength number\n * @returns bigint\n */\nexport function readUIntLE(pipe: Pipe, byteLength: number): bigint {\n if (byteLength <= 0 || !Number.isInteger(byteLength)) {\n throw new Error('Byte length must be a positive integer');\n }\n let val = BigInt(safeReadUint8(pipe));\n let mul = BigInt(1);\n let i = 0;\n while (++i < byteLength) {\n mul *= BigInt(256);\n const byte = BigInt(safeReadUint8(pipe));\n val = val + mul * byte;\n }\n return val;\n}\n\n/**\n *\n * @param pipe Pipe from buffer-pipe\n * @param byteLength number\n * @returns bigint\n */\nexport function readIntLE(pipe: Pipe, byteLength: number): bigint {\n if (byteLength <= 0 || !Number.isInteger(byteLength)) {\n throw new Error('Byte length must be a positive integer');\n }\n let val = readUIntLE(pipe, byteLength);\n const mul = BigInt(2) ** (BigInt(8) * BigInt(byteLength - 1) + BigInt(7));\n if (val >= mul) {\n val -= mul * BigInt(2);\n }\n return val;\n}\n", "/**\n * Returns a true Uint8Array from an ArrayBufferLike object.\n * @param bufLike a buffer-like object\n * @returns Uint8Array\n */\nexport function uint8FromBufLike(\n bufLike:\n | ArrayBuffer\n | Uint8Array\n | DataView\n | ArrayBufferView\n | ArrayBufferLike\n | [number]\n | number[]\n | { buffer: ArrayBuffer },\n): Uint8Array {\n if (!bufLike) {\n throw new Error('Input cannot be null or undefined');\n }\n\n if (bufLike instanceof Uint8Array) {\n return bufLike;\n }\n if (bufLike instanceof ArrayBuffer) {\n return new Uint8Array(bufLike);\n }\n if (Array.isArray(bufLike)) {\n return new Uint8Array(bufLike);\n }\n if ('buffer' in bufLike) {\n return uint8FromBufLike(bufLike.buffer);\n }\n return new Uint8Array(bufLike);\n}\n\n/**\n * Returns a true ArrayBuffer from a Uint8Array, as Uint8Array.buffer is unsafe.\n * @param {Uint8Array} arr Uint8Array to convert\n * @returns ArrayBuffer\n */\nexport function uint8ToBuf(arr: Uint8Array): ArrayBuffer {\n const buf = new ArrayBuffer(arr.byteLength);\n const view = new Uint8Array(buf);\n view.set(arr);\n return buf;\n}\n\n/**\n * Compares two Uint8Arrays for equality.\n * @param a The first Uint8Array.\n * @param b The second Uint8Array.\n * @returns True if the Uint8Arrays are equal, false otherwise.\n */\nexport function uint8Equals(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", "import { lebEncode, compare } from '#candid';\nimport { Principal } from '#principal';\nimport { HashValueErrorCode, InputError } from './errors.ts';\nimport { uint8FromBufLike } from './utils/buffer.ts';\nimport { concatBytes } from '@noble/hashes/utils';\nimport { sha256 } from '@noble/hashes/sha2';\n\nexport type RequestId = Uint8Array & { __requestId__: void };\n\ninterface ToHashable {\n toHash(): unknown;\n}\n\n/**\n *\n * @param value unknown value\n * @returns Uint8Array\n */\nexport function hashValue(value: unknown): Uint8Array {\n if (typeof value === 'string') {\n return hashString(value);\n } else if (typeof value === 'number') {\n return sha256(lebEncode(value));\n } else if (value instanceof Uint8Array || ArrayBuffer.isView(value)) {\n return sha256(uint8FromBufLike(value));\n } else if (Array.isArray(value)) {\n const vals = value.map(hashValue);\n return sha256(concatBytes(...vals));\n } else if (value && typeof value === 'object' && (value as Principal)._isPrincipal) {\n return sha256((value as Principal).toUint8Array());\n } else if (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as ToHashable).toHash === 'function'\n ) {\n return hashValue((value as ToHashable).toHash());\n // TODO This should be move to a specific async method as the webauthn flow required\n // the flow to be synchronous to ensure Safari touch id works.\n // } else if (value instanceof Promise) {\n // return value.then(x => hashValue(x));\n } else if (typeof value === 'object') {\n return hashOfMap(value as Record<string, unknown>);\n } else if (typeof value === 'bigint') {\n // Do this check much later than the other bigint check because this one is much less\n // type-safe.\n // So we want to try all the high-assurance type guards before this 'probable' one.\n return sha256(lebEncode(value));\n }\n throw InputError.fromCode(new HashValueErrorCode(value));\n}\n\nconst hashString = (value: string): Uint8Array => {\n const encoded = new TextEncoder().encode(value);\n return sha256(encoded);\n};\n\n/**\n * Get the RequestId of the provided ic-ref request.\n * RequestId is the result of the representation-independent-hash function.\n * https://sdk.dfinity.org/docs/interface-spec/index.html#hash-of-map\n * @param request - ic-ref request to hash into RequestId\n */\nexport function requestIdOf(request: Record<string, unknown>): RequestId {\n return hashOfMap(request) as RequestId;\n}\n\n/**\n * Hash a map into a Uint8Array using the representation-independent-hash function.\n * https://sdk.dfinity.org/docs/interface-spec/index.html#hash-of-map\n * @param map - Any non-nested object\n * @returns Uint8Array\n */\nexport function hashOfMap(map: Record<string, unknown>): Uint8Array {\n const hashed: Array<[Uint8Array, Uint8Array]> = Object.entries(map)\n .filter(([, value]) => value !== undefined)\n .map(([key, value]: [string, unknown]) => {\n const hashedKey = hashString(key);\n const hashedValue = hashValue(value);\n\n return [hashedKey, hashedValue] as [Uint8Array, Uint8Array];\n });\n\n const traversed: Array<[Uint8Array, Uint8Array]> = hashed;\n\n const sorted: Array<[Uint8Array, Uint8Array]> = traversed.sort(([k1], [k2]) => {\n return compare(k1, k2);\n });\n\n const concatenated = concatBytes(...sorted.map(x => concatBytes(...x)));\n const result = sha256(concatenated);\n return result;\n}\n", "// Default delta for ingress expiry is 5 minutes.\nexport const DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS = 5 * 60 * 1000;\n\n/**\n * The `\\x0Dic-state-root` domain separator used in the root hash of IC certificates.\n */\nexport const IC_STATE_ROOT_DOMAIN_SEPARATOR = new TextEncoder().encode('\\x0Dic-state-root');\n\n/**\n * The `\\x0Aic-request` domain separator used in the signature of IC requests.\n */\nexport const IC_REQUEST_DOMAIN_SEPARATOR = new TextEncoder().encode('\\x0Aic-request');\n\n/**\n * The `\\x0Bic-response` domain separator used in the signature of IC responses.\n */\nexport const IC_RESPONSE_DOMAIN_SEPARATOR = new TextEncoder().encode('\\x0Bic-response');\n\n/**\n * The `\\x1Aic-request-auth-delegation` domain separator used in the signature of delegations.\n */\nexport const IC_REQUEST_AUTH_DELEGATION_DOMAIN_SEPARATOR = new TextEncoder().encode(\n '\\x1Aic-request-auth-delegation',\n);\n", "import { Principal } from '#principal';\nimport { type HttpAgentRequest } from './agent/http/types.ts';\nimport { requestIdOf } from './request_id.ts';\nimport { bytesToHex, concatBytes } from '@noble/hashes/utils';\nimport { IC_REQUEST_DOMAIN_SEPARATOR } from './constants.ts';\n/**\n * A Key Pair, containing a secret and public key.\n */\nexport interface KeyPair {\n secretKey: Uint8Array;\n publicKey: PublicKey;\n}\n\n/**\n * A public key that is DER encoded. This is a branded Uint8Array.\n */\nexport type DerEncodedPublicKey = Uint8Array & { __derEncodedPublicKey__?: void };\n\n/**\n * A signature array buffer.\n */\nexport type Signature = Uint8Array & { __signature__: void };\n\n/**\n * A Public Key implementation.\n */\nexport interface PublicKey {\n toDer(): DerEncodedPublicKey;\n // rawKey, toRaw, and derKey are optional for backwards compatibility.\n toRaw?(): Uint8Array;\n rawKey?: Uint8Array;\n derKey?: DerEncodedPublicKey;\n}\n\n/**\n * A General Identity object. This does not have to be a private key (for example,\n * the Anonymous identity), but it must be able to transform request.\n */\nexport interface Identity {\n /**\n * Get the principal represented by this identity. Normally should be a\n * `Principal.selfAuthenticating()`.\n */\n getPrincipal(): Principal;\n\n /**\n * Transform a request into a signed version of the request. This is done last\n * after the transforms on the body of a request. The returned object can be\n * anything, but must be serializable to CBOR.\n */\n transformRequest(request: HttpAgentRequest): Promise<unknown>;\n}\n\n/**\n * An Identity that can sign blobs.\n */\nexport abstract class SignIdentity implements Identity {\n protected _principal: Principal | undefined;\n\n /**\n * Returns the public key that would match this identity's signature.\n */\n public abstract getPublicKey(): PublicKey;\n\n /**\n * Signs a blob of data, with this identity's private key.\n */\n public abstract sign(blob: Uint8Array): Promise<Signature>;\n\n /**\n * Get the principal represented by this identity. Normally should be a\n * `Principal.selfAuthenticating()`.\n */\n public getPrincipal(): Principal {\n if (!this._principal) {\n this._principal = Principal.selfAuthenticating(new Uint8Array(this.getPublicKey().toDer()));\n }\n return this._principal;\n }\n\n /**\n * Transform a request into a signed version of the request. This is done last\n * after the transforms on the body of a request. The returned object can be\n * anything, but must be serializable to CBOR.\n * @param request - internet computer request to transform\n */\n public async transformRequest(request: HttpAgentRequest): Promise<unknown> {\n const { body, ...fields } = request;\n const requestId = requestIdOf(body);\n return {\n ...fields,\n body: {\n content: body,\n sender_pubkey: this.getPublicKey().toDer(),\n sender_sig: await this.sign(concatBytes(IC_REQUEST_DOMAIN_SEPARATOR, requestId)),\n },\n };\n }\n}\n\nexport class AnonymousIdentity implements Identity {\n public getPrincipal(): Principal {\n return Principal.anonymous();\n }\n\n public async transformRequest(request: HttpAgentRequest): Promise<unknown> {\n return {\n ...request,\n body: { content: request.body },\n };\n }\n}\n\n/*\n * We need to communicate with other agents on the page about identities,\n * but those messages may need to go across boundaries where it's not possible to\n * serialize/deserialize object prototypes easily.\n * So these are lightweight, serializable objects that contain enough information to recreate\n * SignIdentities, but don't commit to having all methods of SignIdentity.\n *\n * Use Case:\n * * DOM Events that let differently-versioned components communicate to one another about\n * Identities, even if they're using slightly different versions of agent packages to\n * create/interpret them.\n */\nexport interface AnonymousIdentityDescriptor {\n type: 'AnonymousIdentity';\n}\nexport interface PublicKeyIdentityDescriptor {\n type: 'PublicKeyIdentity';\n publicKey: string;\n}\nexport type IdentityDescriptor = AnonymousIdentityDescriptor | PublicKeyIdentityDescriptor;\n\n/**\n * Create an IdentityDescriptor from an Identity\n * @param identity - identity describe in returned descriptor\n */\nexport function createIdentityDescriptor(\n identity: SignIdentity | AnonymousIdentity,\n): IdentityDescriptor {\n const identityIndicator: IdentityDescriptor =\n 'getPublicKey' in identity\n ? { type: 'PublicKeyIdentity', publicKey: bytesToHex(identity.getPublicKey().toDer()) }\n : { type: 'AnonymousIdentity' };\n return identityIndicator;\n}\n", "/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes as abytes_,\n bytesToHex as bytesToHex_,\n concatBytes as concatBytes_,\n hexToBytes as hexToBytes_,\n isBytes as isBytes_,\n} from '@noble/hashes/utils.js';\nexport {\n abytes,\n anumber,\n bytesToHex,\n bytesToUtf8,\n concatBytes,\n hexToBytes,\n isBytes,\n randomBytes,\n utf8ToBytes,\n} from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n (message: Uint8Array | string): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nexport function abool(title: string, value: boolean): void {\n if (typeof value !== 'boolean') throw new Error(title + ' boolean expected, got ' + value);\n}\n\n// tmp name until v2\nexport function _abool2(value: boolean, title: string = ''): boolean {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\"`;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n\n// tmp name until v2\n/** Asserts something is Uint8Array. */\nexport function _abytes2(value: Uint8Array, length?: number, title: string = ''): Uint8Array {\n const bytes = isBytes_(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n\n// Used in weierstrass, der\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = num.toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex_(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n abytes_(bytes);\n return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes_(numberToHexUnpadded(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'secret key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n let res: Uint8Array;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes_(hex);\n } catch (e) {\n throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n }\n } else if (isBytes_(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n } else {\n throw new Error(title + ' must be hex string or Uint8Array');\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n return res;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes: Uint8Array): Uint8Array {\n return Uint8Array.from(bytes);\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as utf8ToBytes for ASCII or throws.\n */\nexport function asciiToBytes(ascii: string): Uint8Array {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(\n `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n );\n }\n return charCode;\n });\n}\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\n// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\n// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;\n\n// Is positive bigint\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\nexport function inRange(n: bigint, min: bigint, max: bigint): boolean {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number): bigint {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n: bigint, pos: number, value: boolean): bigint {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\ntype Pred<T> = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG<Key>(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg<T>(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred<T>) => T {\n if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n const u8n = (len: number) => new Uint8Array(len); // creates Uint8Array\n const u8of = (byte: number) => Uint8Array.of(byte); // another shortcut\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n(0)) => {\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) return;\n k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000) throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes_(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred<T>): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\n// Validating curves and fields\n\nconst validatorFns = {\n bigint: (val: any): boolean => typeof val === 'bigint',\n function: (val: any): boolean => typeof val === 'function',\n boolean: (val: any): boolean => typeof val === 'boolean',\n string: (val: any): boolean => typeof val === 'string',\n stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes_(val),\n isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),\n array: (val: any): boolean => Array.isArray(val),\n field: (val: any, object: any): any => (object as any).Fp.isValid(val),\n hash: (val: any): boolean => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap<T extends Record<string, any>> = { [K in keyof T]?: Validator };\n// type Record<K extends string | number | symbol, T> = { [P in K]: T; }\n\nexport function validateObject<T extends Record<string, any>>(\n object: T,\n validators: ValMap<T>,\n optValidators: ValMap<T> = {}\n): T {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function') throw new Error('invalid validator function');\n\n const val = object[fieldName as keyof typeof object];\n if (isOptional && val === undefined) return;\n if (!checkVal(val, object)) {\n throw new Error(\n 'param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val\n );\n }\n };\n for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n\nexport function isHash(val: CHash): boolean {\n return typeof val === 'function' && Number.isSafeInteger(val.outputLen);\n}\nexport function _validateObject(\n object: Record<string, any>,\n fields: Record<string, string>,\n optFields: Record<string, string> = {}\n): void {\n if (!object || typeof object !== 'object') throw new Error('expected valid options object');\n type Item = keyof typeof object;\n function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n const val = object[fieldName];\n if (isOpt && val === undefined) return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));\n Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));\n}\n\n/**\n * throws not implemented error\n */\nexport const notImplemented = (): never => {\n throw new Error('not implemented');\n};\n\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized<T extends object, R, O extends any[]>(\n fn: (arg: T, ...args: O) => R\n): (arg: T, ...args: O) => R {\n const map = new WeakMap<T, R>();\n return (arg: T, ...args: O): R => {\n const val = map.get(arg);\n if (val !== undefined) return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n", "/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n _validateObject,\n anumber,\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n} from '../utils.ts';\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);\n// prettier-ignore\nconst _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\n}\n\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n) throw new Error('invert: expected non-zero number');\n if (modulo <= _0n) throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\nfunction assertIsSquare<T>(Fp: IField<T>, root: T, n: T): void {\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n}\n\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4<T>(Fp: IField<T>, n: T) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\n const root = Fp.pow(n, p1div4);\n assertIsSquare(Fp, root, n);\n return root;\n}\n\nfunction sqrt5mod8<T>(Fp: IField<T>, n: T) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n assertIsSquare(Fp, root, n);\n return root;\n}\n\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));// 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n return <T>(Fp: IField<T>, n: T) => {\n let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = Fp.eql(Fp.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = Fp.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = Fp.cmov(tv1, tv2, e3);// 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(Fp, root, n);\n return root;\n };\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow<T>(Fp: IField<T>, n: T): T {\n if (Fp.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) \u2261 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P \u2261 3 (mod 4)\n * 2. P \u2261 5 (mod 8)\n * 3. P \u2261 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nexport function FpSqrt(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // P \u2261 3 (mod 4) => \u221An = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P \u2261 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P \u2261 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n) return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint): boolean =>\n (mod(num, modulo) & _1n) === _1n;\n\n/** Field is not always over prime: for example, Fp2 has ORDER(q)=p^m. */\nexport interface IField<T> {\n ORDER: bigint;\n isLE: boolean;\n BYTES: number;\n BITS: number;\n MASK: bigint;\n ZERO: T;\n ONE: T;\n // 1-arg\n create: (num: T) => T;\n isValid: (num: T) => boolean;\n is0: (num: T) => boolean;\n isValidNot0: (num: T) => boolean;\n neg(num: T): T;\n inv(num: T): T;\n sqrt(num: T): T;\n sqr(num: T): T;\n // 2-args\n eql(lhs: T, rhs: T): boolean;\n add(lhs: T, rhs: T): T;\n sub(lhs: T, rhs: T): T;\n mul(lhs: T, rhs: T | bigint): T;\n pow(lhs: T, power: bigint): T;\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n addN(lhs: T, rhs: T): T;\n subN(lhs: T, rhs: T): T;\n mulN(lhs: T, rhs: T | bigint): T;\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.\n isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n allowedLengths?: number[];\n // legendre?(num: T): T;\n invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array, skipValidation?: boolean): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\nexport function validateField<T>(field: IField<T>): IField<T> {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n } as Record<string, string>;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n _validateObject(field, opts);\n // const max = 16384;\n // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');\n // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');\n return field;\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow<T>(Fp: IField<T>, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch<T>(Fp: IField<T>, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv<T>(Fp: IField<T>, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) \u2261 1 if a is a square (mod p), quadratic residue\n * * (a | p) \u2261 -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) \u2261 0 if a \u2261 0 (mod p)\n */\nexport function FpLegendre<T>(Fp: IField<T>, n: T): -1 | 0 | 1 {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare<T>(Fp: IField<T>, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n\nexport type NLength = { nByteLength: number; nBitLength: number };\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number): NLength {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;\ntype SqrtFn = (n: bigint) => bigint;\ntype FieldOpts = Partial<{\n sqrt: SqrtFn;\n isLE: boolean;\n BITS: number;\n modFromBytes: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n allowedLengths?: readonly number[]; // for P521 (adds padding for smaller sizes)\n}>;\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. `Object.freeze`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER field order, probably prime, or could be composite\n * @param bitLen how many bits the field consumes\n * @param isLE (default: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n ORDER: bigint,\n bitLenOrOpts?: number | FieldOpts, // TODO: use opts only in v2?\n isLE = false,\n opts: { sqrt?: SqrtFn } = {}\n): Readonly<FpField> {\n if (ORDER <= _0n) throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n let _nbitLength: number | undefined = undefined;\n let _sqrt: SqrtFn | undefined = undefined;\n let modFromBytes: boolean = false;\n let allowedLengths: undefined | readonly number[] = undefined;\n if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {\n if (opts.sqrt || isLE) throw new Error('cannot specify opts in two arguments');\n const _opts = bitLenOrOpts;\n if (_opts.BITS) _nbitLength = _opts.BITS;\n if (_opts.sqrt) _sqrt = _opts.sqrt;\n if (typeof _opts.isLE === 'boolean') isLE = _opts.isLE;\n if (typeof _opts.modFromBytes === 'boolean') modFromBytes = _opts.modFromBytes;\n allowedLengths = _opts.allowedLengths;\n } else {\n if (typeof bitLenOrOpts === 'number') _nbitLength = bitLenOrOpts;\n if (opts.sqrt) _sqrt = opts.sqrt;\n }\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);\n if (BYTES > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n let sqrtP: ReturnType<typeof FpSqrt>; // cached sqrtP\n const f: Readonly<FpField> = Object.freeze({\n ORDER,\n isLE,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n allowedLengths: allowedLengths,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n // is valid and invertible\n isValidNot0: (num: bigint) => !f.is0(num) && f.isValid(num),\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n\n inv: (num) => invert(num, ORDER),\n sqrt:\n _sqrt ||\n ((n) => {\n if (!sqrtP) sqrtP = FpSqrt(ORDER);\n return sqrtP(f, n);\n }),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes, skipValidation = true) => {\n if (allowedLengths) {\n if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error(\n 'Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length\n );\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes) scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!f.isValid(scalar)) throw new Error('invalid field element: outside of range 0..ORDER');\n // NOTE: we don't validate scalar here, please use isValid. This done such way because some\n // protocol may allow non-reduced scalar that reduced later or changed some other way.\n return scalar;\n },\n // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov: (a, b, c) => (c ? b : a),\n } as FpField);\n return Object.freeze(f);\n}\n\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\n\nexport function FpSqrtOdd<T>(Fp: IField<T>, elm: T): T {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven<T>(Fp: IField<T>, elm: T): T {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use `mapKeyToField` instead\n */\nexport function hashToPrivateScalar(\n hash: string | Uint8Array,\n groupOrder: bigint,\n isLE = false\n): bigint {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(\n 'hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen\n );\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n", "/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, validateObject } from '../utils.ts';\nimport { Field, FpInvertBatch, nLength, validateField, type IField } from './modular.ts';\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint<T> = {\n x: T;\n y: T;\n} & { Z?: never };\n\n// This was initialy do this way to re-use montgomery ladder in field (add->mul,double->sqr), but\n// that didn't happen and there is probably not much reason to have separate Group like this?\nexport interface Group<T extends Group<T>> {\n double(): T;\n negate(): T;\n add(other: T): T;\n subtract(other: T): T;\n equals(other: T): boolean;\n multiply(scalar: bigint): T;\n toAffine?(invertedZ?: any): AffinePoint<any>;\n}\n\n// We can't \"abstract out\" coordinates (X, Y, Z; and T in Edwards): argument names of constructor\n// are not accessible. See Typescript gh-56093, gh-41594.\n//\n// We have to use recursive types, so it will return actual point, not constained `CurvePoint`.\n// If, at any point, P is `any`, it will erase all types and replace it\n// with `any`, because of recursion, `any implements CurvePoint`,\n// but we lose all constrains on methods.\n\n/** Base interface for all elliptic curve Points. */\nexport interface CurvePoint<F, P extends CurvePoint<F, P>> extends Group<P> {\n /** Affine x coordinate. Different from projective / extended X coordinate. */\n x: F;\n /** Affine y coordinate. Different from projective / extended Y coordinate. */\n y: F;\n Z?: F;\n double(): P;\n negate(): P;\n add(other: P): P;\n subtract(other: P): P;\n equals(other: P): boolean;\n multiply(scalar: bigint): P;\n assertValidity(): void;\n clearCofactor(): P;\n is0(): boolean;\n isTorsionFree(): boolean;\n isSmallOrder(): boolean;\n multiplyUnsafe(scalar: bigint): P;\n /**\n * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}.\n * @param isLazy calculate cache now. Default (true) ensures it's deferred to first `multiply()`\n */\n precompute(windowSize?: number, isLazy?: boolean): P;\n /** Converts point to 2D xy affine coordinates */\n toAffine(invertedZ?: F): AffinePoint<F>;\n toBytes(): Uint8Array;\n toHex(): string;\n}\n\n/** Base interface for all elliptic curve Point constructors. */\nexport interface CurvePointCons<P extends CurvePoint<any, P>> {\n [Symbol.hasInstance]: (item: unknown) => boolean;\n BASE: P;\n ZERO: P;\n /** Field for basic curve math */\n Fp: IField<P_F<P>>;\n /** Scalar field, for scalars in multiply and others */\n Fn: IField<bigint>;\n /** Creates point from x, y. Does NOT validate if the point is valid. Use `.assertValidity()`. */\n fromAffine(p: AffinePoint<P_F<P>>): P;\n fromBytes(bytes: Uint8Array): P;\n fromHex(hex: Uint8Array | string): P;\n}\n\n// Type inference helpers: PC - PointConstructor, P - Point, Fp - Field element\n// Short names, because we use them a lot in result types:\n// * we can't do 'P = GetCurvePoint<PC>': this is default value and doesn't constrain anything\n// * we can't do 'type X = GetCurvePoint<PC>': it won't be accesible for arguments/return types\n// * `CurvePointCons<P extends CurvePoint<any, P>>` constraints from interface definition\n// won't propagate, if `PC extends CurvePointCons<any>`: the P would be 'any', which is incorrect\n// * PC could be super specific with super specific P, which implements CurvePoint<any, P>.\n// this means we need to do stuff like\n// `function test<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(`\n// if we want type safety around P, otherwise PC_P<PC> will be any\n\n/** Returns Fp type from Point (P_F<P> == P.F) */\nexport type P_F<P extends CurvePoint<any, P>> = P extends CurvePoint<infer F, P> ? F : never;\n/** Returns Fp type from PointCons (PC_F<PC> == PC.P.F) */\nexport type PC_F<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['Fp']['ZERO'];\n/** Returns Point type from PointCons (PC_P<PC> == PC.P) */\nexport type PC_P<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['ZERO'];\n\n// Ugly hack to get proper type inference, because in typescript fails to infer resursively.\n// The hack allows to do up to 10 chained operations without applying type erasure.\n//\n// Types which won't work:\n// * `CurvePointCons<CurvePoint<any, any>>`, will return `any` after 1 operation\n// * `CurvePointCons<any>: WeierstrassPointCons<bigint> extends CurvePointCons<any> = false`\n// * `P extends CurvePoint, PC extends CurvePointCons<P>`\n// * It can't infer P from PC alone\n// * Too many relations between F, P & PC\n// * It will infer P/F if `arg: CurvePointCons<F, P>`, but will fail if PC is generic\n// * It will work correctly if there is an additional argument of type P\n// * But generally, we don't want to parametrize `CurvePointCons` over `F`: it will complicate\n// types, making them un-inferable\n// prettier-ignore\nexport type PC_ANY = CurvePointCons<\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any, any>\n >>>>>>>>>\n>;\n\nexport interface CurveLengths {\n secretKey?: number;\n publicKey?: number;\n publicKeyUncompressed?: number;\n publicKeyHasPrefix?: boolean;\n signature?: number;\n seed?: number;\n}\nexport type GroupConstructor<T> = {\n BASE: T;\n ZERO: T;\n};\n/** @deprecated */\nexport type ExtendedGroupConstructor<T> = GroupConstructor<T> & {\n Fp: IField<any>;\n Fn: IField<bigint>;\n fromAffine(ap: AffinePoint<any>): T;\n};\nexport type Mapper<T> = (i: T[]) => T[];\n\nexport function negateCt<T extends { negate: () => T }>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\n}\n\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\nexport function normalizeZ<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[]\n): P[] {\n const invertedZs = FpInvertBatch(\n c.Fp,\n points.map((p) => p.Z!)\n );\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\n\nfunction validateW(W: number, bits: number) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\n\n/** Internal wNAF opts for specific W and scalarBits */\nexport type WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\n\nfunction validateMSMPoints(points: any[], c: any) {\n if (!Array.isArray(points)) throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c)) throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars: any[], field: any) {\n if (!Array.isArray(scalars)) throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s)) throw new Error('invalid scalar at index ' + i);\n });\n}\n\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap<any, any[]>();\nconst pointWindowSizes = new WeakMap<any, number>();\n\nfunction getW(P: any): number {\n // To disable precomputes:\n // return 1;\n return pointWindowSizes.get(P) || 1;\n}\n\nfunction assert0(n: bigint): void {\n if (n !== _0n) throw new Error('invalid wNAF');\n}\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / \uD835\uDC4A) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport class wNAF<PC extends PC_ANY> {\n private readonly BASE: PC_P<PC>;\n private readonly ZERO: PC_P<PC>;\n private readonly Fn: PC['Fn'];\n readonly bits: number;\n\n // Parametrized with a given Point class (not individual point)\n constructor(Point: PC, bits: number) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n\n // non-const time multiplication ladder\n _unsafeLadder(elm: PC_P<PC>, n: bigint, p: PC_P<PC> = this.ZERO): PC_P<PC> {\n let d: PC_P<PC> = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(\uD835\uDC4A\u22121) * (Math.ceil(\uD835\uDC5B / \uD835\uDC4A) + 1), where:\n * - \uD835\uDC4A is the window size\n * - \uD835\uDC5B is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param point Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n private precomputeWindow(point: PC_P<PC>, W: number): PC_P<PC>[] {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points: PC_P<PC>[] = [];\n let p: PC_P<PC> = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n private wNAF(W: number, precomputes: PC_P<PC>[], n: bigint): { p: PC_P<PC>; f: PC_P<PC> } {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n)) throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points: JIT won't eliminate f.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n }\n\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n private wNAFUnsafe(\n W: number,\n precomputes: PC_P<PC>[],\n n: bigint,\n acc: PC_P<PC> = this.ZERO\n ): PC_P<PC> {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n\n private getPrecomputes(W: number, point: PC_P<PC>, transform?: Mapper<PC_P<PC>>): PC_P<PC>[] {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W) as PC_P<PC>[];\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function') comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n\n cached(\n point: PC_P<PC>,\n scalar: bigint,\n transform?: Mapper<PC_P<PC>>\n ): { p: PC_P<PC>; f: PC_P<PC> } {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n\n unsafe(point: PC_P<PC>, scalar: bigint, transform?: Mapper<PC_P<PC>>, prev?: PC_P<PC>): PC_P<PC> {\n const W = getW(point);\n if (W === 1) return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n createCache(P: PC_P<PC>, W: number): void {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n\n hasCache(elm: PC_P<PC>): boolean {\n return getW(elm) !== 1;\n }\n}\n\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n */\nexport function mulEndoUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n Point: PC,\n point: P,\n k1: bigint,\n k2: bigint\n): { p1: P; p2: P } {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) p1 = p1.add(acc);\n if (k2 & _1n) p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\n}\n\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka secret keys / bigints)\n */\nexport function pippenger<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n fieldN: IField<bigint>,\n points: P[],\n scalars: bigint[]\n): P {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();\n }\n return sum as P;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n fieldN: IField<bigint>,\n points: P[],\n windowSize: number\n): (scalars: bigint[]) => P {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar \u00D7 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 \u00D7 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 \u00D7 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p: P) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars: bigint[]): P => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr) continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\n\n// TODO: remove\n/**\n * Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n * Though generator can be different (Fp2 / Fp6 for BLS).\n */\nexport type BasicCurve<T> = {\n Fp: IField<T>; // Field over which we'll do calculations (Fp)\n n: bigint; // Curve order, total count of valid points in the field\n nBitLength?: number; // bit length of curve order\n nByteLength?: number; // byte length of curve order\n h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n hEff?: bigint; // Number to multiply to clear cofactor\n Gx: T; // base point X coordinate\n Gy: T; // base point Y coordinate\n allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\n// TODO: remove\n/** @deprecated */\nexport function validateBasic<FP, T>(\n curve: BasicCurve<FP> & T\n): Readonly<\n {\n readonly nBitLength: number;\n readonly nByteLength: number;\n } & BasicCurve<FP> &\n T & {\n p: bigint;\n }\n> {\n validateField(curve.Fp);\n validateObject(\n curve,\n {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n },\n {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n }\n );\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n } as const);\n}\n\nexport type ValidCurveParams<T> = {\n p: bigint;\n n: bigint;\n h: bigint;\n a: T;\n b?: T;\n d?: T;\n Gx: T;\n Gy: T;\n};\n\nfunction createField<T>(order: bigint, field?: IField<T>, isLE?: boolean): IField<T> {\n if (field) {\n if (field.ORDER !== order) throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n } else {\n return Field(order, { isLE }) as unknown as IField<T>;\n }\n}\nexport type FpFn<T> = { Fp: IField<T>; Fn: IField<bigint> };\n\n/** Validates CURVE opts and creates fields */\nexport function _createCurveFields<T>(\n type: 'weierstrass' | 'edwards',\n CURVE: ValidCurveParams<T>,\n curveOpts: Partial<FpFn<T>> = {},\n FpFnLE?: boolean\n): FpFn<T> & { CURVE: ValidCurveParams<T> } {\n if (FpFnLE === undefined) FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object') throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h'] as const) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b: 'b' | 'd' = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b] as const;\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\n", "/**\n * Twisted Edwards curve. The formula is: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2.\n * For design rationale of types / exports, see weierstrass module documentation.\n * Untwisted Edwards curves exist, but they aren't used in real-world protocols.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n _validateObject,\n _abool2 as abool,\n _abytes2 as abytes,\n aInRange,\n bytesToHex,\n bytesToNumberLE,\n concatBytes,\n copyBytes,\n ensureBytes,\n isBytes,\n memoized,\n notImplemented,\n randomBytes as randomBytesWeb,\n type FHash,\n type Hex,\n} from '../utils.ts';\nimport {\n _createCurveFields,\n normalizeZ,\n pippenger,\n wNAF,\n type AffinePoint,\n type BasicCurve,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport { Field, type IField, type NLength } from './modular.ts';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n\nexport type UVRatio = (u: bigint, v: bigint) => { isValid: boolean; value: bigint };\n\n/** Instance of Extended Point with coordinates in X, Y, Z, T. */\nexport interface EdwardsPoint extends CurvePoint<bigint, EdwardsPoint> {\n /** extended X coordinate. Different from affine x. */\n readonly X: bigint;\n /** extended Y coordinate. Different from affine y. */\n readonly Y: bigint;\n /** extended Z coordinate */\n readonly Z: bigint;\n /** extended T coordinate */\n readonly T: bigint;\n\n /** @deprecated use `toBytes` */\n toRawBytes(): Uint8Array;\n /** @deprecated use `p.precompute(windowSize)` */\n _setWindowSize(windowSize: number): void;\n /** @deprecated use .X */\n readonly ex: bigint;\n /** @deprecated use .Y */\n readonly ey: bigint;\n /** @deprecated use .Z */\n readonly ez: bigint;\n /** @deprecated use .T */\n readonly et: bigint;\n}\n/** Static methods of Extended Point with coordinates in X, Y, Z, T. */\nexport interface EdwardsPointCons extends CurvePointCons<EdwardsPoint> {\n new (X: bigint, Y: bigint, Z: bigint, T: bigint): EdwardsPoint;\n CURVE(): EdwardsOpts;\n fromBytes(bytes: Uint8Array, zip215?: boolean): EdwardsPoint;\n fromHex(hex: Hex, zip215?: boolean): EdwardsPoint;\n /** @deprecated use `import { pippenger } from '@noble/curves/abstract/curve.js';` */\n msm(points: EdwardsPoint[], scalars: bigint[]): EdwardsPoint;\n}\n/** @deprecated use EdwardsPoint */\nexport type ExtPointType = EdwardsPoint;\n/** @deprecated use EdwardsPointCons */\nexport type ExtPointConstructor = EdwardsPointCons;\n\n/**\n * Twisted Edwards curve options.\n *\n * * a: formula param\n * * d: formula param\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor. h*n is group order; n is subgroup order\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type EdwardsOpts = Readonly<{\n p: bigint;\n n: bigint;\n h: bigint;\n a: bigint;\n d: bigint;\n Gx: bigint;\n Gy: bigint;\n}>;\n\n/**\n * Extra curve options for Twisted Edwards.\n *\n * * Fp: redefined Field over curve.p\n * * Fn: redefined Field over curve.n\n * * uvRatio: helper function for decompression, calculating \u221A(u/v)\n */\nexport type EdwardsExtraOpts = Partial<{\n Fp: IField<bigint>;\n Fn: IField<bigint>;\n FpFnLE: boolean;\n uvRatio: (u: bigint, v: bigint) => { isValid: boolean; value: bigint };\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) options.\n *\n * * hash: hash function used to hash secret keys and messages\n * * adjustScalarBytes: clears bits to get valid field element\n * * domain: Used for hashing\n * * mapToCurve: for hash-to-curve standard\n * * prehash: RFC 8032 pre-hashing of messages to sign() / verify()\n * * randomBytes: function generating random bytes, used for randomSecretKey\n */\nexport type EdDSAOpts = Partial<{\n adjustScalarBytes: (bytes: Uint8Array) => Uint8Array;\n domain: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array;\n mapToCurve: (scalar: bigint[]) => AffinePoint<bigint>;\n prehash: FHash;\n randomBytes: (bytesLength?: number) => Uint8Array;\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) interface.\n *\n * Allows to create and verify signatures, create public and secret keys.\n */\nexport interface EdDSA {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Hex) => Uint8Array;\n sign: (message: Hex, secretKey: Hex, options?: { context?: Hex }) => Uint8Array;\n verify: (\n sig: Hex,\n message: Hex,\n publicKey: Hex,\n options?: { context?: Hex; zip215: boolean }\n ) => boolean;\n Point: EdwardsPointCons;\n utils: {\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n isValidSecretKey: (secretKey: Uint8Array) => boolean;\n isValidPublicKey: (publicKey: Uint8Array, zip215?: boolean) => boolean;\n\n /**\n * Converts ed public key to x public key.\n *\n * There is NO `fromMontgomery`:\n * - There are 2 valid ed25519 points for every x25519, with flipped coordinate\n * - Sometimes there are 0 valid ed25519 points, because x25519 *additionally*\n * accepts inputs on the quadratic twist, which can't be moved to ed25519\n *\n * @example\n * ```js\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomSecretKey());\n * const aPriv = x25519.utils.randomSecretKey();\n * x25519.getSharedSecret(aPriv, ed25519.utils.toMontgomery(someonesPub))\n * ```\n */\n toMontgomery: (publicKey: Uint8Array) => Uint8Array;\n /**\n * Converts ed secret key to x secret key.\n * @example\n * ```js\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomSecretKey());\n * const aPriv = ed25519.utils.randomSecretKey();\n * x25519.getSharedSecret(ed25519.utils.toMontgomerySecret(aPriv), someonesPub)\n * ```\n */\n toMontgomerySecret: (privateKey: Uint8Array) => Uint8Array;\n getExtendedPublicKey: (key: Hex) => {\n head: Uint8Array;\n prefix: Uint8Array;\n scalar: bigint;\n point: EdwardsPoint;\n pointBytes: Uint8Array;\n };\n\n /** @deprecated use `randomSecretKey` */\n randomPrivateKey: (seed?: Uint8Array) => Uint8Array;\n /** @deprecated use `point.precompute()` */\n precompute: (windowSize?: number, point?: EdwardsPoint) => EdwardsPoint;\n };\n lengths: CurveLengths;\n}\n\nfunction isEdValidXY(Fp: IField<bigint>, CURVE: EdwardsOpts, x: bigint, y: bigint): boolean {\n const x2 = Fp.sqr(x);\n const y2 = Fp.sqr(y);\n const left = Fp.add(Fp.mul(CURVE.a, x2), y2);\n const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));\n return Fp.eql(left, right);\n}\n\nexport function edwards(params: EdwardsOpts, extraOpts: EdwardsExtraOpts = {}): EdwardsPointCons {\n const validated = _createCurveFields('edwards', params, extraOpts, extraOpts.FpFnLE);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE as EdwardsOpts;\n const { h: cofactor } = CURVE;\n _validateObject(extraOpts, {}, { uvRatio: 'function' });\n\n // Important:\n // There are some places where Fp.BYTES is used instead of nByteLength.\n // So far, everything has been tested with curves of Fp.BYTES == nByteLength.\n // TODO: test and find curves which behave otherwise.\n const MASK = _2n << (BigInt(Fn.BYTES * 8) - _1n);\n const modP = (n: bigint) => Fp.create(n); // Function overrides\n\n // sqrt(u/v)\n const uvRatio =\n extraOpts.uvRatio ||\n ((u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n\n // Validate whether the passed curve params are valid.\n // equation ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2 should work for generator point.\n if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n\n /**\n * Asserts coordinate is valid: 0 <= n < MASK.\n * Coordinates >= Fp.ORDER are allowed for zip215.\n */\n function acoord(title: string, n: bigint, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n return n;\n }\n\n function aextpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ExtendedPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p: Point, iz?: bigint): AffinePoint<bigint> => {\n const { X, Y, Z } = p;\n const is0 = p.is0();\n if (iz == null) iz = is0 ? _8n : (Fp.inv(Z) as bigint); // 8 was chosen arbitrarily\n const x = modP(X * iz);\n const y = modP(Y * iz);\n const zz = Fp.mul(Z, iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x, y };\n });\n const assertValidMemo = memoized((p: Point) => {\n const { a, d } = CURVE;\n if (p.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX\u00B2 + Y\u00B2)Z\u00B2 = Z\u2074 + dX\u00B2Y\u00B2\n const { X, Y, Z, T } = p;\n const X2 = modP(X * X); // X\u00B2\n const Y2 = modP(Y * Y); // Y\u00B2\n const Z2 = modP(Z * Z); // Z\u00B2\n const Z4 = modP(Z2 * Z2); // Z\u2074\n const aX2 = modP(X2 * a); // aX\u00B2\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX\u00B2 + Y\u00B2)Z\u00B2\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z\u2074 + dX\u00B2Y\u00B2\n if (left !== right) throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT) throw new Error('bad point: equation left != right (2)');\n return true;\n });\n\n // Extended Point works in extended coordinates: (X, Y, Z, T) \u220B (x=X/Z, y=Y/Z, T=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point implements EdwardsPoint {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n // zero / infinity / identity point\n static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: bigint;\n readonly Y: bigint;\n readonly Z: bigint;\n readonly T: bigint;\n\n constructor(X: bigint, Y: bigint, Z: bigint, T: bigint) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y);\n this.Z = acoord('z', Z, true);\n this.T = acoord('t', T);\n Object.freeze(this);\n }\n\n static CURVE(): EdwardsOpts {\n return CURVE;\n }\n\n static fromAffine(p: AffinePoint<bigint>): Point {\n if (p instanceof Point) throw new Error('extended point not allowed');\n const { x, y } = p || {};\n acoord('x', x);\n acoord('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n\n // Uses algo from RFC8032 5.1.3.\n static fromBytes(bytes: Uint8Array, zip215 = false): Point {\n const len = Fp.BYTES;\n const { a, d } = CURVE;\n bytes = copyBytes(abytes(bytes, len, 'point'));\n abool(zip215, 'zip215');\n const normed = copyBytes(bytes); // copy again, we'll manipulate it\n const lastByte = bytes[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = bytesToNumberLE(normed);\n\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n aInRange('point.y', y, _0n, max);\n\n // Ed25519: x\u00B2 = (y\u00B2-1)/(dy\u00B2+1) mod p. Ed448: x\u00B2 = (y\u00B2-1)/(dy\u00B2-1) mod p. Generic case:\n // ax\u00B2+y\u00B2=1+dx\u00B2y\u00B2 => y\u00B2-1=dx\u00B2y\u00B2-ax\u00B2 => y\u00B2-1=x\u00B2(dy\u00B2-a) => x\u00B2=(y\u00B2-1)/(dy\u00B2-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y\u00B2 - 1\n const v = modP(d * y2 - a); // v = d y\u00B2 + 1.\n let { isValid, value: x } = uvRatio(u, v); // \u221A(u/v)\n if (!isValid) throw new Error('bad point: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('bad point: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromHex(bytes: Uint8Array, zip215 = false): Point {\n return Point.fromBytes(ensureBytes('point', bytes), zip215);\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n precompute(windowSize: number = 8, isLazy = true) {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_2n); // random number\n return this;\n }\n\n // Useful in fromAffine() - not for fromBytes(), which always created valid points.\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n aextpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n\n is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n negate(): Point {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));\n }\n\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double(): Point {\n const { a } = CURVE;\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other: Point) {\n aextpoint(other);\n const { a, d } = CURVE;\n const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n subtract(other: Point): Point {\n return this.add(other.negate());\n }\n\n // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n // 1 <= scalar < L\n if (!Fn.isValidNot0(scalar)) throw new Error('invalid scalar: expected 1 <= sc < curve.n');\n const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));\n return normalizeZ(Point, [p, f])[0];\n }\n\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n // Accepts optional accumulator to merge with multiply (important for sparse scalars)\n multiplyUnsafe(scalar: bigint, acc = Point.ZERO): Point {\n // 0 <= scalar < L\n if (!Fn.isValid(scalar)) throw new Error('invalid scalar: expected 0 <= sc < curve.n');\n if (scalar === _0n) return Point.ZERO;\n if (this.is0() || scalar === _1n) return this;\n return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);\n }\n\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder(): boolean {\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree(): boolean {\n return wnaf.unsafe(this, CURVE.n).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n return toAffineMemo(this, invertedZ);\n }\n\n clearCofactor(): Point {\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n toBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n // Fp.toBytes() allows non-canonical encoding of y (>= p).\n const bytes = Fp.toBytes(y);\n // Each y has 2 valid points: (x, y), (x,-y).\n // When compressing, it's enough to store y and use the last byte to encode sign of x\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0;\n return bytes;\n }\n toHex(): string {\n return bytesToHex(this.toBytes());\n }\n\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n\n // TODO: remove\n get ex(): bigint {\n return this.X;\n }\n get ey(): bigint {\n return this.Y;\n }\n get ez(): bigint {\n return this.Z;\n }\n get et(): bigint {\n return this.T;\n }\n static normalizeZ(points: Point[]): Point[] {\n return normalizeZ(Point, points);\n }\n static msm(points: Point[], scalars: bigint[]): Point {\n return pippenger(Point, Fn, points, scalars);\n }\n _setWindowSize(windowSize: number) {\n this.precompute(windowSize);\n }\n toRawBytes(): Uint8Array {\n return this.toBytes();\n }\n }\n const wnaf = new wNAF(Point, Fn.BITS);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n\n/**\n * Base class for prime-order points like Ristretto255 and Decaf448.\n * These points eliminate cofactor issues by representing equivalence classes\n * of Edwards curve points.\n */\nexport abstract class PrimeEdwardsPoint<T extends PrimeEdwardsPoint<T>>\n implements CurvePoint<bigint, T>\n{\n static BASE: PrimeEdwardsPoint<any>;\n static ZERO: PrimeEdwardsPoint<any>;\n static Fp: IField<bigint>;\n static Fn: IField<bigint>;\n\n protected readonly ep: EdwardsPoint;\n\n constructor(ep: EdwardsPoint) {\n this.ep = ep;\n }\n\n // Abstract methods that must be implemented by subclasses\n abstract toBytes(): Uint8Array;\n abstract equals(other: T): boolean;\n\n // Static methods that must be implemented by subclasses\n static fromBytes(_bytes: Uint8Array): any {\n notImplemented();\n }\n\n static fromHex(_hex: Hex): any {\n notImplemented();\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n // Common implementations\n clearCofactor(): T {\n // no-op for prime-order groups\n return this as any;\n }\n\n assertValidity(): void {\n this.ep.assertValidity();\n }\n\n toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n return this.ep.toAffine(invertedZ);\n }\n\n toHex(): string {\n return bytesToHex(this.toBytes());\n }\n\n toString(): string {\n return this.toHex();\n }\n\n isTorsionFree(): boolean {\n return true;\n }\n\n isSmallOrder(): boolean {\n return false;\n }\n\n add(other: T): T {\n this.assertSame(other);\n return this.init(this.ep.add(other.ep));\n }\n\n subtract(other: T): T {\n this.assertSame(other);\n return this.init(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): T {\n return this.init(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): T {\n return this.init(this.ep.multiplyUnsafe(scalar));\n }\n\n double(): T {\n return this.init(this.ep.double());\n }\n\n negate(): T {\n return this.init(this.ep.negate());\n }\n\n precompute(windowSize?: number, isLazy?: boolean): T {\n return this.init(this.ep.precompute(windowSize, isLazy));\n }\n\n // Helper methods\n abstract is0(): boolean;\n protected abstract assertSame(other: T): void;\n protected abstract init(ep: EdwardsPoint): T;\n\n /** @deprecated use `toBytes` */\n toRawBytes(): Uint8Array {\n return this.toBytes();\n }\n}\n\n/**\n * Initializes EdDSA signatures over given Edwards curve.\n */\nexport function eddsa(Point: EdwardsPointCons, cHash: FHash, eddsaOpts: EdDSAOpts = {}): EdDSA {\n if (typeof cHash !== 'function') throw new Error('\"hash\" function param is required');\n _validateObject(\n eddsaOpts,\n {},\n {\n adjustScalarBytes: 'function',\n randomBytes: 'function',\n domain: 'function',\n prehash: 'function',\n mapToCurve: 'function',\n }\n );\n\n const { prehash } = eddsaOpts;\n const { BASE, Fp, Fn } = Point;\n\n const randomBytes = eddsaOpts.randomBytes || randomBytesWeb;\n const adjustScalarBytes = eddsaOpts.adjustScalarBytes || ((bytes: Uint8Array) => bytes);\n const domain =\n eddsaOpts.domain ||\n ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => {\n abool(phflag, 'phflag');\n if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n\n // Little-endian SHA512 with modulo n\n function modN_LE(hash: Uint8Array): bigint {\n return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit\n }\n\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key: Hex) {\n const len = lengths.secretKey;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n return { head, prefix, scalar };\n }\n\n /** Convenience method that creates public key from scalar. RFC8032 5.1.5 */\n function getExtendedPublicKey(secretKey: Hex) {\n const { head, prefix, scalar } = getPrivateScalar(secretKey);\n const point = BASE.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toBytes();\n return { head, prefix, scalar, point, pointBytes };\n }\n\n /** Calculates EdDSA pub key. RFC8032 5.1.5. */\n function getPublicKey(secretKey: Hex): Uint8Array {\n return getExtendedPublicKey(secretKey).pointBytes;\n }\n\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context: Hex = Uint8Array.of(), ...msgs: Uint8Array[]) {\n const msg = concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg: Hex, secretKey: Hex, options: { context?: Hex } = {}): Uint8Array {\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = BASE.multiply(r).toBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L\n if (!Fn.isValid(s)) throw new Error('sign failed: invalid s'); // 0 <= s < L\n const rs = concatBytes(R, Fn.toBytes(s));\n return abytes(rs, lengths.signature, 'result');\n }\n\n // verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\n const verifyOpts: { context?: Hex; zip215?: boolean } = { zip215: true };\n\n /**\n * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n * An extended group equation is checked.\n */\n function verify(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean {\n const { context, zip215 } = options;\n const len = lengths.signature;\n sig = ensureBytes('signature', sig, len);\n msg = ensureBytes('message', msg);\n publicKey = ensureBytes('publicKey', publicKey, lengths.publicKey);\n if (zip215 !== undefined) abool(zip215, 'zip215');\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const mid = len / 2;\n const r = sig.subarray(0, mid);\n const s = bytesToNumberLE(sig.subarray(mid, len));\n let A, R, SB;\n try {\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromBytes(publicKey, zip215);\n R = Point.fromBytes(r, zip215);\n SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder()) return false; // zip215 allows public keys of small order\n\n const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Extended group equation\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().is0();\n }\n\n const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448\n const lengths = {\n secretKey: _size,\n publicKey: _size,\n signature: 2 * _size,\n seed: _size,\n };\n function randomSecretKey(seed = randomBytes(lengths.seed)): Uint8Array {\n return abytes(seed, lengths.seed, 'seed');\n }\n function keygen(seed?: Uint8Array) {\n const secretKey = utils.randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n }\n function isValidSecretKey(key: Uint8Array): boolean {\n return isBytes(key) && key.length === Fn.BYTES;\n }\n function isValidPublicKey(key: Uint8Array, zip215?: boolean): boolean {\n try {\n return !!Point.fromBytes(key, zip215);\n } catch (error) {\n return false;\n }\n }\n\n const utils = {\n getExtendedPublicKey,\n randomSecretKey,\n isValidSecretKey,\n isValidPublicKey,\n /**\n * Converts ed public key to x public key. Uses formula:\n * - ed25519:\n * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * - ed448:\n * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`\n * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`\n */\n toMontgomery(publicKey: Uint8Array): Uint8Array {\n const { y } = Point.fromBytes(publicKey);\n const size = lengths.publicKey;\n const is25519 = size === 32;\n if (!is25519 && size !== 57) throw new Error('only defined for 25519 and 448');\n const u = is25519 ? Fp.div(_1n + y, _1n - y) : Fp.div(y - _1n, y + _1n);\n return Fp.toBytes(u);\n },\n\n toMontgomerySecret(secretKey: Uint8Array): Uint8Array {\n const size = lengths.secretKey;\n abytes(secretKey, size);\n const hashed = cHash(secretKey.subarray(0, size));\n return adjustScalarBytes(hashed).subarray(0, size);\n },\n\n /** @deprecated */\n randomPrivateKey: randomSecretKey,\n /** @deprecated */\n precompute(windowSize = 8, point: EdwardsPoint = Point.BASE): EdwardsPoint {\n return point.precompute(windowSize, false);\n },\n };\n\n return Object.freeze({\n keygen,\n getPublicKey,\n sign,\n verify,\n utils,\n Point,\n lengths,\n });\n}\n\n// TODO: remove everything below\nexport type CurveType = BasicCurve<bigint> & {\n a: bigint; // curve param a\n d: bigint; // curve param d\n /** @deprecated the property will be removed in next release */\n hash: FHash; // Hashing\n randomBytes?: (bytesLength?: number) => Uint8Array; // CSPRNG\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing\n uvRatio?: UVRatio; // Ratio \u221A(u/v)\n prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify()\n mapToCurve?: (scalar: bigint[]) => AffinePoint<bigint>; // for hash-to-curve standard\n};\nexport type CurveTypeWithLength = Readonly<CurveType & Partial<NLength>>;\nexport type CurveFn = {\n /** @deprecated the property will be removed in next release */\n CURVE: CurveType;\n keygen: EdDSA['keygen'];\n getPublicKey: EdDSA['getPublicKey'];\n sign: EdDSA['sign'];\n verify: EdDSA['verify'];\n Point: EdwardsPointCons;\n /** @deprecated use `Point` */\n ExtendedPoint: EdwardsPointCons;\n utils: EdDSA['utils'];\n lengths: CurveLengths;\n};\nexport type EdComposed = {\n CURVE: EdwardsOpts;\n curveOpts: EdwardsExtraOpts;\n hash: FHash;\n eddsaOpts: EdDSAOpts;\n};\nfunction _eddsa_legacy_opts_to_new(c: CurveTypeWithLength): EdComposed {\n const CURVE: EdwardsOpts = {\n a: c.a,\n d: c.d,\n p: c.Fp.ORDER,\n n: c.n,\n h: c.h,\n Gx: c.Gx,\n Gy: c.Gy,\n };\n const Fp = c.Fp;\n const Fn = Field(CURVE.n, c.nBitLength, true);\n const curveOpts: EdwardsExtraOpts = { Fp, Fn, uvRatio: c.uvRatio };\n const eddsaOpts: EdDSAOpts = {\n randomBytes: c.randomBytes,\n adjustScalarBytes: c.adjustScalarBytes,\n domain: c.domain,\n prehash: c.prehash,\n mapToCurve: c.mapToCurve,\n };\n return { CURVE, curveOpts, hash: c.hash, eddsaOpts };\n}\nfunction _eddsa_new_output_to_legacy(c: CurveTypeWithLength, eddsa: EdDSA): CurveFn {\n const Point = eddsa.Point;\n const legacy = Object.assign({}, eddsa, {\n ExtendedPoint: Point,\n CURVE: c,\n nBitLength: Point.Fn.BITS,\n nByteLength: Point.Fn.BYTES,\n });\n return legacy;\n}\n// TODO: remove. Use eddsa\nexport function twistedEdwards(c: CurveTypeWithLength): CurveFn {\n const { CURVE, curveOpts, hash, eddsaOpts } = _eddsa_legacy_opts_to_new(c);\n const Point = edwards(CURVE, curveOpts);\n const EDDSA = eddsa(Point, hash, eddsaOpts);\n return _eddsa_new_output_to_legacy(c, EDDSA);\n}\n", "/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, utf8ToBytes } from '@noble/hashes/utils.js';\nimport { pippenger, type AffinePoint } from './abstract/curve.ts';\nimport {\n PrimeEdwardsPoint,\n twistedEdwards,\n type CurveFn,\n type EdwardsOpts,\n type EdwardsPoint,\n} from './abstract/edwards.ts';\nimport {\n _DST_scalar,\n createHasher,\n expand_message_xmd,\n type H2CHasher,\n type H2CHasherBase,\n type H2CMethod,\n type htfBasicOpts,\n} from './abstract/hash-to-curve.ts';\nimport {\n Field,\n FpInvertBatch,\n FpSqrtEven,\n isNegativeLE,\n mod,\n pow2,\n type IField,\n} from './abstract/modular.ts';\nimport { montgomery, type MontgomeryECDH as XCurveFn } from './abstract/montgomery.ts';\nimport { bytesToNumberLE, ensureBytes, equalBytes, type Hex } from './utils.ts';\n\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\n\n// P = 2n**255n-19n\nconst ed25519_CURVE_p = BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed'\n);\n\n// N = 2n**252n + 27742317777372353535851937790883648493n\n// a = Fp.create(BigInt(-1))\n// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\nconst ed25519_CURVE: EdwardsOpts = /* @__PURE__ */ (() => ({\n p: ed25519_CURVE_p,\n n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),\n h: _8n,\n a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),\n d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),\n Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),\n Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),\n}))();\n\nfunction ed25519_pow_2_252_3(x: bigint) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ed25519_CURVE_p;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\n\nfunction adjustScalarBytes(bytes: Uint8Array): Uint8Array {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\n// Fp.sqrt(Fp.neg(1))\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt(\n '19681161376707505956807079304988542015446066515923890162744021073123829784752'\n);\n// sqrt(u/v)\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ed25519_CURVE_p;\n const v3 = mod(v * v * v, P); // v\u00B3\n const v7 = mod(v3 * v3 * v, P); // v\u2077\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv\u00B3)(uv\u2077)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx\u00B2\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx\u00B2 = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx\u00B2 = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx\u00B2 = -u\u221A(-1)\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P)) x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n\nconst Fp = /* @__PURE__ */ (() => Field(ed25519_CURVE.p, { isLE: true }))();\nconst Fn = /* @__PURE__ */ (() => Field(ed25519_CURVE.n, { isLE: true }))();\n\nconst ed25519Defaults = /* @__PURE__ */ (() => ({\n ...ed25519_CURVE,\n Fp,\n hash: sha512,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/\u221Av\n uvRatio,\n}))();\n\n/**\n * ed25519 curve with EdDSA signatures.\n * @example\n * import { ed25519 } from '@noble/curves/ed25519';\n * const { secretKey, publicKey } = ed25519.keygen();\n * const msg = new TextEncoder().encode('hello');\n * const sig = ed25519.sign(msg, priv);\n * ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215\n * ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5\n */\nexport const ed25519: CurveFn = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();\n\nfunction ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) {\n if (ctx.length > 255) throw new Error('Context is too big');\n return concatBytes(\n utf8ToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n );\n}\n\n/** Context of ed25519. Uses context for domain separation. */\nexport const ed25519ctx: CurveFn = /* @__PURE__ */ (() =>\n twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n }))();\n\n/** Prehashed version of ed25519. Accepts already-hashed messages in sign() and verify(). */\nexport const ed25519ph: CurveFn = /* @__PURE__ */ (() =>\n twistedEdwards(\n Object.assign({}, ed25519Defaults, {\n domain: ed25519_domain,\n prehash: sha512,\n })\n ))();\n\n/**\n * ECDH using curve25519 aka x25519.\n * @example\n * import { x25519 } from '@noble/curves/ed25519';\n * const priv = 'a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4';\n * const pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c';\n * x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases\n * x25519.getPublicKey(priv) === x25519.scalarMultBase(priv);\n * x25519.getPublicKey(x25519.utils.randomSecretKey());\n */\nexport const x25519: XCurveFn = /* @__PURE__ */ (() => {\n const P = Fp.ORDER;\n return montgomery({\n P,\n type: 'x25519',\n powPminus2: (x: bigint): bigint => {\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n },\n adjustScalarBytes,\n });\n})();\n\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\nconst ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u: bigint) {\n const ELL2_C4 = (ed25519_CURVE_p - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic\n const ELL2_J = BigInt(486662);\n\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J);// 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd!(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\n\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u: bigint) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division\n return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd)\n}\n\n/** Hashing to ed25519 points / field. RFC 9380 methods. */\nexport const ed25519_hasher: H2CHasher<bigint> = /* @__PURE__ */ (() =>\n createHasher(\n ed25519.Point,\n (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]),\n {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: ed25519_CURVE_p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\n ))();\n\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// \u221A(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt(\n '25063068953384623474111414158702152701244531502492656460079210482610430750235'\n);\n// 1 / \u221A(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt(\n '54469307008909316920995813868745141605393597292927456921205312896311721017578'\n);\n// 1-d\u00B2\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt(\n '1159843021668779879193775521855586647937357759715417654439879720876111806838'\n);\n// (d-1)\u00B2\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt(\n '40440834346308536858101042469323190826248399146238708352240133220865137265952'\n);\n// Calculates 1/\u221A(number)\nconst invertSqrt = (number: bigint) => uvRatio(_1n, number);\n\nconst MAX_255B = /* @__PURE__ */ BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'\n);\nconst bytes255ToNumberLE = (bytes: Uint8Array) =>\n ed25519.Point.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\ntype ExtendedPoint = EdwardsPoint;\n\n/**\n * Computes Elligator map for Ristretto255.\n * Described in [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#appendix-B) and on\n * the [website](https://ristretto.group/formulas/elligator.html).\n */\nfunction calcElligatorRistrettoMap(r0: bigint): ExtendedPoint {\n const { d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P)) s_ = mod(-s_);\n if (!Ns_D_is_sq) s = s_; // 7\n if (!Ns_D_is_sq) c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\nfunction ristretto255_map(bytes: Uint8Array): _RistrettoPoint {\n abytes(bytes, 64);\n const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new _RistrettoPoint(R1.add(R2));\n}\n\n/**\n * Wrapper over Edwards Point for ristretto255.\n *\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nclass _RistrettoPoint extends PrimeEdwardsPoint<_RistrettoPoint> {\n // Do NOT change syntax: the following gymnastics is done,\n // because typescript strips comments, which makes bundlers disable tree-shaking.\n // prettier-ignore\n static BASE: _RistrettoPoint =\n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.BASE))();\n // prettier-ignore\n static ZERO: _RistrettoPoint =\n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.ZERO))();\n // prettier-ignore\n static Fp: IField<bigint> =\n /* @__PURE__ */ (() => Fp)();\n // prettier-ignore\n static Fn: IField<bigint> =\n /* @__PURE__ */ (() => Fn)();\n\n constructor(ep: ExtendedPoint) {\n super(ep);\n }\n\n static fromAffine(ap: AffinePoint<bigint>): _RistrettoPoint {\n return new _RistrettoPoint(ed25519.Point.fromAffine(ap));\n }\n\n protected assertSame(other: _RistrettoPoint): void {\n if (!(other instanceof _RistrettoPoint)) throw new Error('RistrettoPoint expected');\n }\n\n protected init(ep: EdwardsPoint): _RistrettoPoint {\n return new _RistrettoPoint(ep);\n }\n\n /** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\n static hashToCurve(hex: Hex): _RistrettoPoint {\n return ristretto255_map(ensureBytes('ristrettoHash', hex, 64));\n }\n\n static fromBytes(bytes: Uint8Array): _RistrettoPoint {\n abytes(bytes, 32);\n const { a, d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const s = bytes255ToNumberLE(bytes);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))\n throw new Error('invalid ristretto255 encoding 1');\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P)) x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n)\n throw new Error('invalid ristretto255 encoding 2');\n return new _RistrettoPoint(new ed25519.Point(x, y, _1n, t));\n }\n\n /**\n * Converts ristretto-encoded string to ristretto point.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex: Hex): _RistrettoPoint {\n return _RistrettoPoint.fromBytes(ensureBytes('ristrettoHex', hex, 32));\n }\n\n static msm(points: _RistrettoPoint[], scalars: bigint[]): _RistrettoPoint {\n return pippenger(_RistrettoPoint, ed25519.Point.Fn, points, scalars);\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n */\n toBytes(): Uint8Array {\n let { X, Y, Z, T } = this.ep;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const u1 = mod(mod(Z + Y) * mod(Z - Y)); // 1\n const u2 = mod(X * Y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * T); // 6\n let D: bigint; // 7\n if (isNegativeLE(T * zInv, P)) {\n let _x = mod(Y * SQRT_M1);\n let _y = mod(X * SQRT_M1);\n X = _x;\n Y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n } else {\n D = D2; // 8\n }\n if (isNegativeLE(X * zInv, P)) Y = mod(-Y); // 9\n let s = mod((Z - Y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P)) s = mod(-s);\n return Fp.toBytes(s); // 11\n }\n\n /**\n * Compares two Ristretto points.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).\n */\n equals(other: _RistrettoPoint): boolean {\n this.assertSame(other);\n const { X: X1, Y: Y1 } = this.ep;\n const { X: X2, Y: Y2 } = other.ep;\n const mod = (n: bigint) => Fp.create(n);\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n\n is0(): boolean {\n return this.equals(_RistrettoPoint.ZERO);\n }\n}\n\nexport const ristretto255: {\n Point: typeof _RistrettoPoint;\n} = { Point: _RistrettoPoint };\n\n/** Hashing to ristretto255 points / field. RFC 9380 methods. */\nexport const ristretto255_hasher: H2CHasherBase<bigint> = {\n hashToCurve(msg: Uint8Array, options?: htfBasicOpts): _RistrettoPoint {\n const DST = options?.DST || 'ristretto255_XMD:SHA-512_R255MAP_RO_';\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n return ristretto255_map(xmd);\n },\n hashToScalar(msg: Uint8Array, options: htfBasicOpts = { DST: _DST_scalar }) {\n const xmd = expand_message_xmd(msg, options.DST, 64, sha512);\n return Fn.create(bytesToNumberLE(xmd));\n },\n};\n\n// export const ristretto255_oprf: OPRF = createORPF({\n// name: 'ristretto255-SHA512',\n// Point: RistrettoPoint,\n// hash: sha512,\n// hashToGroup: ristretto255_hasher.hashToCurve,\n// hashToScalar: ristretto255_hasher.hashToScalar,\n// });\n\n/**\n * Weird / bogus points, useful for debugging.\n * All 8 ed25519 points of 8-torsion subgroup can be generated from the point\n * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.\n * \u27E8T\u27E9 = { O, T, 2T, 3T, 4T, 5T, 6T, 7T }\n */\nexport const ED25519_TORSION_SUBGROUP: string[] = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n\n/** @deprecated use `ed25519.utils.toMontgomery` */\nexport function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array {\n return ed25519.utils.toMontgomery(ensureBytes('pub', edwardsPub));\n}\n/** @deprecated use `ed25519.utils.toMontgomery` */\nexport const edwardsToMontgomery: typeof edwardsToMontgomeryPub = edwardsToMontgomeryPub;\n\n/** @deprecated use `ed25519.utils.toMontgomerySecret` */\nexport function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array {\n return ed25519.utils.toMontgomerySecret(ensureBytes('pub', edwardsPriv));\n}\n\n/** @deprecated use `ristretto255.Point` */\nexport const RistrettoPoint: typeof _RistrettoPoint = _RistrettoPoint;\n/** @deprecated use `import { ed25519_hasher } from '@noble/curves/ed25519.js';` */\nexport const hashToCurve: H2CMethod<bigint> = /* @__PURE__ */ (() => ed25519_hasher.hashToCurve)();\n/** @deprecated use `import { ed25519_hasher } from '@noble/curves/ed25519.js';` */\nexport const encodeToCurve: H2CMethod<bigint> = /* @__PURE__ */ (() =>\n ed25519_hasher.encodeToCurve)();\ntype RistHasher = (msg: Uint8Array, options: htfBasicOpts) => _RistrettoPoint;\n/** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\nexport const hashToRistretto255: RistHasher = /* @__PURE__ */ (() =>\n ristretto255_hasher.hashToCurve as RistHasher)();\n/** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\nexport const hash_to_ristretto255: RistHasher = /* @__PURE__ */ (() =>\n ristretto255_hasher.hashToCurve as RistHasher)();\n", "import {\n DerDecodeErrorCode,\n DerDecodeLengthMismatchErrorCode,\n DerEncodeErrorCode,\n InputError,\n} from './errors.ts';\nimport { uint8Equals } from './utils/buffer.ts';\n\nexport const encodeLenBytes = (len: number): number => {\n if (len <= 0x7f) {\n return 1;\n } else if (len <= 0xff) {\n return 2;\n } else if (len <= 0xffff) {\n return 3;\n } else if (len <= 0xffffff) {\n return 4;\n } else {\n throw InputError.fromCode(new DerEncodeErrorCode('Length too long (> 4 bytes)'));\n }\n};\n\nexport const encodeLen = (buf: Uint8Array, offset: number, len: number): number => {\n if (len <= 0x7f) {\n buf[offset] = len;\n return 1;\n } else if (len <= 0xff) {\n buf[offset] = 0x81;\n buf[offset + 1] = len;\n return 2;\n } else if (len <= 0xffff) {\n buf[offset] = 0x82;\n buf[offset + 1] = len >> 8;\n buf[offset + 2] = len;\n return 3;\n } else if (len <= 0xffffff) {\n buf[offset] = 0x83;\n buf[offset + 1] = len >> 16;\n buf[offset + 2] = len >> 8;\n buf[offset + 3] = len;\n return 4;\n } else {\n throw InputError.fromCode(new DerEncodeErrorCode('Length too long (> 4 bytes)'));\n }\n};\n\nexport const decodeLenBytes = (buf: Uint8Array, offset: number): number => {\n if (buf[offset] < 0x80) return 1;\n if (buf[offset] === 0x80) throw InputError.fromCode(new DerDecodeErrorCode('Invalid length 0'));\n if (buf[offset] === 0x81) return 2;\n if (buf[offset] === 0x82) return 3;\n if (buf[offset] === 0x83) return 4;\n throw InputError.fromCode(new DerDecodeErrorCode('Length too long (> 4 bytes)'));\n};\n\nexport const decodeLen = (buf: Uint8Array, offset: number): number => {\n const lenBytes = decodeLenBytes(buf, offset);\n if (lenBytes === 1) return buf[offset];\n else if (lenBytes === 2) return buf[offset + 1];\n else if (lenBytes === 3) return (buf[offset + 1] << 8) + buf[offset + 2];\n else if (lenBytes === 4)\n return (buf[offset + 1] << 16) + (buf[offset + 2] << 8) + buf[offset + 3];\n throw InputError.fromCode(new DerDecodeErrorCode('Length too long (> 4 bytes)'));\n};\n\n/**\n * A DER encoded `SEQUENCE(OID)` for DER-encoded-COSE\n */\nexport const DER_COSE_OID = Uint8Array.from([\n ...[0x30, 0x0c], // SEQUENCE\n ...[0x06, 0x0a], // OID with 10 bytes\n ...[0x2b, 0x06, 0x01, 0x04, 0x01, 0x83, 0xb8, 0x43, 0x01, 0x01], // DER encoded COSE\n]);\n\n/**\n * A DER encoded `SEQUENCE(OID)` for the Ed25519 algorithm\n */\nexport const ED25519_OID = Uint8Array.from([\n ...[0x30, 0x05], // SEQUENCE\n ...[0x06, 0x03], // OID with 3 bytes\n ...[0x2b, 0x65, 0x70], // id-Ed25519 OID\n]);\n\n/**\n * A DER encoded `SEQUENCE(OID)` for secp256k1 with the ECDSA algorithm\n */\nexport const SECP256K1_OID = Uint8Array.from([\n ...[0x30, 0x10], // SEQUENCE\n ...[0x06, 0x07], // OID with 7 bytes\n ...[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01], // OID ECDSA\n ...[0x06, 0x05], // OID with 5 bytes\n ...[0x2b, 0x81, 0x04, 0x00, 0x0a], // OID secp256k1\n]);\n\nexport const BLS12_381_G2_OID = Uint8Array.from([\n ...[0x30, 0x1d], // SEQUENCE, length 29 bytes\n // Algorithm OID\n ...[0x06, 0x0d],\n ...[0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xdc, 0x7c, 0x05, 0x03, 0x01, 0x02, 0x01],\n // Curve OID\n ...[0x06, 0x0c],\n ...[0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xdc, 0x7c, 0x05, 0x03, 0x02, 0x01],\n]);\n\n/**\n * Wraps the given `payload` in a DER encoding tagged with the given encoded `oid` like so:\n * `SEQUENCE(oid, BITSTRING(payload))`\n * @param payload The payload to encode as the bit string\n * @param oid The DER encoded (and SEQUENCE wrapped!) OID to tag the payload with\n */\nexport function wrapDER(payload: Uint8Array, oid: Uint8Array): Uint8Array {\n // The Bit String header needs to include the unused bit count byte in its length\n const bitStringHeaderLength = 2 + encodeLenBytes(payload.byteLength + 1);\n const len = oid.byteLength + bitStringHeaderLength + payload.byteLength;\n let offset = 0;\n const buf = new Uint8Array(1 + encodeLenBytes(len) + len);\n // Sequence\n buf[offset++] = 0x30;\n // Sequence Length\n offset += encodeLen(buf, offset, len);\n\n // OID\n buf.set(oid, offset);\n offset += oid.byteLength;\n\n // Bit String Header\n buf[offset++] = 0x03;\n offset += encodeLen(buf, offset, payload.byteLength + 1);\n // 0 padding\n buf[offset++] = 0x00;\n buf.set(new Uint8Array(payload), offset);\n\n return buf;\n}\n\n/**\n * Extracts a payload from the given `derEncoded` data, and checks that it was tagged with the given `oid`.\n *\n * `derEncoded = SEQUENCE(oid, BITSTRING(payload))`\n * @param derEncoded The DER encoded and tagged data\n * @param oid The DER encoded (and SEQUENCE wrapped!) expected OID\n * @returns The unwrapped payload\n */\nexport const unwrapDER = (derEncoded: Uint8Array, oid: Uint8Array): Uint8Array => {\n let offset = 0;\n const expect = (n: number, msg: string) => {\n if (buf[offset++] !== n) {\n throw InputError.fromCode(new DerDecodeErrorCode(`Expected ${msg} at offset ${offset}`));\n }\n };\n\n const buf = new Uint8Array(derEncoded);\n expect(0x30, 'sequence');\n offset += decodeLenBytes(buf, offset);\n\n if (!uint8Equals(buf.slice(offset, offset + oid.byteLength), oid)) {\n throw InputError.fromCode(new DerDecodeErrorCode('Not the expected OID.'));\n }\n offset += oid.byteLength;\n\n expect(0x03, 'bit string');\n const payloadLen = decodeLen(buf, offset) - 1; // Subtracting 1 to account for the 0 padding\n offset += decodeLenBytes(buf, offset);\n expect(0x00, '0 padding');\n const result = buf.slice(offset);\n if (payloadLen !== result.length) {\n throw InputError.fromCode(new DerDecodeLengthMismatchErrorCode(payloadLen, result.length));\n }\n return result;\n};\n", "import {\n type DerEncodedPublicKey,\n type KeyPair,\n type PublicKey,\n type Signature,\n SignIdentity,\n ED25519_OID,\n unwrapDER,\n wrapDER,\n} from '#agent';\nimport { uint8Equals, uint8FromBufLike } from '#candid';\nimport { ed25519 } from '@noble/curves/ed25519';\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils';\n\ndeclare type KeyLike = PublicKey | DerEncodedPublicKey | ArrayBuffer | ArrayBufferView;\n\nfunction isObject(value: unknown) {\n return value !== null && typeof value === 'object';\n}\n\nexport class Ed25519PublicKey implements PublicKey {\n /**\n * Construct Ed25519PublicKey from an existing PublicKey\n * @param {unknown} maybeKey - existing PublicKey, ArrayBuffer, DerEncodedPublicKey, or hex string\n * @returns {Ed25519PublicKey} Instance of Ed25519PublicKey\n */\n public static from(maybeKey: unknown): Ed25519PublicKey {\n if (typeof maybeKey === 'string') {\n const key = hexToBytes(maybeKey);\n return this.fromRaw(key);\n } else if (isObject(maybeKey)) {\n const key = maybeKey as KeyLike;\n if (isObject(key) && Object.hasOwnProperty.call(key, '__derEncodedPublicKey__')) {\n return this.fromDer(key as DerEncodedPublicKey);\n } else if (ArrayBuffer.isView(key)) {\n const view = key as ArrayBufferView;\n return this.fromRaw(uint8FromBufLike(view.buffer));\n } else if (key instanceof ArrayBuffer) {\n return this.fromRaw(uint8FromBufLike(key));\n } else if ('rawKey' in key && key.rawKey instanceof Uint8Array) {\n return this.fromRaw(key.rawKey);\n } else if ('derKey' in key) {\n return this.fromDer(key.derKey as DerEncodedPublicKey);\n } else if ('toDer' in key) {\n return this.fromDer(key.toDer());\n }\n }\n throw new Error('Cannot construct Ed25519PublicKey from the provided key.');\n }\n\n public static fromRaw(rawKey: Uint8Array): Ed25519PublicKey {\n return new Ed25519PublicKey(rawKey);\n }\n\n public static fromDer(derKey: DerEncodedPublicKey): Ed25519PublicKey {\n return new Ed25519PublicKey(this.derDecode(derKey));\n }\n\n // The length of Ed25519 public keys is always 32 bytes.\n private static RAW_KEY_LENGTH = 32;\n\n private static derEncode(publicKey: Uint8Array): DerEncodedPublicKey {\n const key = wrapDER(publicKey, ED25519_OID) as DerEncodedPublicKey;\n key.__derEncodedPublicKey__ = undefined;\n return key;\n }\n\n private static derDecode(key: DerEncodedPublicKey): Uint8Array {\n const unwrapped = unwrapDER(key, ED25519_OID);\n if (unwrapped.length !== this.RAW_KEY_LENGTH) {\n throw new Error('An Ed25519 public key must be exactly 32bytes long');\n }\n return unwrapped;\n }\n\n #rawKey: Uint8Array;\n\n public get rawKey(): Uint8Array {\n return this.#rawKey;\n }\n\n #derKey: DerEncodedPublicKey;\n\n public get derKey(): DerEncodedPublicKey {\n return this.#derKey;\n }\n\n // `fromRaw` and `fromDer` should be used for instantiation, not this constructor.\n private constructor(key: Uint8Array) {\n if (key.byteLength !== Ed25519PublicKey.RAW_KEY_LENGTH) {\n throw new Error('An Ed25519 public key must be exactly 32bytes long');\n }\n this.#rawKey = key;\n this.#derKey = Ed25519PublicKey.derEncode(key);\n }\n\n public toDer(): DerEncodedPublicKey {\n return this.derKey;\n }\n\n public toRaw(): Uint8Array {\n return this.rawKey;\n }\n}\n\n/**\n * Ed25519KeyIdentity is an implementation of SignIdentity that uses Ed25519 keys. This class is used to sign and verify messages for an agent.\n */\nexport class Ed25519KeyIdentity extends SignIdentity {\n /**\n * Generate a new Ed25519KeyIdentity.\n * @param seed a 32-byte seed for the private key. If not provided, a random seed will be generated.\n * @returns Ed25519KeyIdentity\n */\n public static generate(seed?: Uint8Array): Ed25519KeyIdentity {\n if (seed && seed.length !== 32) {\n throw new Error('Ed25519 Seed needs to be 32 bytes long.');\n }\n if (!seed) seed = ed25519.utils.randomPrivateKey();\n // Check if the seed is all zeros\n if (uint8Equals(seed, new Uint8Array(new Array(32).fill(0)))) {\n console.warn(\n 'Seed is all zeros. This is not a secure seed. Please provide a seed with sufficient entropy if this is a production environment.',\n );\n }\n const sk = new Uint8Array(32);\n for (let i = 0; i < 32; i++) {\n sk[i] = seed[i];\n }\n\n const pk = ed25519.getPublicKey(sk);\n return Ed25519KeyIdentity.fromKeyPair(pk, sk);\n }\n\n public static fromParsedJson(obj: JsonnableEd25519KeyIdentity): Ed25519KeyIdentity {\n const [publicKeyDer, privateKeyRaw] = obj;\n return new Ed25519KeyIdentity(\n Ed25519PublicKey.fromDer(hexToBytes(publicKeyDer) as DerEncodedPublicKey),\n hexToBytes(privateKeyRaw),\n );\n }\n\n public static fromJSON(json: string): Ed25519KeyIdentity {\n const parsed = JSON.parse(json);\n if (Array.isArray(parsed)) {\n if (typeof parsed[0] === 'string' && typeof parsed[1] === 'string') {\n return this.fromParsedJson([parsed[0], parsed[1]]);\n } else {\n throw new Error('Deserialization error: JSON must have at least 2 items.');\n }\n }\n throw new Error(`Deserialization error: Invalid JSON type for string: ${JSON.stringify(json)}`);\n }\n\n public static fromKeyPair(publicKey: Uint8Array, privateKey: Uint8Array): Ed25519KeyIdentity {\n return new Ed25519KeyIdentity(Ed25519PublicKey.fromRaw(publicKey), privateKey);\n }\n\n public static fromSecretKey(secretKey: Uint8Array): Ed25519KeyIdentity {\n const publicKey = ed25519.getPublicKey(secretKey);\n return Ed25519KeyIdentity.fromKeyPair(publicKey, secretKey);\n }\n\n #publicKey: Ed25519PublicKey;\n #privateKey: Uint8Array;\n\n // `fromRaw` and `fromDer` should be used for instantiation, not this constructor.\n protected constructor(publicKey: PublicKey, privateKey: Uint8Array) {\n super();\n this.#publicKey = Ed25519PublicKey.from(publicKey);\n this.#privateKey = privateKey;\n }\n\n /**\n * Serialize this key to JSON.\n */\n public toJSON(): JsonnableEd25519KeyIdentity {\n return [bytesToHex(this.#publicKey.toDer()), bytesToHex(this.#privateKey)];\n }\n\n /**\n * Return a copy of the key pair.\n */\n public getKeyPair(): KeyPair {\n return {\n secretKey: this.#privateKey,\n publicKey: this.#publicKey,\n };\n }\n\n /**\n * Return the public key.\n */\n public getPublicKey(): Required<PublicKey> {\n return this.#publicKey;\n }\n\n /**\n * Signs a blob of data, with this identity's private key.\n * @param challenge - challenge to sign with this identity's secretKey, producing a signature\n */\n public async sign(challenge: Uint8Array): Promise<Signature> {\n // Some implementations of Ed25519 private keys append a public key to the end of the private key. We only want the private key.\n const signature = ed25519.sign(challenge, this.#privateKey.slice(0, 32));\n // add { __signature__: void; } to the signature to make it compatible with the agent\n\n Object.defineProperty(signature, '__signature__', {\n enumerable: false,\n value: undefined,\n });\n\n return signature as Signature;\n }\n\n /**\n * Verify\n * @param sig - signature to verify\n * @param msg - message to verify\n * @param pk - public key\n * @returns - true if the signature is valid, false otherwise\n */\n public static verify(\n sig: ArrayBuffer | Uint8Array | string,\n msg: ArrayBuffer | Uint8Array | string,\n pk: ArrayBuffer | Uint8Array | string,\n ) {\n const [signature, message, publicKey] = [sig, msg, pk].map(x => {\n if (typeof x === 'string') {\n x = hexToBytes(x);\n }\n return uint8FromBufLike(x);\n });\n return ed25519.verify(signature, message, publicKey);\n }\n}\n\ntype PublicKeyHex = string;\ntype SecretKeyHex = string;\nexport type JsonnableEd25519KeyIdentity = [PublicKeyHex, SecretKeyHex];\n", "import { type DerEncodedPublicKey, type PublicKey, type Signature, SignIdentity } from '#agent';\nimport { uint8FromBufLike } from '#candid';\n\n/**\n * Options used in a {@link ECDSAKeyIdentity}\n */\nexport type CryptoKeyOptions = {\n extractable?: boolean;\n keyUsages?: KeyUsage[];\n subtleCrypto?: SubtleCrypto;\n};\n\nexport class CryptoError extends Error {\n constructor(public readonly message: string) {\n super(message);\n Object.setPrototypeOf(this, CryptoError.prototype);\n }\n}\n\nexport interface DerCryptoKey extends CryptoKey {\n toDer: () => DerEncodedPublicKey;\n}\n\n/**\n * Utility method to ensure that a subtleCrypto implementation is provided or is available in the global context\n * @param subtleCrypto SubtleCrypto implementation\n * @returns subleCrypto\n */\nfunction _getEffectiveCrypto(subtleCrypto: CryptoKeyOptions['subtleCrypto']): SubtleCrypto {\n if (typeof global !== 'undefined' && global['crypto'] && global['crypto']['subtle']) {\n return global['crypto']['subtle'];\n }\n if (subtleCrypto) {\n return subtleCrypto;\n } else if (typeof crypto !== 'undefined' && crypto['subtle']) {\n return crypto.subtle;\n } else {\n throw new CryptoError(\n 'Global crypto was not available and none was provided. Please inlcude a SubtleCrypto implementation. See https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto',\n );\n }\n}\n\n/**\n * An identity interface that wraps an ECDSA keypair using the P-256 named curve. Supports DER-encoding and decoding for agent calls\n */\nexport class ECDSAKeyIdentity extends SignIdentity {\n /**\n * Generates a randomly generated identity for use in calls to the Internet Computer.\n * @param {CryptoKeyOptions} options optional settings\n * @param {CryptoKeyOptions['extractable']} options.extractable - whether the key should allow itself to be used. Set to false for maximum security.\n * @param {CryptoKeyOptions['keyUsages']} options.keyUsages - a list of key usages that the key can be used for\n * @param {CryptoKeyOptions['subtleCrypto']} options.subtleCrypto interface\n * @returns a {@link ECDSAKeyIdentity}\n */\n public static async generate(options?: CryptoKeyOptions): Promise<ECDSAKeyIdentity> {\n const { extractable = false, keyUsages = ['sign', 'verify'], subtleCrypto } = options ?? {};\n const effectiveCrypto = _getEffectiveCrypto(subtleCrypto);\n const keyPair = await effectiveCrypto.generateKey(\n {\n name: 'ECDSA',\n namedCurve: 'P-256',\n },\n extractable,\n keyUsages,\n );\n const derKey: DerEncodedPublicKey = uint8FromBufLike(\n await effectiveCrypto.exportKey('spki', keyPair.publicKey),\n );\n\n Object.assign(derKey, {\n __derEncodedPublicKey__: undefined,\n });\n\n return new this(keyPair, derKey, effectiveCrypto);\n }\n\n /**\n * generates an identity from a public and private key. Please ensure that you are generating these keys securely and protect the user's private key\n * @param keyPair a CryptoKeyPair\n * @param subtleCrypto - a SubtleCrypto interface in case one is not available globally\n * @returns an {@link ECDSAKeyIdentity}\n */\n public static async fromKeyPair(\n keyPair: CryptoKeyPair | { privateKey: CryptoKey; publicKey: CryptoKey },\n subtleCrypto?: SubtleCrypto,\n ): Promise<ECDSAKeyIdentity> {\n const effectiveCrypto = _getEffectiveCrypto(subtleCrypto);\n const derKey: DerEncodedPublicKey = uint8FromBufLike(\n await effectiveCrypto.exportKey('spki', keyPair.publicKey),\n );\n Object.assign(derKey, {\n __derEncodedPublicKey__: undefined,\n });\n return new ECDSAKeyIdentity(keyPair, derKey, effectiveCrypto);\n }\n\n protected _derKey: DerEncodedPublicKey;\n protected _keyPair: CryptoKeyPair;\n protected _subtleCrypto: SubtleCrypto;\n\n // `fromKeyPair` and `generate` should be used for instantiation, not this constructor.\n protected constructor(\n keyPair: CryptoKeyPair,\n derKey: DerEncodedPublicKey,\n subtleCrypto: SubtleCrypto,\n ) {\n super();\n this._keyPair = keyPair;\n this._derKey = derKey;\n this._subtleCrypto = subtleCrypto;\n }\n\n /**\n * Return the internally-used key pair.\n * @returns a CryptoKeyPair\n */\n public getKeyPair(): CryptoKeyPair {\n return this._keyPair;\n }\n\n /**\n * Return the public key.\n * @returns an {@link PublicKey & DerCryptoKey}\n */\n public getPublicKey(): PublicKey & DerCryptoKey {\n const derKey = this._derKey;\n const key: DerCryptoKey = Object.create(this._keyPair.publicKey);\n key.toDer = function () {\n return derKey;\n };\n\n return key;\n }\n\n /**\n * Signs a blob of data, with this identity's private key.\n * @param {Uint8Array} challenge - challenge to sign with this identity's secretKey, producing a signature\n * @returns {Promise<Signature>} signature\n */\n public async sign(challenge: Uint8Array): Promise<Signature> {\n const params: EcdsaParams = {\n name: 'ECDSA',\n hash: { name: 'SHA-256' },\n };\n const signature = uint8FromBufLike(\n await this._subtleCrypto.sign(params, this._keyPair.privateKey, challenge),\n );\n\n Object.assign(signature, {\n __signature__: undefined,\n });\n\n return signature as Signature;\n }\n}\n\nexport default ECDSAKeyIdentity;\n", "import { type Identity, type PublicKey } from '#agent';\nimport { Principal } from '#principal';\n\n/**\n * A partial delegated identity, representing a delegation chain and the public key that it targets\n */\nexport class PartialIdentity implements Identity {\n #inner: PublicKey;\n\n /**\n * The raw public key of this identity.\n */\n get rawKey(): Uint8Array | undefined {\n return this.#inner.rawKey;\n }\n\n /**\n * The DER-encoded public key of this identity.\n */\n get derKey(): Uint8Array | undefined {\n return this.#inner.derKey;\n }\n\n /**\n * The DER-encoded public key of this identity.\n */\n public toDer(): Uint8Array {\n return this.#inner.toDer();\n }\n\n /**\n * The inner {@link PublicKey} used by this identity.\n */\n public getPublicKey(): PublicKey {\n return this.#inner;\n }\n\n /**\n * The {@link Principal} of this identity.\n */\n public getPrincipal(): Principal {\n if (!this.#inner.rawKey) {\n throw new Error('Cannot get principal from a public key without a raw key.');\n }\n return Principal.fromUint8Array(new Uint8Array(this.#inner.rawKey));\n }\n\n /**\n * Required for the Identity interface, but cannot implemented for just a public key.\n */\n public transformRequest(): Promise<never> {\n return Promise.reject(\n 'Not implemented. You are attempting to use a partial identity to sign calls, but this identity only has access to the public key.To sign calls, use a DelegationIdentity instead.',\n );\n }\n\n constructor(inner: PublicKey) {\n this.#inner = inner;\n }\n}\n", "import {\n type DerEncodedPublicKey,\n type HttpAgentRequest,\n type PublicKey,\n requestIdOf,\n type Signature,\n SignIdentity,\n IC_REQUEST_DOMAIN_SEPARATOR,\n IC_REQUEST_AUTH_DELEGATION_DOMAIN_SEPARATOR,\n ToCborValue,\n} from '#agent';\nimport { Principal } from '#principal';\nimport { PartialIdentity } from './partial.ts';\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils';\n\n/**\n * Safe wrapper around bytesToHex that handles ArrayBuffer/Uint8Array type conversion.\n * Required because @noble/hashes v1.8+ strictly expects Uint8Array inputs.\n * @param data The binary data to convert to hexadecimal string (ArrayBuffer, Uint8Array, or ArrayLike<number>)\n */\nfunction safeBytesToHex(data: ArrayBuffer | Uint8Array | ArrayLike<number>): string {\n if (data instanceof Uint8Array) {\n return bytesToHex(data);\n }\n return bytesToHex(new Uint8Array(data));\n}\n\nfunction _parseBlob(value: unknown): Uint8Array {\n if (typeof value !== 'string' || value.length < 64) {\n throw new Error('Invalid public key.');\n }\n\n return hexToBytes(value);\n}\n\n/**\n * A single delegation object that is signed by a private key. This is constructed by\n * `DelegationChain.create()`.\n *\n * {@see DelegationChain}\n */\nexport class Delegation implements ToCborValue {\n constructor(\n public readonly pubkey: Uint8Array,\n public readonly expiration: bigint,\n public readonly targets?: Principal[],\n ) {}\n\n public toCborValue() {\n return {\n pubkey: this.pubkey,\n expiration: this.expiration,\n ...(this.targets && {\n targets: this.targets,\n }),\n };\n }\n\n public toJSON(): JsonnableDelegation {\n // every string should be hex and once-de-hexed,\n // discoverable what it is (e.g. de-hex to get JSON with a 'type' property, or de-hex to DER\n // with an OID). After de-hex, if it's not obvious what it is, it's an ArrayBuffer.\n return {\n expiration: this.expiration.toString(16),\n pubkey: safeBytesToHex(this.pubkey),\n ...(this.targets && { targets: this.targets.map(p => p.toHex()) }),\n };\n }\n}\n\n/**\n * Type of ReturnType<Delegation.toJSON>.\n * The goal here is to stringify all non-JSON-compatible types to some bytes representation we can\n * stringify as hex.\n * (Hex shouldn't be ambiguous ever, because you can encode as DER with semantic OIDs).\n */\ninterface JsonnableDelegation {\n // A BigInt of Nanoseconds since epoch as hex\n expiration: string;\n // Hexadecimal representation of the DER public key.\n pubkey: string;\n // Array of strings, where each string is hex of principal blob (*NOT* textual representation).\n targets?: string[];\n}\n\n/**\n * A signed delegation, which lends its identity to the public key in the delegation\n * object. This is constructed by `DelegationChain.create()`.\n *\n * {@see DelegationChain}\n */\nexport interface SignedDelegation {\n delegation: Delegation;\n signature: Signature;\n}\n\n/**\n * Sign a single delegation object for a period of time.\n * @param from The identity that lends its delegation.\n * @param to The identity that receives the delegation.\n * @param expiration An expiration date for this delegation.\n * @param targets Limit this delegation to the target principals.\n */\nasync function _createSingleDelegation(\n from: SignIdentity,\n to: PublicKey,\n expiration: Date,\n targets?: Principal[],\n): Promise<SignedDelegation> {\n const delegation: Delegation = new Delegation(\n to.toDer(),\n BigInt(+expiration) * BigInt(1000000), // In nanoseconds.\n targets,\n );\n // The signature is calculated by signing the concatenation of the domain separator\n // and the message.\n // Note: To ensure Safari treats this as a user gesture, ensure to not use async methods\n // besides the actualy webauthn functionality (such as `sign`). Safari will de-register\n // a user gesture if you await an async call thats not fetch, xhr, or setTimeout.\n const challenge = new Uint8Array([\n ...IC_REQUEST_AUTH_DELEGATION_DOMAIN_SEPARATOR,\n ...new Uint8Array(requestIdOf({ ...delegation })),\n ]);\n const signature = await from.sign(challenge);\n\n return {\n delegation,\n signature,\n };\n}\n\nexport interface JsonnableDelegationChain {\n publicKey: string;\n delegations: Array<{\n signature: string;\n delegation: {\n pubkey: string;\n expiration: string;\n targets?: string[];\n };\n }>;\n}\n\n/**\n * A chain of delegations. This is JSON Serializable.\n * This is the object to serialize and pass to a DelegationIdentity. It does not keep any\n * private keys.\n */\nexport class DelegationChain {\n /**\n * Create a delegation chain between two (or more) keys. By default, the expiration time\n * will be very short (15 minutes).\n *\n * To build a chain of more than 2 identities, this function needs to be called multiple times,\n * passing the previous delegation chain into the options argument. For example:\n * @example\n * const rootKey = createKey();\n * const middleKey = createKey();\n * const bottomeKey = createKey();\n *\n * const rootToMiddle = await DelegationChain.create(\n * root, middle.getPublicKey(), Date.parse('2100-01-01'),\n * );\n * const middleToBottom = await DelegationChain.create(\n * middle, bottom.getPublicKey(), Date.parse('2100-01-01'), { previous: rootToMiddle },\n * );\n *\n * // We can now use a delegation identity that uses the delegation above:\n * const identity = DelegationIdentity.fromDelegation(bottomKey, middleToBottom);\n * @param from The identity that will delegate.\n * @param to The identity that gets delegated. It can now sign messages as if it was the\n * identity above.\n * @param expiration The length the delegation is valid. By default, 15 minutes from calling\n * this function.\n * @param options A set of options for this delegation. expiration and previous\n * @param options.previous - Another DelegationChain that this chain should start with.\n * @param options.targets - targets that scope the delegation (e.g. Canister Principals)\n */\n public static async create(\n from: SignIdentity,\n to: PublicKey,\n expiration: Date = new Date(Date.now() + 15 * 60 * 1000),\n options: {\n previous?: DelegationChain;\n targets?: Principal[];\n } = {},\n ): Promise<DelegationChain> {\n const delegation = await _createSingleDelegation(from, to, expiration, options.targets);\n return new DelegationChain(\n [...(options.previous?.delegations || []), delegation],\n options.previous?.publicKey || from.getPublicKey().toDer(),\n );\n }\n\n /**\n * Creates a DelegationChain object from a JSON string.\n * @param json The JSON string to parse.\n */\n public static fromJSON(json: string | JsonnableDelegationChain): DelegationChain {\n const { publicKey, delegations } = typeof json === 'string' ? JSON.parse(json) : json;\n if (!Array.isArray(delegations)) {\n throw new Error('Invalid delegations.');\n }\n\n const parsedDelegations: SignedDelegation[] = delegations.map(signedDelegation => {\n const { delegation, signature } = signedDelegation;\n const { pubkey, expiration, targets } = delegation;\n if (targets !== undefined && !Array.isArray(targets)) {\n throw new Error('Invalid targets.');\n }\n\n return {\n delegation: new Delegation(\n _parseBlob(pubkey),\n BigInt('0x' + expiration), // expiration in JSON is an hexa string (See toJSON() below).\n targets &&\n targets.map((t: unknown) => {\n if (typeof t !== 'string') {\n throw new Error('Invalid target.');\n }\n return Principal.fromHex(t);\n }),\n ),\n signature: _parseBlob(signature) as Signature,\n };\n });\n\n return new this(parsedDelegations, _parseBlob(publicKey) as DerEncodedPublicKey);\n }\n\n /**\n * Creates a DelegationChain object from a list of delegations and a DER-encoded public key.\n * @param delegations The list of delegations.\n * @param publicKey The DER-encoded public key of the key-pair signing the first delegation.\n */\n public static fromDelegations(\n delegations: SignedDelegation[],\n publicKey: DerEncodedPublicKey,\n ): DelegationChain {\n return new this(delegations, publicKey);\n }\n\n protected constructor(\n public readonly delegations: SignedDelegation[],\n public readonly publicKey: DerEncodedPublicKey,\n ) {}\n\n public toJSON(): JsonnableDelegationChain {\n return {\n delegations: this.delegations.map(signedDelegation => {\n const { delegation, signature } = signedDelegation;\n const { targets } = delegation;\n return {\n delegation: {\n expiration: delegation.expiration.toString(16),\n pubkey: safeBytesToHex(delegation.pubkey),\n ...(targets && {\n targets: targets.map(t => t.toHex()),\n }),\n },\n signature: safeBytesToHex(signature),\n };\n }),\n publicKey: safeBytesToHex(this.publicKey),\n };\n }\n}\n\n/**\n * An Identity that adds delegation to a request. Everywhere in this class, the name\n * innerKey refers to the SignIdentity that is being used to sign the requests, while\n * originalKey is the identity that is being borrowed. More identities can be used\n * in the middle to delegate.\n */\nexport class DelegationIdentity extends SignIdentity {\n /**\n * Create a delegation without having access to delegateKey.\n * @param key The key used to sign the requests.\n * @param delegation A delegation object created using `createDelegation`.\n */\n public static fromDelegation(\n key: Pick<SignIdentity, 'sign'>,\n delegation: DelegationChain,\n ): DelegationIdentity {\n return new this(key, delegation);\n }\n\n protected constructor(\n private _inner: Pick<SignIdentity, 'sign'>,\n private _delegation: DelegationChain,\n ) {\n super();\n }\n\n public getDelegation(): DelegationChain {\n return this._delegation;\n }\n\n public getPublicKey(): PublicKey {\n return {\n derKey: this._delegation.publicKey,\n toDer: () => this._delegation.publicKey,\n };\n }\n public sign(blob: Uint8Array): Promise<Signature> {\n return this._inner.sign(blob);\n }\n\n public async transformRequest(request: HttpAgentRequest): Promise<unknown> {\n const { body, ...fields } = request;\n const requestId = await requestIdOf(body);\n return {\n ...fields,\n body: {\n content: body,\n sender_sig: await this.sign(\n new Uint8Array([...IC_REQUEST_DOMAIN_SEPARATOR, ...new Uint8Array(requestId)]),\n ),\n sender_delegation: this._delegation.delegations,\n sender_pubkey: this._delegation.publicKey,\n },\n };\n }\n}\n\n/**\n * A partial delegated identity, representing a delegation chain and the public key that it targets\n */\nexport class PartialDelegationIdentity extends PartialIdentity {\n #delegation: DelegationChain;\n\n /**\n * The Delegation Chain of this identity.\n */\n get delegation(): DelegationChain {\n return this.#delegation;\n }\n\n private constructor(inner: PublicKey, delegation: DelegationChain) {\n super(inner);\n this.#delegation = delegation;\n }\n\n /**\n * Create a {@link PartialDelegationIdentity} from a {@link PublicKey} and a {@link DelegationChain}.\n * @param key The {@link PublicKey} to delegate to.\n * @param delegation a {@link DelegationChain} targeting the inner key.\n */\n public static fromDelegation(key: PublicKey, delegation: DelegationChain) {\n return new PartialDelegationIdentity(key, delegation);\n }\n}\n\n/**\n * List of things to check for a delegation chain validity.\n */\nexport interface DelegationValidChecks {\n /**\n * Check that the scope is amongst the scopes that this delegation has access to.\n */\n scope?: Principal | string | Array<Principal | string>;\n}\n\n/**\n * Analyze a DelegationChain and validate that it's valid, ie. not expired and apply to the\n * scope.\n * @param chain The chain to validate.\n * @param checks Various checks to validate on the chain.\n */\nexport function isDelegationValid(chain: DelegationChain, checks?: DelegationValidChecks): boolean {\n // Verify that the no delegation is expired. If any are in the chain, returns false.\n for (const { delegation } of chain.delegations) {\n // prettier-ignore\n if (+new Date(Number(delegation.expiration / BigInt(1000000))) <= +Date.now()) {\n return false;\n }\n }\n\n // Check the scopes.\n const scopes: Principal[] = [];\n const maybeScope = checks?.scope;\n if (maybeScope) {\n if (Array.isArray(maybeScope)) {\n scopes.push(...maybeScope.map(s => (typeof s === 'string' ? Principal.fromText(s) : s)));\n } else {\n scopes.push(typeof maybeScope === 'string' ? Principal.fromText(maybeScope) : maybeScope);\n }\n }\n\n for (const s of scopes) {\n const scope = s.toText();\n for (const { delegation } of chain.delegations) {\n if (delegation.targets === undefined) {\n continue;\n }\n\n let none = true;\n for (const target of delegation.targets) {\n if (target.toText() === scope) {\n none = false;\n break;\n }\n }\n if (none) {\n return false;\n }\n }\n }\n\n return true;\n}\n", "type IdleCB = () => unknown;\n\nexport type IdleManagerOptions = {\n /**\n * Callback after the user has gone idle\n */\n onIdle?: IdleCB;\n /**\n * timeout in ms\n * @default 30 minutes [600_000]\n */\n idleTimeout?: number;\n /**\n * capture scroll events\n * @default false\n */\n captureScroll?: boolean;\n /**\n * scroll debounce time in ms\n * @default 100\n */\n scrollDebounce?: number;\n};\n\nconst events = ['mousedown', 'mousemove', 'keydown', 'touchstart', 'wheel'];\n\n/**\n * Detects if the user has been idle for a duration of `idleTimeout` ms, and calls `onIdle` and registered callbacks.\n * By default, the IdleManager will log a user out after 10 minutes of inactivity.\n * To override these defaults, you can pass an `onIdle` callback, or configure a custom `idleTimeout` in milliseconds\n */\nexport class IdleManager {\n callbacks: IdleCB[] = [];\n idleTimeout: IdleManagerOptions['idleTimeout'] = 10 * 60 * 1000;\n timeoutID?: number = undefined;\n\n /**\n * Creates an {@link IdleManager}\n * @param {IdleManagerOptions} options Optional configuration\n * @see {@link IdleManagerOptions}\n * @param options.onIdle Callback once user has been idle. Use to prompt for fresh login, and use `Actor.agentOf(your_actor).invalidateIdentity()` to protect the user\n * @param options.idleTimeout timeout in ms\n * @param options.captureScroll capture scroll events\n * @param options.scrollDebounce scroll debounce time in ms\n */\n public static create(\n options: {\n /**\n * Callback after the user has gone idle\n * @see {@link IdleCB}\n */\n onIdle?: () => unknown;\n /**\n * timeout in ms\n * @default 10 minutes [600_000]\n */\n idleTimeout?: number;\n /**\n * capture scroll events\n * @default false\n */\n captureScroll?: boolean;\n /**\n * scroll debounce time in ms\n * @default 100\n */\n scrollDebounce?: number;\n } = {},\n ): IdleManager {\n return new IdleManager(options);\n }\n\n /**\n * @protected\n * @param options {@link IdleManagerOptions}\n */\n protected constructor(options: IdleManagerOptions = {}) {\n const { onIdle, idleTimeout = 10 * 60 * 1000 } = options || {};\n\n this.callbacks = onIdle ? [onIdle] : [];\n this.idleTimeout = idleTimeout;\n\n const _resetTimer = this._resetTimer.bind(this);\n\n window.addEventListener('load', _resetTimer, true);\n\n events.forEach((name) => {\n document.addEventListener(name, _resetTimer, true);\n });\n\n const debounce = (func: (...args: unknown[]) => void, wait: number) => {\n let timeout: number | undefined;\n return (...args: unknown[]) => {\n const context = this;\n const later = () => {\n timeout = undefined;\n func.apply(context, args);\n };\n clearTimeout(timeout);\n timeout = window.setTimeout(later, wait);\n };\n };\n\n if (options?.captureScroll) {\n // debounce scroll events\n const scroll = debounce(_resetTimer, options?.scrollDebounce ?? 100);\n window.addEventListener('scroll', scroll, true);\n }\n\n _resetTimer();\n }\n\n /**\n * @param {IdleCB} callback function to be called when user goes idle\n */\n public registerCallback(callback: IdleCB): void {\n this.callbacks.push(callback);\n }\n\n /**\n * Cleans up the idle manager and its listeners\n */\n public exit(): void {\n clearTimeout(this.timeoutID);\n window.removeEventListener('load', this._resetTimer, true);\n\n const _resetTimer = this._resetTimer.bind(this);\n events.forEach((name) => {\n document.removeEventListener(name, _resetTimer, true);\n });\n this.callbacks.forEach((cb) => {\n cb();\n });\n }\n\n /**\n * Resets the timeouts during cleanup\n */\n _resetTimer(): void {\n const exit = this.exit.bind(this);\n window.clearTimeout(this.timeoutID);\n this.timeoutID = window.setTimeout(exit, this.idleTimeout);\n }\n}\n", "const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n", "import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);\n });\n }\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event.newVersion, event));\n }\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking) {\n db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));\n }\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event));\n }\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n", "import { type IDBPDatabase, openDB } from 'idb';\nimport { DB_VERSION, KEY_STORAGE_DELEGATION, KEY_STORAGE_KEY } from './storage.ts';\n\ntype Database = IDBPDatabase<unknown>;\ntype IDBValidKey = string | number | Date | BufferSource | IDBValidKey[];\nconst AUTH_DB_NAME = 'auth-client-db';\nconst OBJECT_STORE_NAME = 'ic-keyval';\n\nconst _openDbStore = async (\n dbName = AUTH_DB_NAME,\n storeName = OBJECT_STORE_NAME,\n version: number,\n) => {\n // Clear legacy stored delegations\n if (globalThis.localStorage?.getItem(KEY_STORAGE_DELEGATION)) {\n globalThis.localStorage.removeItem(KEY_STORAGE_DELEGATION);\n globalThis.localStorage.removeItem(KEY_STORAGE_KEY);\n }\n return await openDB(dbName, version, {\n upgrade: (database) => {\n if (database.objectStoreNames.contains(storeName)) {\n database.clear(storeName);\n }\n database.createObjectStore(storeName);\n },\n });\n};\n\nasync function _getValue<T>(\n db: Database,\n storeName: string,\n key: IDBValidKey,\n): Promise<T | undefined> {\n return await db.get(storeName, key);\n}\n\nasync function _setValue<T>(\n db: Database,\n storeName: string,\n key: IDBValidKey,\n value: T,\n): Promise<IDBValidKey> {\n return await db.put(storeName, value, key);\n}\n\nasync function _removeValue(db: Database, storeName: string, key: IDBValidKey): Promise<void> {\n return await db.delete(storeName, key);\n}\n\nexport type DBCreateOptions = {\n dbName?: string;\n storeName?: string;\n version?: number;\n};\n\n/**\n * Simple Key Value store\n * Defaults to `'auth-client-db'` with an object store of `'ic-keyval'`\n */\nexport class IdbKeyVal {\n /**\n * @param {DBCreateOptions} options - DBCreateOptions\n * @param {DBCreateOptions['dbName']} options.dbName name for the indexeddb database\n * @default\n * @param {DBCreateOptions['storeName']} options.storeName name for the indexeddb Data Store\n * @default\n * @param {DBCreateOptions['version']} options.version version of the database. Increment to safely upgrade\n */\n public static async create(options?: DBCreateOptions): Promise<IdbKeyVal> {\n const {\n dbName = AUTH_DB_NAME,\n storeName = OBJECT_STORE_NAME,\n version = DB_VERSION,\n } = options ?? {};\n const db = await _openDbStore(dbName, storeName, version);\n return new IdbKeyVal(db, storeName);\n }\n\n // Do not use - instead prefer create\n private constructor(\n private _db: Database,\n private _storeName: string,\n ) {}\n\n /**\n * Basic setter\n * @param {IDBValidKey} key string | number | Date | BufferSource | IDBValidKey[]\n * @param value value to set\n * @returns void\n */\n public async set<T>(key: IDBValidKey, value: T) {\n return await _setValue<T>(this._db, this._storeName, key, value);\n }\n /**\n * Basic getter\n * Pass in a type T for type safety if you know the type the value will have if it is found\n * @param {IDBValidKey} key string | number | Date | BufferSource | IDBValidKey[]\n * @returns `Promise<T | null>`\n * @example\n * await get<string>('exampleKey') -> 'exampleValue'\n */\n public async get<T>(key: IDBValidKey): Promise<T | null> {\n return (await _getValue<T>(this._db, this._storeName, key)) ?? null;\n }\n\n /**\n * Remove a key\n * @param key {@link IDBValidKey}\n * @returns void\n */\n public async remove(key: IDBValidKey) {\n return await _removeValue(this._db, this._storeName, key);\n }\n}\n", "import { type DBCreateOptions, IdbKeyVal } from './db.ts';\n\nexport const KEY_STORAGE_KEY = 'identity';\nexport const KEY_STORAGE_DELEGATION = 'delegation';\nexport const KEY_VECTOR = 'iv';\n// Increment if any fields are modified\nexport const DB_VERSION = 1;\n\nexport type StoredKey = string | CryptoKeyPair;\n\n/**\n * Interface for persisting user authentication data\n */\nexport interface AuthClientStorage {\n get(key: string): Promise<StoredKey | null>;\n\n set(key: string, value: StoredKey): Promise<void>;\n\n remove(key: string): Promise<void>;\n}\n\n/**\n * Legacy implementation of AuthClientStorage, for use where IndexedDb is not available\n */\nexport class LocalStorage implements AuthClientStorage {\n constructor(\n public readonly prefix = 'ic-',\n private readonly _localStorage?: Storage,\n ) {}\n\n public get(key: string): Promise<string | null> {\n return Promise.resolve(this._getLocalStorage().getItem(this.prefix + key));\n }\n\n public set(key: string, value: string): Promise<void> {\n this._getLocalStorage().setItem(this.prefix + key, value);\n return Promise.resolve();\n }\n\n public remove(key: string): Promise<void> {\n this._getLocalStorage().removeItem(this.prefix + key);\n return Promise.resolve();\n }\n\n private _getLocalStorage() {\n if (this._localStorage) {\n return this._localStorage;\n }\n\n const ls = globalThis.localStorage;\n if (!ls) {\n throw new Error('Could not find local storage.');\n }\n\n return ls;\n }\n}\n\n/**\n * IdbStorage is an interface for simple storage of string key-value pairs built on {@link IdbKeyVal}\n *\n * It replaces {@link LocalStorage}\n * @see implements {@link AuthClientStorage}\n */\nexport class IdbStorage implements AuthClientStorage {\n #options: DBCreateOptions;\n\n /**\n * @param options - DBCreateOptions\n * @param options.dbName - name for the indexeddb database\n * @param options.storeName - name for the indexeddb Data Store\n * @param options.version - version of the database. Increment to safely upgrade\n * @example\n * ```ts\n * const storage = new IdbStorage({ dbName: 'my-db', storeName: 'my-store', version: 2 });\n * ```\n */\n constructor(options?: DBCreateOptions) {\n this.#options = options ?? {};\n }\n\n // Initializes a KeyVal on first request\n private initializedDb: IdbKeyVal | undefined;\n get _db(): Promise<IdbKeyVal> {\n return new Promise((resolve, reject) => {\n if (this.initializedDb) {\n resolve(this.initializedDb);\n return;\n }\n IdbKeyVal.create(this.#options)\n .then((db) => {\n this.initializedDb = db;\n resolve(db);\n })\n .catch(reject);\n });\n }\n\n public async get<T = string>(key: string): Promise<T | null> {\n const db = await this._db;\n return await db.get<T>(key);\n // return (await db.get<string>(key)) ?? null;\n }\n\n public async set<T = string>(key: string, value: T): Promise<void> {\n const db = await this._db;\n await db.set(key, value);\n }\n\n public async remove(key: string): Promise<void> {\n const db = await this._db;\n await db.remove(key);\n }\n}\n", "import {\n AnonymousIdentity,\n type DerEncodedPublicKey,\n type Identity,\n type Signature,\n type SignIdentity,\n} from '@icp-sdk/core/agent';\nimport {\n Delegation,\n DelegationChain,\n DelegationIdentity,\n ECDSAKeyIdentity,\n Ed25519KeyIdentity,\n isDelegationValid,\n PartialDelegationIdentity,\n type PartialIdentity,\n} from '@icp-sdk/core/identity';\nimport type { Principal } from '@icp-sdk/core/principal';\nimport { IdleManager, type IdleManagerOptions } from './idle-manager.ts';\nimport {\n type AuthClientStorage,\n IdbStorage,\n KEY_STORAGE_DELEGATION,\n KEY_STORAGE_KEY,\n KEY_VECTOR,\n LocalStorage,\n type StoredKey,\n} from './storage.ts';\n\nconst NANOSECONDS_PER_SECOND = BigInt(1_000_000_000);\nconst SECONDS_PER_HOUR = BigInt(3_600);\nconst NANOSECONDS_PER_HOUR = NANOSECONDS_PER_SECOND * SECONDS_PER_HOUR;\n\nconst IDENTITY_PROVIDER_DEFAULT = 'https://identity.internetcomputer.org';\nconst IDENTITY_PROVIDER_ENDPOINT = '#authorize';\n\nconst DEFAULT_MAX_TIME_TO_LIVE = BigInt(8) * NANOSECONDS_PER_HOUR;\n\nconst ECDSA_KEY_LABEL = 'ECDSA';\nconst ED25519_KEY_LABEL = 'Ed25519';\ntype BaseKeyType = typeof ECDSA_KEY_LABEL | typeof ED25519_KEY_LABEL;\n\nconst INTERRUPT_CHECK_INTERVAL = 500;\n\nexport const ERROR_USER_INTERRUPT = 'UserInterrupt';\n\n/**\n * List of options for creating an {@link AuthClient}.\n */\nexport interface AuthClientCreateOptions {\n /**\n * An {@link SignIdentity} or {@link PartialIdentity} to authenticate via delegation.\n */\n identity?: SignIdentity | PartialIdentity;\n /**\n * Optional storage with get, set, and remove. Uses {@link IdbStorage} by default.\n * @see {@link AuthClientStorage}\n */\n storage?: AuthClientStorage;\n\n /**\n * Type to use for the base key.\n *\n * If you are using a custom storage provider that does not support CryptoKey storage,\n * you should use `Ed25519` as the key type, as it can serialize to a string.\n * @default 'ECDSA'\n */\n keyType?: BaseKeyType;\n\n /**\n * Options to handle idle timeouts\n * @default after 10 minutes, invalidates the identity\n */\n idleOptions?: IdleOptions;\n\n /**\n * Options to handle login, passed to the login method\n */\n loginOptions?: AuthClientLoginOptions;\n}\n\nexport interface IdleOptions extends IdleManagerOptions {\n /**\n * Disables idle functionality for {@link IdleManager}\n * @default false\n */\n disableIdle?: boolean;\n\n /**\n * Disables default idle behavior - call logout & reload window\n * @default false\n */\n disableDefaultIdleCallback?: boolean;\n}\n\nexport type OnSuccessFunc =\n | (() => void | Promise<void>)\n | ((message: InternetIdentityAuthResponseSuccess) => void | Promise<void>);\n\nexport type OnErrorFunc = (error?: string) => void | Promise<void>;\n\nexport interface AuthClientLoginOptions {\n /**\n * Identity provider\n * @default \"https://identity.internetcomputer.org\"\n */\n identityProvider?: string | URL;\n /**\n * Expiration of the authentication in nanoseconds\n * @default BigInt(8) hours * BigInt(3_600_000_000_000) nanoseconds\n */\n maxTimeToLive?: bigint;\n /**\n * If present, indicates whether or not the Identity Provider should allow the user to authenticate and/or register using a temporary key/PIN identity. Authenticating dapps may want to prevent users from using Temporary keys/PIN identities because Temporary keys/PIN identities are less secure than Passkeys (webauthn credentials) and because Temporary keys/PIN identities generally only live in a browser database (which may get cleared by the browser/OS).\n */\n allowPinAuthentication?: boolean;\n /**\n * Origin for Identity Provider to use while generating the delegated identity. For II, the derivation origin must authorize this origin by setting a record at `<derivation-origin>/.well-known/ii-alternative-origins`.\n * @see https://github.com/dfinity/internet-identity/blob/main/docs/internet-identity-spec.adoc\n */\n derivationOrigin?: string | URL;\n /**\n * Auth Window feature config string\n * @example \"toolbar=0,location=0,menubar=0,width=500,height=500,left=100,top=100\"\n */\n windowOpenerFeatures?: string;\n /**\n * Callback once login has completed\n */\n onSuccess?: OnSuccessFunc;\n /**\n * Callback in case authentication fails\n */\n onError?: OnErrorFunc;\n /**\n * Extra values to be passed in the login request during the authorize-ready phase\n */\n customValues?: Record<string, unknown>;\n}\n\ninterface InternetIdentityAuthRequest {\n kind: 'authorize-client';\n sessionPublicKey: Uint8Array;\n maxTimeToLive?: bigint;\n allowPinAuthentication?: boolean;\n derivationOrigin?: string;\n}\n\nexport interface InternetIdentityAuthResponseSuccess {\n kind: 'authorize-client-success';\n delegations: {\n delegation: {\n pubkey: Uint8Array;\n expiration: bigint;\n targets?: Principal[];\n };\n signature: Uint8Array;\n }[];\n userPublicKey: Uint8Array;\n authnMethod: 'passkey' | 'pin' | 'recovery';\n}\n\ninterface AuthReadyMessage {\n kind: 'authorize-ready';\n}\n\ninterface AuthResponseSuccess {\n kind: 'authorize-client-success';\n delegations: {\n delegation: {\n pubkey: Uint8Array;\n expiration: bigint;\n targets?: Principal[];\n };\n signature: Uint8Array;\n }[];\n userPublicKey: Uint8Array;\n authnMethod: 'passkey' | 'pin' | 'recovery';\n}\n\ninterface AuthResponseFailure {\n kind: 'authorize-client-failure';\n text: string;\n}\n\ntype IdentityServiceResponseMessage = AuthReadyMessage | AuthResponse;\ntype AuthResponse = AuthResponseSuccess | AuthResponseFailure;\n\n/**\n * Tool to manage authentication and identity\n * @see {@link AuthClient}\n */\nexport class AuthClient {\n /**\n * Create an AuthClient to manage authentication and identity\n * @param {AuthClientCreateOptions} options - Options for creating an {@link AuthClient}\n * @see {@link AuthClientCreateOptions}\n * @param options.identity Optional Identity to use as the base\n * @see {@link SignIdentity}\n * @param options.storage Storage mechanism for delegation credentials\n * @see {@link AuthClientStorage}\n * @param options.keyType Type of key to use for the base key\n * @param {IdleOptions} options.idleOptions Configures an {@link IdleManager}\n * @see {@link IdleOptions}\n * Default behavior is to clear stored identity and reload the page when a user goes idle, unless you set the disableDefaultIdleCallback flag or pass in a custom idle callback.\n * @example\n * const authClient = await AuthClient.create({\n * idleOptions: {\n * disableIdle: true\n * }\n * })\n */\n public static async create(options: AuthClientCreateOptions = {}): Promise<AuthClient> {\n const storage = options.storage ?? new IdbStorage();\n const keyType = options.keyType ?? ECDSA_KEY_LABEL;\n\n let key: null | SignIdentity | PartialIdentity = null;\n if (options.identity) {\n key = options.identity;\n } else {\n let maybeIdentityStorage = await storage.get(KEY_STORAGE_KEY);\n if (!maybeIdentityStorage) {\n // Attempt to migrate from localstorage\n try {\n const fallbackLocalStorage = new LocalStorage();\n const localChain = await fallbackLocalStorage.get(KEY_STORAGE_DELEGATION);\n const localKey = await fallbackLocalStorage.get(KEY_STORAGE_KEY);\n // not relevant for Ed25519\n if (localChain && localKey && keyType === ECDSA_KEY_LABEL) {\n console.log('Discovered an identity stored in localstorage. Migrating to IndexedDB');\n await storage.set(KEY_STORAGE_DELEGATION, localChain);\n await storage.set(KEY_STORAGE_KEY, localKey);\n\n maybeIdentityStorage = localChain;\n // clean up\n await fallbackLocalStorage.remove(KEY_STORAGE_DELEGATION);\n await fallbackLocalStorage.remove(KEY_STORAGE_KEY);\n }\n } catch (error) {\n console.error(`error while attempting to recover localstorage: ${error}`);\n }\n }\n if (maybeIdentityStorage) {\n try {\n if (typeof maybeIdentityStorage === 'object') {\n if (keyType === ED25519_KEY_LABEL && typeof maybeIdentityStorage === 'string') {\n key = Ed25519KeyIdentity.fromJSON(maybeIdentityStorage);\n } else {\n key = await ECDSAKeyIdentity.fromKeyPair(maybeIdentityStorage);\n }\n } else if (typeof maybeIdentityStorage === 'string') {\n // This is a legacy identity, which is a serialized Ed25519KeyIdentity.\n key = Ed25519KeyIdentity.fromJSON(maybeIdentityStorage);\n }\n } catch {\n // Ignore this, this means that the localStorage value isn't a valid Ed25519KeyIdentity or ECDSAKeyIdentity\n // serialization.\n }\n }\n }\n\n let identity: SignIdentity | PartialIdentity = new AnonymousIdentity() as PartialIdentity;\n let chain: null | DelegationChain = null;\n if (key) {\n try {\n const chainStorage = await storage.get(KEY_STORAGE_DELEGATION);\n if (typeof chainStorage === 'object' && chainStorage !== null) {\n throw new Error(\n 'Delegation chain is incorrectly stored. A delegation chain should be stored as a string.',\n );\n }\n\n if (options.identity) {\n identity = options.identity;\n } else if (chainStorage) {\n chain = DelegationChain.fromJSON(chainStorage);\n\n // Verify that the delegation isn't expired.\n if (!isDelegationValid(chain)) {\n await _deleteStorage(storage);\n key = null;\n } else {\n // If the key is a public key, then we create a PartialDelegationIdentity.\n if ('toDer' in key) {\n identity = PartialDelegationIdentity.fromDelegation(key, chain);\n // otherwise, we create a DelegationIdentity.\n } else {\n identity = DelegationIdentity.fromDelegation(key, chain);\n }\n }\n }\n } catch (e) {\n console.error(e);\n // If there was a problem loading the chain, delete the key.\n await _deleteStorage(storage);\n key = null;\n }\n }\n let idleManager: IdleManager | undefined;\n if (options.idleOptions?.disableIdle) {\n idleManager = undefined;\n }\n // if there is a delegation chain or provided identity, setup idleManager\n else if (chain || options.identity) {\n idleManager = IdleManager.create(options.idleOptions);\n }\n\n if (!key) {\n // Create a new key (whether or not one was in storage).\n if (keyType === ED25519_KEY_LABEL) {\n key = Ed25519KeyIdentity.generate();\n } else {\n if (options.storage && keyType === ECDSA_KEY_LABEL) {\n console.warn(\n `You are using a custom storage provider that may not support CryptoKey storage. If you are using a custom storage provider that does not support CryptoKey storage, you should use '${ED25519_KEY_LABEL}' as the key type, as it can serialize to a string`,\n );\n }\n key = await ECDSAKeyIdentity.generate();\n }\n await persistKey(storage, key);\n }\n\n return new AuthClient(identity, key, chain, storage, idleManager, options);\n }\n\n protected constructor(\n private _identity: Identity | PartialIdentity,\n private _key: SignIdentity | PartialIdentity,\n private _chain: DelegationChain | null,\n private _storage: AuthClientStorage,\n public idleManager: IdleManager | undefined,\n private _createOptions: AuthClientCreateOptions | undefined,\n // A handle on the IdP window.\n private _idpWindow?: Window,\n // The event handler for processing events from the IdP.\n private _eventHandler?: (event: MessageEvent) => void,\n ) {\n this._registerDefaultIdleCallback();\n }\n\n private _registerDefaultIdleCallback() {\n const idleOptions = this._createOptions?.idleOptions;\n /**\n * Default behavior is to clear stored identity and reload the page.\n * By either setting the disableDefaultIdleCallback flag or passing in a custom idle callback, we will ignore this config\n */\n if (!idleOptions?.onIdle && !idleOptions?.disableDefaultIdleCallback) {\n this.idleManager?.registerCallback(() => {\n this.logout();\n location.reload();\n });\n }\n }\n\n private async _handleSuccess(\n message: InternetIdentityAuthResponseSuccess,\n onSuccess?: OnSuccessFunc,\n ) {\n const delegations = message.delegations.map((signedDelegation) => {\n return {\n delegation: new Delegation(\n signedDelegation.delegation.pubkey,\n signedDelegation.delegation.expiration,\n signedDelegation.delegation.targets,\n ),\n signature: signedDelegation.signature as Signature,\n };\n });\n\n const delegationChain = DelegationChain.fromDelegations(\n delegations,\n message.userPublicKey as DerEncodedPublicKey,\n );\n\n const key = this._key;\n if (!key) {\n return;\n }\n\n this._chain = delegationChain;\n\n if ('toDer' in key) {\n this._identity = PartialDelegationIdentity.fromDelegation(key, this._chain);\n } else {\n this._identity = DelegationIdentity.fromDelegation(key, this._chain);\n }\n\n this._idpWindow?.close();\n const idleOptions = this._createOptions?.idleOptions;\n // create the idle manager on a successful login if we haven't disabled it\n // and it doesn't already exist.\n if (!this.idleManager && !idleOptions?.disableIdle) {\n this.idleManager = IdleManager.create(idleOptions);\n this._registerDefaultIdleCallback();\n }\n\n this._removeEventListener();\n delete this._idpWindow;\n\n if (this._chain) {\n await this._storage.set(KEY_STORAGE_DELEGATION, JSON.stringify(this._chain.toJSON()));\n }\n\n // Ensure the stored key in persistent storage matches the in-memory key that\n // was used to obtain the delegation. This avoids key/delegation mismatches\n // across multiple tabs overwriting each other's cached keys.\n await persistKey(this._storage, this._key);\n\n // onSuccess should be the last thing to do to avoid consumers\n // interfering by navigating or refreshing the page\n onSuccess?.(message);\n }\n\n public getIdentity(): Identity {\n return this._identity;\n }\n\n public async isAuthenticated(): Promise<boolean> {\n return (\n !this.getIdentity().getPrincipal().isAnonymous() &&\n this._chain !== null &&\n isDelegationValid(this._chain)\n );\n }\n\n /**\n * AuthClient Login - Opens up a new window to authenticate with Internet Identity\n * @param {AuthClientLoginOptions} options - Options for logging in, merged with the options set during creation if any. Note: we only perform a shallow merge for the `customValues` property.\n * @param options.identityProvider Identity provider\n * @param options.maxTimeToLive Expiration of the authentication in nanoseconds\n * @param options.allowPinAuthentication If present, indicates whether or not the Identity Provider should allow the user to authenticate and/or register using a temporary key/PIN identity. Authenticating dapps may want to prevent users from using Temporary keys/PIN identities because Temporary keys/PIN identities are less secure than Passkeys (webauthn credentials) and because Temporary keys/PIN identities generally only live in a browser database (which may get cleared by the browser/OS).\n * @param options.derivationOrigin Origin for Identity Provider to use while generating the delegated identity\n * @param options.windowOpenerFeatures Configures the opened authentication window\n * @param options.onSuccess Callback once login has completed\n * @param options.onError Callback in case authentication fails\n * @param options.customValues Extra values to be passed in the login request during the authorize-ready phase. Note: we only perform a shallow merge for the `customValues` property.\n * @example\n * const authClient = await AuthClient.create();\n * authClient.login({\n * identityProvider: 'http://<canisterID>.127.0.0.1:8000',\n * maxTimeToLive: BigInt (7) * BigInt(24) * BigInt(3_600_000_000_000), // 1 week\n * windowOpenerFeatures: \"toolbar=0,location=0,menubar=0,width=500,height=500,left=100,top=100\",\n * onSuccess: () => {\n * console.log('Login Successful!');\n * },\n * onError: (error) => {\n * console.error('Login Failed: ', error);\n * }\n * });\n */\n public async login(options?: AuthClientLoginOptions): Promise<void> {\n // Merge the passed options with the options set during creation\n const loginOptions = mergeLoginOptions(this._createOptions?.loginOptions, options);\n\n // Set default maxTimeToLive to 8 hours\n const maxTimeToLive = loginOptions?.maxTimeToLive ?? DEFAULT_MAX_TIME_TO_LIVE;\n\n // Create the URL of the IDP. (e.g. https://XXXX/#authorize)\n const identityProviderUrl = new URL(\n loginOptions?.identityProvider?.toString() || IDENTITY_PROVIDER_DEFAULT,\n );\n // Set the correct hash if it isn't already set.\n identityProviderUrl.hash = IDENTITY_PROVIDER_ENDPOINT;\n\n // If `login` has been called previously, then close/remove any previous windows\n // and event listeners.\n this._idpWindow?.close();\n this._removeEventListener();\n\n // Add an event listener to handle responses.\n this._eventHandler = this._getEventHandler(identityProviderUrl, {\n maxTimeToLive,\n ...loginOptions,\n });\n window.addEventListener('message', this._eventHandler);\n\n // Open a new window with the IDP provider.\n this._idpWindow =\n window.open(\n identityProviderUrl.toString(),\n 'idpWindow',\n loginOptions?.windowOpenerFeatures,\n ) ?? undefined;\n\n // Check if the _idpWindow is closed by user.\n const checkInterruption = (): void => {\n // The _idpWindow is opened and not yet closed by the client\n if (this._idpWindow) {\n if (this._idpWindow.closed) {\n this._handleFailure(ERROR_USER_INTERRUPT, loginOptions?.onError);\n } else {\n setTimeout(checkInterruption, INTERRUPT_CHECK_INTERVAL);\n }\n }\n };\n checkInterruption();\n }\n\n private _getEventHandler(identityProviderUrl: URL, options?: AuthClientLoginOptions) {\n return async (event: MessageEvent) => {\n if (event.origin !== identityProviderUrl.origin) {\n // Ignore any event that is not from the identity provider\n return;\n }\n\n const message = event.data as IdentityServiceResponseMessage;\n\n switch (message.kind) {\n case 'authorize-ready': {\n // IDP is ready. Send a message to request authorization.\n const request: InternetIdentityAuthRequest = {\n kind: 'authorize-client',\n sessionPublicKey: new Uint8Array(this._key?.getPublicKey().toDer()),\n maxTimeToLive: options?.maxTimeToLive,\n allowPinAuthentication: options?.allowPinAuthentication,\n derivationOrigin: options?.derivationOrigin?.toString(),\n // Pass any custom values to the IDP.\n ...options?.customValues,\n };\n this._idpWindow?.postMessage(request, identityProviderUrl.origin);\n break;\n }\n case 'authorize-client-success':\n // Create the delegation chain and store it.\n try {\n await this._handleSuccess(message, options?.onSuccess);\n } catch (err) {\n this._handleFailure((err as Error).message, options?.onError);\n }\n break;\n case 'authorize-client-failure':\n this._handleFailure(message.text, options?.onError);\n break;\n default:\n break;\n }\n };\n }\n\n private _handleFailure(errorMessage?: string, onError?: (error?: string) => void): void {\n this._idpWindow?.close();\n onError?.(errorMessage);\n this._removeEventListener();\n delete this._idpWindow;\n }\n\n private _removeEventListener() {\n if (this._eventHandler) {\n window.removeEventListener('message', this._eventHandler);\n }\n this._eventHandler = undefined;\n }\n\n public async logout(options: { returnTo?: string } = {}): Promise<void> {\n await _deleteStorage(this._storage);\n\n // Reset this auth client to a non-authenticated state.\n this._identity = new AnonymousIdentity();\n this._chain = null;\n\n if (options.returnTo) {\n try {\n window.history.pushState({}, '', options.returnTo);\n } catch {\n window.location.href = options.returnTo;\n }\n }\n }\n}\n\nasync function _deleteStorage(storage: AuthClientStorage) {\n await storage.remove(KEY_STORAGE_KEY);\n await storage.remove(KEY_STORAGE_DELEGATION);\n await storage.remove(KEY_VECTOR);\n}\n\nfunction mergeLoginOptions(\n loginOptions: AuthClientLoginOptions | undefined,\n otherLoginOptions: AuthClientLoginOptions | undefined,\n): AuthClientLoginOptions | undefined {\n if (!loginOptions && !otherLoginOptions) {\n return undefined;\n }\n\n const customValues =\n loginOptions?.customValues || otherLoginOptions?.customValues\n ? {\n ...loginOptions?.customValues,\n ...otherLoginOptions?.customValues,\n }\n : undefined;\n\n return {\n ...loginOptions,\n ...otherLoginOptions,\n customValues,\n };\n}\n\nfunction toStoredKey(key: SignIdentity | PartialIdentity): StoredKey {\n if (key instanceof ECDSAKeyIdentity) {\n return key.getKeyPair();\n }\n if (key instanceof Ed25519KeyIdentity) {\n return JSON.stringify(key.toJSON());\n }\n throw new Error('Unsupported key type');\n}\n\nasync function persistKey(\n storage: AuthClientStorage,\n key: SignIdentity | PartialIdentity,\n): Promise<void> {\n const serialized = toStoredKey(key);\n await storage.set(KEY_STORAGE_KEY, serialized);\n}\n", "// How long the delegation identity should remain valid?\n// e.g. BigInt(7 * 24 * 60 * 60 * 1000 * 1000 * 1000) = 7 days in nanoseconds\n// For Juno: 4 hours\nexport const DELEGATION_IDENTITY_EXPIRATION_IN_MILLISECONDS = 4 * 60 * 60 * 1000;\nexport const DELEGATION_IDENTITY_EXPIRATION = BigInt(\n DELEGATION_IDENTITY_EXPIRATION_IN_MILLISECONDS * 1000 * 1000\n);\n\n// We consider PIN authentication as \"insecure\" because users can easily lose their PIN if they do not register a passphrase, especially since Safari clears the browser cache every two weeks in cases of inactivity.\n// That's why we disable it by default.\nexport const ALLOW_PIN_AUTHENTICATION = false;\n\ninterface PopupSize {\n width: number;\n height: number;\n}\n\nexport const II_DESIGN_V1_POPUP: PopupSize = {width: 576, height: 576};\nexport const II_DESIGN_V2_POPUP: PopupSize = {width: 424, height: 576};\nexport const NFID_POPUP: PopupSize = {width: 505, height: 705};\n\nexport const INTERNET_COMPUTER_ORG = 'internetcomputer.org';\nexport const IC0_APP = 'ic0.app';\nexport const ID_AI = 'id.ai';\n\n// Worker\nexport const AUTH_TIMER_INTERVAL = 1000;\n", "export enum FromStringToTokenError {\n FractionalMoreThan8Decimals,\n InvalidFormat,\n FractionalTooManyDecimals,\n}\n", "export const E8S_PER_TOKEN = BigInt(100000000);\n", "import { E8S_PER_TOKEN } from \"../constants/constants\";\nimport { FromStringToTokenError } from \"../enums/token.enums\";\n\nconst DECIMALS_CONVERSION_SUPPORTED = 8;\n\n/**\n * Receives a string representing a number and returns the big int or error.\n *\n * @param amount - in string format\n * @returns bigint | FromStringToTokenError\n */\nexport const convertStringToE8s = (\n value: string,\n): bigint | FromStringToTokenError => {\n // replace exponential format (1e-4) with plain (0.0001)\n // doesn't support decimals for values >= ~1e16\n let amount = value.includes(\"e\")\n ? Number(value).toLocaleString(\"en\", {\n useGrouping: false,\n maximumFractionDigits: 20,\n })\n : value;\n\n // Remove all instances of \",\" and \"'\".\n amount = amount.trim().replace(/[,']/g, \"\");\n\n // Verify that the string is of the format 1234.5678\n const regexMatch = amount.match(/\\d*(\\.\\d*)?/);\n if (!regexMatch || regexMatch[0] !== amount) {\n return FromStringToTokenError.InvalidFormat;\n }\n\n const [integral, fractional] = amount.split(\".\");\n\n let e8s = BigInt(0);\n\n if (integral) {\n try {\n e8s += BigInt(integral) * E8S_PER_TOKEN;\n } catch {\n return FromStringToTokenError.InvalidFormat;\n }\n }\n\n if (fractional) {\n if (fractional.length > 8) {\n return FromStringToTokenError.FractionalMoreThan8Decimals;\n }\n try {\n e8s += BigInt(fractional.padEnd(8, \"0\"));\n } catch {\n return FromStringToTokenError.InvalidFormat;\n }\n }\n\n return e8s;\n};\n\n/**\n * Receives a string representing a number and returns the big int or error.\n *\n * @param amount - in string format\n * @returns bigint | FromStringToTokenError\n */\nconst convertStringToUlps = ({\n amount,\n decimals,\n}: {\n amount: string;\n decimals: number;\n}): bigint | FromStringToTokenError => {\n // Remove all instances of \",\" and \"'\".\n amount = amount.trim().replace(/[,']/g, \"\");\n\n // Verify that the string is of the format 1234.5678\n const regexMatch = amount.match(/\\d*(\\.\\d*)?/);\n if (!regexMatch || regexMatch[0] !== amount) {\n return FromStringToTokenError.InvalidFormat;\n }\n\n const [integral, fractional] = amount.split(\".\");\n\n let ulps = 0n;\n const ulpsPerToken = 10n ** BigInt(decimals);\n\n if (integral) {\n try {\n ulps += BigInt(integral) * ulpsPerToken;\n } catch {\n return FromStringToTokenError.InvalidFormat;\n }\n }\n\n if (fractional) {\n if (fractional.length > decimals) {\n return FromStringToTokenError.FractionalTooManyDecimals;\n }\n try {\n ulps += BigInt(fractional.padEnd(decimals, \"0\"));\n } catch {\n return FromStringToTokenError.InvalidFormat;\n }\n }\n\n return ulps;\n};\n\nexport interface Token {\n symbol: string;\n name: string;\n decimals: number;\n logo?: string;\n}\n\n// TODO: Remove this token and use the value from ICP ledger\nexport const ICPToken: Token = {\n symbol: \"ICP\",\n name: \"Internet Computer\",\n decimals: 8,\n};\n\n/**\n * Deprecated. Use TokenAmountV2 instead which supports decimals !== 8.\n *\n * Represents an amount of tokens.\n *\n * @param e8s - The amount of tokens in bigint.\n * @param token - The token type.\n */\nexport class TokenAmount {\n private constructor(\n protected e8s: bigint,\n public token: Token,\n ) {\n if (token.decimals !== 8) {\n throw new Error(\"Use TokenAmountV2 for number of decimals other than 8\");\n }\n }\n\n /**\n * Initialize from a bigint. Bigint are considered e8s.\n *\n * @param {amount: bigint; token?: Token;} params\n * @param {bigint} params.amount The amount in bigint format.\n * @param {Token} params.token The token type.\n */\n public static fromE8s({\n amount,\n token,\n }: {\n amount: bigint;\n token: Token;\n }): TokenAmount {\n return new TokenAmount(amount, token);\n }\n\n /**\n * Initialize from a string. Accepted formats:\n *\n * 1234567.8901\n * 1'234'567.8901\n * 1,234,567.8901\n *\n * @param {amount: string; token?: Token;} params\n * @param {string} params.amount The amount in string format.\n * @param {Token} params.token The token type.\n */\n public static fromString({\n amount,\n token,\n }: {\n amount: string;\n token: Token;\n }): TokenAmount | FromStringToTokenError {\n // If parsing the number fails because of the number of decimals, we still\n // want the error to be about the number of decimals and not about the\n // parsing.\n if (token.decimals !== 8) {\n throw new Error(\"Use TokenAmountV2 for number of decimals other than 8\");\n }\n const e8s = convertStringToE8s(amount);\n\n if (typeof e8s === \"bigint\") {\n return new TokenAmount(e8s, token);\n }\n return e8s;\n }\n\n /**\n * Initialize from a number.\n *\n * 1 integer is considered E8S_PER_TOKEN\n *\n * @param {amount: number; token?: Token;} params\n * @param {string} params.amount The amount in number format.\n * @param {Token} params.token The token type.\n */\n public static fromNumber({\n amount,\n token,\n }: {\n amount: number;\n token: Token;\n }): TokenAmount {\n const tokenAmount = TokenAmount.fromString({\n amount: amount.toString(),\n token,\n });\n if (tokenAmount instanceof TokenAmount) {\n return tokenAmount;\n }\n if (tokenAmount === FromStringToTokenError.FractionalMoreThan8Decimals) {\n throw new Error(`Number ${amount} has more than 8 decimals`);\n }\n\n // This should never happen\n throw new Error(`Invalid number ${amount}`);\n }\n\n /**\n *\n * @returns The amount of e8s.\n */\n public toE8s(): bigint {\n return this.e8s;\n }\n}\n\n/**\n * Represents an amount of tokens.\n *\n * @param upls - The amount of tokens in units in the last place. If the token\n * supports N decimals, 10^N ulp = 1 token.\n * @param token - The token type.\n */\nexport class TokenAmountV2 {\n private constructor(\n protected ulps: bigint,\n public token: Token,\n ) {}\n\n /**\n * Initialize from a bigint. Bigint are considered ulps.\n *\n * @param {amount: bigint; token?: Token;} params\n * @param {bigint} params.amount The amount in bigint format.\n * @param {Token} params.token The token type.\n */\n public static fromUlps({\n amount,\n token,\n }: {\n amount: bigint;\n token: Token;\n }): TokenAmountV2 {\n return new TokenAmountV2(amount, token);\n }\n\n /**\n * Initialize from a string. Accepted formats:\n *\n * 1234567.8901\n * 1'234'567.8901\n * 1,234,567.8901\n *\n * @param {amount: string; token?: Token;} params\n * @param {string} params.amount The amount in string format.\n * @param {Token} params.token The token type.\n */\n public static fromString({\n amount,\n token,\n }: {\n amount: string;\n token: Token;\n }): TokenAmountV2 | FromStringToTokenError {\n const ulps = convertStringToUlps({ amount, decimals: token.decimals });\n\n if (typeof ulps === \"bigint\") {\n return new TokenAmountV2(ulps, token);\n }\n return ulps;\n }\n\n /**\n * Initialize from a number.\n *\n * 1 integer is considered 10^{token.decimals} ulps\n *\n * @param {amount: number; token?: Token;} params\n * @param {string} params.amount The amount in number format.\n * @param {Token} params.token The token type.\n */\n public static fromNumber({\n amount,\n token,\n }: {\n amount: number;\n token: Token;\n }): TokenAmountV2 {\n const tokenAmount = TokenAmountV2.fromString({\n amount: amount.toFixed(\n Math.min(DECIMALS_CONVERSION_SUPPORTED, token.decimals),\n ),\n token,\n });\n if (tokenAmount instanceof TokenAmountV2) {\n return tokenAmount;\n }\n if (tokenAmount === FromStringToTokenError.FractionalTooManyDecimals) {\n throw new Error(\n `Number ${amount} has more than ${token.decimals} decimals`,\n );\n }\n\n // This should never happen\n throw new Error(`Invalid number ${amount}`);\n }\n\n /**\n *\n * @returns The amount of ulps.\n */\n public toUlps(): bigint {\n return this.ulps;\n }\n\n /**\n *\n * @returns The amount of ulps in e8s precision\n */\n public toE8s(): bigint {\n if (this.token.decimals < 8) {\n return this.ulps * 10n ** BigInt(8 - this.token.decimals);\n }\n if (this.token.decimals === 8) {\n return this.ulps;\n }\n return this.ulps / 10n ** BigInt(this.token.decimals - 8);\n }\n}\n", "import type { Principal } from \"@icp-sdk/core/principal\";\nimport type { QueryParams } from \"../types/query.params\";\n\nexport abstract class Canister<T> {\n protected constructor(\n private readonly id: Principal,\n protected readonly service: T,\n protected readonly certifiedService: T,\n ) {}\n\n get canisterId(): Principal {\n return this.id;\n }\n\n protected caller = ({ certified = true }: QueryParams): T =>\n certified ? this.certifiedService : this.service;\n}\n", "/**\n * Checks if a given argument is null or undefined.\n *\n * @template T - The type of the argument.\n * @param {T | undefined | null} argument - The argument to check.\n * @returns {argument is undefined | null} `true` if the argument is null or undefined; otherwise, `false`.\n */\nexport const isNullish = <T>(\n argument: T | undefined | null,\n): argument is undefined | null => argument === null || argument === undefined;\n\n/**\n * Checks if a given argument is neither null nor undefined.\n *\n * @template T - The type of the argument.\n * @param {T | undefined | null} argument - The argument to check.\n * @returns {argument is NonNullable<T>} `true` if the argument is not null or undefined; otherwise, `false`.\n */\nexport const nonNullish = <T>(\n argument: T | undefined | null,\n): argument is NonNullable<T> => !isNullish(argument);\n\n/**\n * Checks if a given value is not null, not undefined, and not an empty string.\n *\n * @param {string | undefined | null} value - The value to check.\n * @returns {boolean} `true` if the value is not null, not undefined, and not an empty string; otherwise, `false`.\n */\nexport const notEmptyString = (\n value: string | undefined | null,\n): value is string => nonNullish(value) && value !== \"\";\n\n/**\n * Checks if a given value is null, undefined, or an empty string.\n *\n * @param {string | undefined | null} value - The value to check.\n * @returns {value is undefined | null | \"\"} Type predicate indicating if the value is null, undefined, or an empty string.\n */\nexport const isEmptyString = (\n value: string | undefined | null,\n): value is undefined | null | \"\" => !notEmptyString(value);\n", "import type { QueryAndUpdateParams } from \"../types/query-and-update.params\";\nimport { isNullish } from \"../utils/nullish.utils\";\n\n/**\n * This service performs a query (not-certified) call and/or an update (certified) call, and handles the results.\n *\n * It is useful because it can do both type of calls for security reasons.\n * For example, malicious nodes can forge transactions and balance when calling an Index canister, if no update is performed to certify the results.\n *\n * Furthermore, it can handle the results of the calls in different ways:\n * - `query` only performs a query call.\n * - `update` only performs an update call.\n * - `query_and_update` performs both calls.\n *\n * The resolution can be:\n * - `all_settled` waits for all calls to settle.\n * - `race` waits for the first call to settle (typically, `query` is the fastest one).\n *\n * Once the call(s) are done, the response is handled by the `onLoad` callback.\n * However, if an error occurs, it is handled by the error callbacks, if provided: one for the query call and one for the update call.\n *\n * @param {QueryAndUpdateParams<R, E>} params The parameters to perform the request.\n * @param {QueryAndUpdateRequest<R>} params.request The request to perform.\n * @param {QueryAndUpdateOnResponse<R>} params.onLoad The callback to handle the response of the request.\n * @param {QueryAndUpdateOnQueryError<E>} [params.onQueryError] The callback to handle the error of the `query` request.\n * @param {QueryAndUpdateOnUpdateError<E>} [params.onUpdateError] The callback to handle the error of the `update` request.\n * @param {QueryAndUpdateStrategy} [params.strategy=\"query_and_update\"] The strategy to use. Default is `query_and_update`.\n * @param {QueryAndUpdateIdentity} params.identity The identity to use for the request.\n * @param {QueryAndUpdatePromiseResolution} [params.resolution=\"race\"] The resolution to use. Default is `race`.\n *\n * @template R The type of the response.\n * @template E The type of the error.\n *\n * @returns A promise that resolves when the request is done.\n */\nexport const queryAndUpdate = async <R, E = unknown>({\n request,\n onLoad,\n onQueryError,\n onUpdateError,\n strategy = \"query_and_update\",\n identity,\n resolution = \"race\",\n}: QueryAndUpdateParams<R, E>): Promise<void> => {\n let certifiedDone = false;\n\n const queryOrUpdate = (certified: boolean) =>\n request({ certified, identity })\n .then((response) => {\n if (certifiedDone) {\n return;\n }\n\n onLoad({ certified, response });\n })\n .catch((error: E) => {\n if (!certified) {\n onQueryError?.({ error, identity });\n }\n\n if (certifiedDone) {\n return;\n }\n\n if (isNullish(onUpdateError)) {\n return;\n }\n\n console.error(error);\n\n if (!certified) {\n return;\n }\n\n onUpdateError({ error, identity });\n })\n .finally(() => (certifiedDone = certifiedDone || certified));\n\n const requests: Array<Promise<void>> =\n strategy === \"query\"\n ? [queryOrUpdate(false)]\n : strategy === \"update\"\n ? [queryOrUpdate(true)]\n : [queryOrUpdate(false), queryOrUpdate(true)];\n\n await (resolution === \"all_settled\"\n ? Promise.allSettled(requests)\n : Promise.race(requests));\n};\n", "import {\n Actor,\n type ActorConfig,\n type ActorSubclass,\n type Agent,\n} from \"@icp-sdk/core/agent\";\nimport type { IDL } from \"@icp-sdk/core/candid\";\nimport type { Principal } from \"@icp-sdk/core/principal\";\nimport type { CanisterOptions } from \"../types/canister.options\";\nimport { defaultAgent } from \"./agent.utils\";\n\ntype RequiredCanisterOptions<T> = Required<\n Pick<CanisterOptions<T>, \"canisterId\">\n> &\n Omit<CanisterOptions<T>, \"canisterId\">;\n\nexport const createServices = <T>({\n options: {\n canisterId,\n serviceOverride,\n certifiedServiceOverride,\n agent: agentOption,\n callTransform,\n queryTransform,\n },\n idlFactory,\n certifiedIdlFactory,\n}: {\n options: RequiredCanisterOptions<T> &\n Pick<ActorConfig, \"queryTransform\" | \"callTransform\">;\n idlFactory: IDL.InterfaceFactory;\n certifiedIdlFactory: IDL.InterfaceFactory;\n}): {\n service: ActorSubclass<T>;\n certifiedService: ActorSubclass<T>;\n agent: Agent;\n canisterId: Principal;\n} => {\n const agent: Agent = agentOption ?? defaultAgent();\n\n const service: ActorSubclass<T> =\n serviceOverride ??\n Actor.createActor<T>(idlFactory, {\n agent,\n canisterId,\n callTransform,\n queryTransform,\n });\n\n const certifiedService: ActorSubclass<T> =\n certifiedServiceOverride ??\n Actor.createActor<T>(certifiedIdlFactory, {\n agent,\n canisterId,\n callTransform,\n queryTransform,\n });\n\n return { service, certifiedService, agent, canisterId };\n};\n", "import {\n AnonymousIdentity,\n HttpAgent,\n type Agent,\n type Identity,\n} from \"@icp-sdk/core/agent\";\nimport type { CreateAgentParams } from \"../types/agent.utils\";\nimport { isNullish, nonNullish } from \"./nullish.utils\";\n\n/**\n * Get a default agent that connects to mainnet with the anonymous identity.\n * @returns The default agent to use\n */\nexport const defaultAgent = (): Agent =>\n HttpAgent.createSync({\n host: \"https://icp-api.io\",\n identity: new AnonymousIdentity(),\n });\n\n/**\n * Create an agent for a given identity\n *\n * @param {CreateAgentParams} params The parameters to create a new HTTP agent\n * @param {Identity} params.identity A mandatory identity to use for the agent\n * @param {string} params.host An optional host to connect to, particularly useful for local development\n * @param {boolean} params.fetchRootKey Fetch root key for certificate validation during local development or on testnet\n * @param {boolean} params.verifyQuerySignatures Check for signatures in the state tree signed by the node that replies to queries - i.e. certify responses.\n * @param {number} params.retryTimes Set the number of retries the agent should perform before error.\n */\nexport const createAgent = async ({\n identity,\n host,\n fetchRootKey = false,\n verifyQuerySignatures = false,\n retryTimes,\n}: CreateAgentParams): Promise<HttpAgent> =>\n await HttpAgent.create({\n identity,\n ...(nonNullish(host) && { host }),\n verifyQuerySignatures,\n ...(nonNullish(retryTimes) && { retryTimes }),\n shouldFetchRootKey: fetchRootKey,\n });\n\nexport type AgentManagerConfig = Pick<\n CreateAgentParams,\n \"fetchRootKey\" | \"host\"\n>;\n\n/**\n * AgentManager class manages HttpAgent instances for different identities.\n *\n * It caches agents by identity to optimise resource usage and avoid unnecessary agent creation.\n * Provides functionality to create new agents, retrieve cached agents, and clear the cache when needed.\n */\nexport class AgentManager {\n private agents: Record<string, HttpAgent> | undefined | null = undefined;\n\n private constructor(private readonly config: AgentManagerConfig) {}\n\n /**\n * Static factory method to create a new AgentManager instance.\n *\n * This method serves as an alternative to directly using the private constructor,\n * making it more convenient to create instances of `AgentManager` using a simple and clear method.\n *\n * @param {AgentManagerConfig} config - Configuration options for the AgentManager instance.\n * @param {boolean} config.fetchRootKey - Whether to fetch the root key for certificate validation.\n * @param {string} config.host - The host to connect to.\n * @returns {AgentManager} A new instance of `AgentManager`.\n */\n public static create(config: AgentManagerConfig): AgentManager {\n return new AgentManager(config);\n }\n\n /**\n * Get or create an HTTP agent for a given identity.\n *\n * If the agent for the specified identity has been created and cached, it is retrieved from the cache.\n * If no agent exists for the identity, a new one is created, cached, and then returned.\n *\n * @param {Identity} identity - The identity to be used to create the agent.\n * @returns {Promise<HttpAgent>} The HttpAgent associated with the given identity.\n */\n public getAgent = async ({\n identity,\n }: {\n identity: Identity;\n }): Promise<HttpAgent> => {\n const key = identity.getPrincipal().toText();\n\n if (isNullish(this.agents) || isNullish(this.agents[key])) {\n const agent = await createAgent({\n identity,\n fetchRootKey: this.config.fetchRootKey,\n host: this.config.host,\n verifyQuerySignatures: true,\n });\n\n this.agents = {\n ...(this.agents ?? {}),\n [key]: agent,\n };\n\n return agent;\n }\n\n return this.agents[key];\n };\n\n /**\n * Clear the cache of HTTP agents.\n *\n * This method removes all cached agents, forcing new agent creation on the next request for any identity.\n * Useful when identities have changed or if you want to reset all active connections.\n */\n public clearAgents = (): void => {\n this.agents = null;\n };\n}\n", "export class InvalidPercentageError extends Error {}\nexport class NullishError extends Error {}\n\nexport const assertNonNullish: <T>(\n value: T,\n message?: string,\n // eslint-disable-next-line local-rules/prefer-object-params\n) => asserts value is NonNullable<T> = <T>(\n value: T,\n message?: string,\n): void => {\n if (value === null || value === undefined) {\n throw new NullishError(message);\n }\n};\n\n// eslint-disable-next-line local-rules/prefer-object-params\nexport const asNonNullish = <T>(value: T, message?: string): NonNullable<T> => {\n assertNonNullish(value, message);\n return value;\n};\n\nexport const assertPercentageNumber = (percentage: number) => {\n if (percentage < 0 || percentage > 100) {\n throw new InvalidPercentageError(\n `${percentage} is not a valid percentage number.`,\n );\n }\n};\n\n/**\n * Utility to enforce exhaustiveness checks in TypeScript.\n *\n * This function should only be called in branches of a `switch` or conditional\n * that should be unreachable if the union type has been fully handled.\n *\n * By typing the parameter as `never`, the compiler will emit an error if\n * a new variant is added to the union but not covered in the logic.\n *\n * @param _ - A value that should be of type `never`. If this is not the case,\n * the TypeScript compiler will flag a type error.\n * @param message - Optional custom error message to include in the thrown error.\n * @throws {Error} Always throws when invoked at runtime.\n *\n */\n// eslint-disable-next-line local-rules/prefer-object-params\nexport const assertNever = (_: never, message?: string): never => {\n throw new Error(message);\n};\n", "import { assertNonNullish } from \"./asserts.utils\";\n\nexport const uint8ArrayToBigInt = (array: Uint8Array): bigint => {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n if (typeof view.getBigUint64 === \"function\") {\n return view.getBigUint64(0);\n }\n const high = BigInt(view.getUint32(0));\n const low = BigInt(view.getUint32(4));\n\n return (high << BigInt(32)) + low;\n};\n\nexport const bigIntToUint8Array = (value: bigint): Uint8Array => {\n const buffer = new ArrayBuffer(8);\n const view = new DataView(buffer);\n if (typeof view.setBigUint64 === \"function\") {\n view.setBigUint64(0, value);\n } else {\n const high = Number(value >> BigInt(32));\n const low = Number(value & BigInt(0xffffffff));\n\n view.setUint32(0, high);\n view.setUint32(4, low);\n }\n\n return new Uint8Array(buffer);\n};\n\nexport const numberToUint8Array = (value: number): Uint8Array => {\n const view = new DataView(new ArrayBuffer(8));\n for (let index = 7; index >= 0; --index) {\n view.setUint8(index, value % 256);\n value = value >> 8;\n }\n return new Uint8Array(view.buffer);\n};\n\nexport const arrayBufferToUint8Array = (buffer: ArrayBuffer): Uint8Array =>\n new Uint8Array(buffer);\n\nexport const uint8ArrayToArrayOfNumber = (array: Uint8Array): Array<number> =>\n Array.from(array);\n\nexport const arrayOfNumberToUint8Array = (numbers: Array<number>): Uint8Array =>\n new Uint8Array(numbers);\n\nexport const asciiStringToByteArray = (text: string): Array<number> =>\n Array.from(text).map((c) => c.charCodeAt(0));\n\nexport const hexStringToUint8Array = (hexString: string): Uint8Array => {\n const matches = hexString.match(/.{1,2}/g);\n\n assertNonNullish(matches, \"Invalid hex string.\");\n\n return Uint8Array.from(matches.map((byte) => parseInt(byte, 16)));\n};\n\n/**\n * Compare two Uint8Arrays for byte-level equality.\n *\n * @param {Object} params\n * @param {Uint8Array} params.a - First Uint8Array to compare.\n * @param {Uint8Array} params.b - Second Uint8Array to compare.\n * @returns {boolean} True if both arrays have the same length and identical contents.\n */\nexport const uint8ArraysEqual = ({ a, b }: { a: Uint8Array; b: Uint8Array }) =>\n a.length === b.length && a.every((byte, i) => byte === b[i]);\n\nexport const uint8ArrayToHexString = (bytes: Uint8Array | number[]) => {\n if (!(bytes instanceof Uint8Array)) {\n bytes = Uint8Array.from(bytes);\n }\n return bytes.reduce(\n (str, byte) => str + byte.toString(16).padStart(2, \"0\"),\n \"\",\n );\n};\n\nexport const candidNumberArrayToBigInt = (array: number[]): bigint => {\n let result = 0n;\n for (let i = array.length - 1; i >= 0; i--) {\n result = (result << 32n) + BigInt(array[i]);\n }\n return result;\n};\n", "import { assertNonNullish } from \"./asserts.utils\";\n\nconst ALPHABET = \"abcdefghijklmnopqrstuvwxyz234567\";\n\n// Build a lookup table for decoding.\nconst LOOKUP_TABLE: Record<string, number> = Object.create(null);\nfor (let i = 0; i < ALPHABET.length; i++) {\n LOOKUP_TABLE[ALPHABET[i]] = i;\n}\n\n// Add aliases for rfc4648.\nLOOKUP_TABLE[\"0\"] = LOOKUP_TABLE.o;\nLOOKUP_TABLE[\"1\"] = LOOKUP_TABLE.i;\n\n/**\n * Encode an Uint8Array to a base32 string.\n *\n * @param input The input array to encode.\n * @returns A Base32 string encoding the input.\n */\nexport const encodeBase32 = (input: Uint8Array): string => {\n // How many bits will we skip from the first byte.\n let skip = 0;\n // 5 high bits, carry from one byte to the next.\n let bits = 0;\n\n // The output string in base32.\n let output = \"\";\n\n const encodeByte = (byte: number): number => {\n if (skip < 0) {\n // we have a carry from the previous byte\n bits |= byte >> -skip;\n } else {\n // no carry\n bits = (byte << skip) & 248;\n }\n\n if (skip > 3) {\n // Not enough data to produce a character, get us another one\n skip -= 8;\n return 1;\n }\n\n if (skip < 4) {\n // produce a character\n output += ALPHABET[bits >> 3];\n skip += 5;\n }\n\n return 0;\n };\n\n for (let i = 0; i < input.length; ) {\n i += encodeByte(input[i]);\n }\n\n return output + (skip < 0 ? ALPHABET[bits >> 3] : \"\");\n};\n\n/**\n * Decode a base32 string to Uint8Array.\n *\n * @param input The input string to decode.\n * @param input The base32 encoded string to decode.\n */\nexport const decodeBase32 = (input: string): Uint8Array => {\n // how many bits we have from the previous character.\n let skip = 0;\n // current byte we're producing.\n let byte = 0;\n\n const output = new Uint8Array(((input.length * 4) / 3) | 0);\n let o = 0;\n\n const decodeChar = (char: string) => {\n // Consume a character from the stream, store\n // the output in this.output. As before, better\n // to use update().\n let val = LOOKUP_TABLE[char.toLowerCase()];\n assertNonNullish(val, `Invalid character: ${JSON.stringify(char)}`);\n\n // move to the high bits\n val <<= 3;\n byte |= val >>> skip;\n skip += 5;\n\n if (skip >= 8) {\n // We have enough bytes to produce an output\n output[o++] = byte;\n skip -= 8;\n\n if (skip > 0) {\n byte = (val << (5 - skip)) & 255;\n } else {\n byte = 0;\n }\n }\n };\n\n for (const c of input) {\n decodeChar(c);\n }\n\n return output.slice(0, o);\n};\n", "/**\n * Converts a Uint8Array (binary data) to a base64 encoded string.\n *\n * @param {Uint8Array} uint8Array - The Uint8Array containing binary data to be encoded.\n * @returns {string} - The base64 encoded string representation of the binary data.\n */\nexport const uint8ArrayToBase64 = (uint8Array: Uint8Array): string =>\n btoa(String.fromCharCode(...new Uint8Array(uint8Array)));\n\n/**\n * Converts a base64 encoded string to a Uint8Array (binary data).\n *\n * @param {string} base64String - The base64 encoded string to be decoded.\n * @returns {Uint8Array} - The Uint8Array representation of the decoded binary data.\n */\nexport const base64ToUint8Array = (base64String: string): Uint8Array =>\n Uint8Array.from(atob(base64String), (c) => c.charCodeAt(0));\n", "// This file is translated to JavaScript from\n// https://lxp32.github.io/docs/a-simple-example-crc32-calculation/\nconst lookUpTable: Uint32Array = new Uint32Array([\n 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,\n 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,\n 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,\n 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,\n 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,\n 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,\n 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,\n 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,\n 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,\n 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,\n 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,\n 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,\n 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,\n 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,\n 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,\n 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,\n 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,\n 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,\n 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,\n 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,\n 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,\n 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,\n 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,\n 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,\n 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,\n 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,\n 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,\n 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,\n 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,\n 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,\n 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,\n 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,\n 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,\n 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,\n 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,\n 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,\n 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,\n 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,\n 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,\n 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,\n 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,\n 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,\n 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,\n]);\n\nconst crc32 = (bytes: Uint8Array): number => {\n let crc = -1;\n\n for (let i = 0; i < bytes.length; i++) {\n const byte = bytes[i];\n const t = (byte ^ crc) & 0xff;\n crc = lookUpTable[t] ^ (crc >>> 8);\n }\n\n return (crc ^ -1) >>> 0;\n};\n\nexport const bigEndianCrc32 = (bytes: Uint8Array): Uint8Array => {\n const checksumArrayBuf = new ArrayBuffer(4);\n const view = new DataView(checksumArrayBuf);\n view.setUint32(0, crc32(bytes), false);\n return new Uint8Array(checksumArrayBuf);\n};\n", "import { Principal } from \"@icp-sdk/core/principal\";\nimport { nonNullish } from \"./nullish.utils\";\n\nconst JSON_KEY_BIGINT = \"__bigint__\";\nconst JSON_KEY_PRINCIPAL = \"__principal__\";\nconst JSON_KEY_UINT8ARRAY = \"__uint8array__\";\n\n/**\n * A custom replacer for `JSON.stringify` that converts specific types not natively supported\n * by the API into JSON-compatible formats.\n *\n * Supported conversions:\n * - `BigInt` \u2192 `{ \"__bigint__\": string }`\n * - `Principal` \u2192 `{ \"__principal__\": string }`\n * - `Uint8Array` \u2192 `{ \"__uint8array__\": number[] }`\n *\n * @param {string} _key - Ignored. Only provided for API compatibility.\n * @param {unknown} value - The value to transform before stringification.\n * @returns {unknown} The transformed value if it matches a known type, otherwise the original value.\n */\n// eslint-disable-next-line local-rules/prefer-object-params\nexport const jsonReplacer = (_key: string, value: unknown): unknown => {\n if (typeof value === \"bigint\") {\n return { [JSON_KEY_BIGINT]: `${value}` };\n }\n\n if (nonNullish(value) && Principal.isPrincipal(value)) {\n // isPrincipal asserts if a value is a Principal, but does not assert if the object\n // contains functions such as toText(). That's why we construct a new object.\n return { [JSON_KEY_PRINCIPAL]: Principal.from(value).toText() };\n }\n\n if (nonNullish(value) && value instanceof Uint8Array) {\n return { [JSON_KEY_UINT8ARRAY]: Array.from(value) };\n }\n\n return value;\n};\n\n/**\n * A custom reviver for `JSON.parse` that reconstructs specific types from their JSON-encoded representations.\n *\n * This reverses the transformations applied by `jsonReplacer`, restoring the original types.\n *\n * Supported conversions:\n * - `{ \"__bigint__\": string }` \u2192 `BigInt`\n * - `{ \"__principal__\": string }` \u2192 `Principal`\n * - `{ \"__uint8array__\": number[] }` \u2192 `Uint8Array`\n *\n * @param {string} _key - Ignored but provided for API compatibility.\n * @param {unknown} value - The parsed value to transform.\n * @returns {unknown} The reconstructed value if it matches a known type, otherwise the original value.\n */\n// eslint-disable-next-line local-rules/prefer-object-params\nexport const jsonReviver = (_key: string, value: unknown): unknown => {\n const mapValue = <T>(key: string): T => (value as Record<string, T>)[key];\n\n if (\n nonNullish(value) &&\n typeof value === \"object\" &&\n JSON_KEY_BIGINT in value\n ) {\n return BigInt(mapValue(JSON_KEY_BIGINT));\n }\n\n if (\n nonNullish(value) &&\n typeof value === \"object\" &&\n JSON_KEY_PRINCIPAL in value\n ) {\n return Principal.fromText(mapValue(JSON_KEY_PRINCIPAL));\n }\n\n if (\n nonNullish(value) &&\n typeof value === \"object\" &&\n JSON_KEY_UINT8ARRAY in value\n ) {\n return Uint8Array.from(mapValue(JSON_KEY_UINT8ARRAY));\n }\n\n return value;\n};\n", "import { uint8ArrayToHexString } from \"./arrays.utils\";\nimport { jsonReplacer } from \"./json.utils\";\n\n/**\n * Generates a SHA-256 hash from the given object.\n *\n * The object is first stringified using a custom `jsonReplacer`, then\n * hashed using the SubtleCrypto API. The resulting hash is returned as a hex string.\n *\n * @template T - The type of the input object.\n * @param {T} params - The object to hash.\n * @returns {Promise<string>} A promise that resolves to the hex string of the SHA-256 hash.\n */\nexport const hashObject = async <T extends object>(\n params: T,\n): Promise<string> => {\n const jsonString = JSON.stringify(params, jsonReplacer);\n\n return await hashText(jsonString);\n};\n\n/**\n * Generates a SHA-256 hash from a plain text string.\n *\n * The string is UTF-8 encoded and hashed using the SubtleCrypto API.\n * The resulting hash is returned as a hexadecimal string.\n *\n * @param {string} text - The text to hash.\n * @returns {Promise<string>} A promise that resolves to the hex string of the SHA-256 hash.\n */\nexport const hashText = async (text: string): Promise<string> => {\n const dataBuffer = new TextEncoder().encode(text);\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", dataBuffer);\n\n return uint8ArrayToHexString(new Uint8Array(hashBuffer));\n};\n", "const SECONDS_IN_MINUTE = 60;\nconst MINUTES_IN_HOUR = 60;\nconst HOURS_IN_DAY = 24;\nconst DAYS_IN_NON_LEAP_YEAR = 365;\n\nexport interface I18nSecondsToDuration {\n year: string;\n year_plural: string;\n month: string;\n month_plural: string;\n day: string;\n day_plural: string;\n hour: string;\n hour_plural: string;\n minute: string;\n minute_plural: string;\n second: string;\n second_plural: string;\n}\n\nconst EN_TIME: I18nSecondsToDuration = {\n year: \"year\",\n year_plural: \"years\",\n month: \"month\",\n month_plural: \"months\",\n day: \"day\",\n day_plural: \"days\",\n hour: \"hour\",\n hour_plural: \"hours\",\n minute: \"minute\",\n minute_plural: \"minutes\",\n second: \"second\",\n second_plural: \"seconds\",\n};\n\n/**\n * Convert seconds to a human-readable duration, such as \"6 days, 10 hours.\"\n * @param {Object} options - The options object.\n * @param {bigint} options.seconds - The number of seconds to convert.\n * @param {I18nSecondsToDuration} [options.i18n] - The i18n object for customizing language and units. Defaults to English.\n * @returns {string} The human-readable duration string.\n */\nexport const secondsToDuration = ({\n seconds,\n i18n = EN_TIME,\n}: {\n seconds: bigint;\n i18n?: I18nSecondsToDuration;\n}): string => {\n let minutes = seconds / BigInt(SECONDS_IN_MINUTE);\n\n let hours = minutes / BigInt(MINUTES_IN_HOUR);\n minutes -= hours * BigInt(MINUTES_IN_HOUR);\n\n let days = hours / BigInt(HOURS_IN_DAY);\n hours -= days * BigInt(HOURS_IN_DAY);\n\n const years = fullYearsInDays(days);\n days -= daysInYears(years);\n\n const periods = [\n createLabel({ labelKey: \"year\", amount: years }),\n createLabel({ labelKey: \"day\", amount: days }),\n createLabel({ labelKey: \"hour\", amount: hours }),\n createLabel({ labelKey: \"minute\", amount: minutes }),\n ...(seconds > BigInt(0) && seconds < BigInt(60)\n ? [createLabel({ labelKey: \"second\", amount: seconds })]\n : []),\n ];\n\n return periods\n .filter(({ amount }) => amount > 0)\n .slice(0, 2)\n .map(\n (labelInfo) =>\n `${labelInfo.amount} ${\n labelInfo.amount === 1\n ? i18n[labelInfo.labelKey]\n : i18n[`${labelInfo.labelKey}_plural`]\n }`,\n )\n .join(\", \");\n};\n\nconst fullYearsInDays = (days: bigint): bigint => {\n // Use integer division.\n let years = days / BigInt(DAYS_IN_NON_LEAP_YEAR);\n while (daysInYears(years) > days) {\n years--;\n }\n return years;\n};\n\nconst daysInYears = (years: bigint): bigint => {\n // Use integer division.\n const leapDays = years / BigInt(4);\n return years * BigInt(DAYS_IN_NON_LEAP_YEAR) + leapDays;\n};\n\ntype LabelKey = \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\" | \"second\";\ninterface LabelInfo {\n labelKey: LabelKey;\n amount: number;\n}\nconst createLabel = ({\n labelKey,\n amount,\n}: {\n labelKey: LabelKey;\n amount: bigint;\n}): LabelInfo => ({\n labelKey,\n amount: Number(amount),\n});\n\nconst NANOSECONDS_PER_MILLISECOND = 1_000_000n;\n\n/**\n * Returns the current timestamp in nanoseconds as a `bigint`.\n *\n * @returns {bigint} The current timestamp in nanoseconds.\n */\nexport const nowInBigIntNanoSeconds = (): bigint =>\n BigInt(Date.now()) * NANOSECONDS_PER_MILLISECOND;\n\n/**\n * Converts a given `Date` object to a timestamp in nanoseconds as a `bigint`.\n *\n * @param {Date} date - The `Date` object to convert.\n * @returns {bigint} The timestamp in nanoseconds.\n */\nexport const toBigIntNanoSeconds = (date: Date): bigint =>\n BigInt(date.getTime()) * NANOSECONDS_PER_MILLISECOND;\n", "/**\n * Creates a debounced version of the provided function.\n *\n * The debounced function postpones its execution until after a certain amount of time\n * has elapsed since the last time it was invoked. This is useful for limiting the rate\n * at which a function is called (e.g. in response to user input or events).\n *\n * @param {Function} func - The function to debounce. It will only be called after no new calls happen within the specified timeout.\n * @param {number} [timeout=300] - The debounce delay in milliseconds. Defaults to 300ms if not provided or invalid.\n * @returns {(args: unknown[]) => void} A debounced version of the original function.\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type, local-rules/prefer-object-params\nexport const debounce = (func: Function, timeout?: number) => {\n let timer: NodeJS.Timer | undefined;\n\n return (...args: unknown[]) => {\n const next = () => func(...args);\n\n if (timer) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore TypeScript global and window confusion even if we are using @types/node\n clearTimeout(timer);\n }\n\n timer = setTimeout(\n next,\n timeout !== undefined && timeout > 0 ? timeout : 300,\n );\n };\n};\n", "import type { Nullable, NullishNullable } from \"../types/did.utils\";\nimport { assertNonNullish } from \"./asserts.utils\";\nimport { nonNullish } from \"./nullish.utils\";\n\n/**\n * Converts a value into a Candid-style variant representation of an optional value.\n *\n * @template T The type of the value.\n * @param {T | null | undefined} value - The value to convert into a Candid-style variant.\n * @returns {Nullable<T>} A Candid-style variant representation: an empty array for `null` and `undefined` or an array with the value.\n */\nexport const toNullable = <T>(value?: T | null): Nullable<T> =>\n nonNullish(value) ? [value] : [];\n\n/**\n * Extracts the value from a Candid-style variant representation of an optional value.\n *\n * @template T The type of the value.\n * @param {Nullable<T>} value - A Candid-style variant representing an optional value.\n * @returns {T | undefined} The extracted value, or `undefined` if the array is empty.\n */\nexport const fromNullable = <T>(value: Nullable<T>): T | undefined =>\n value?.[0];\n\n/**\n * Extracts the value from a Candid-style variant representation of an optional value,\n * ensuring the value is defined. Throws an error if the array is empty or the value is nullish.\n *\n * @template T The type of the value.\n * @param {Nullable<T>} value - A Candid-style variant representing an optional value.\n * @returns {T} The extracted value.\n * @throws {Error} If the array is empty or the value is nullish.\n */\nexport const fromDefinedNullable = <T>(value: Nullable<T>): T => {\n const result = fromNullable(value);\n\n assertNonNullish(result);\n\n return result;\n};\n\n/**\n * Extracts the value from a nullish Candid-style variant representation.\n *\n * @template T The type of the value.\n * @param {NullishNullable<T>} value - A Candid-style variant or `undefined`.\n * @returns {T | undefined} The extracted value, or `undefined` if the input is nullish or the array is empty.\n */\nexport const fromNullishNullable = <T>(\n value: NullishNullable<T>,\n): T | undefined => fromNullable(value ?? []);\n", "import type { Principal } from \"@icp-sdk/core/principal\";\n\n/**\n * Convert a principal to a Uint8Array 32 length.\n * e.g. Useful to convert a canister ID when topping up cycles with the Cmc canister\n * @param principal The principal that needs to be converted to Subaccount\n */\nexport const principalToSubAccount = (principal: Principal): Uint8Array => {\n const bytes: Uint8Array = principal.toUint8Array();\n const subAccount: Uint8Array = new Uint8Array(32);\n subAccount[0] = bytes.length;\n subAccount.set(bytes, 1);\n return subAccount;\n};\n", "const AMOUNT_VERSION_PARTS = 3;\nconst addZeros = ({\n nums,\n amountZeros,\n}: {\n nums: number[];\n amountZeros: number;\n}): number[] =>\n amountZeros > nums.length\n ? [...nums, ...[...Array(amountZeros - nums.length).keys()].map(() => 0)]\n : nums;\n\nconst convertToNumber = (versionStringPart: string): number => {\n if (!Number.isNaN(Number(versionStringPart))) {\n return Number(versionStringPart);\n }\n const strippedVersion = versionStringPart.split(\"\").reduce((acc, char) => {\n if (Number.isNaN(Number(char))) {\n return acc;\n }\n return acc + char;\n }, \"\");\n return Number(strippedVersion);\n};\n/**\n * Returns true if the current version is smaller than the minVersion, false if equal or bigger.\n * Tags after patch version are ignored, e.g. 1.0.0-beta.1 is considered equal to 1.0.0.\n *\n * @param {Object} params\n * @param {string} params.minVersion Ex: \"1.0.0\"\n * @param {string} params.currentVersion Ex: \"2.0.0\"\n * @returns boolean\n */\nexport const smallerVersion = ({\n minVersion,\n currentVersion,\n}: {\n minVersion: string;\n currentVersion: string;\n}): boolean => {\n const minVersionStandarized = addZeros({\n nums: minVersion.split(\".\").map(convertToNumber),\n amountZeros: AMOUNT_VERSION_PARTS,\n }).join(\".\");\n const currentVersionStandarized = addZeros({\n nums: currentVersion.split(\".\").map(convertToNumber),\n amountZeros: AMOUNT_VERSION_PARTS,\n }).join(\".\");\n // Versions need to have the same number of parts to be comparable\n // Source: https://stackoverflow.com/a/65687141\n return (\n currentVersionStandarized.localeCompare(minVersionStandarized, undefined, {\n numeric: true,\n sensitivity: \"base\",\n }) < 0\n );\n};\n", "import {isNullish} from '@dfinity/utils';\nimport {\n AuthClient,\n IdbStorage,\n KEY_STORAGE_DELEGATION,\n KEY_STORAGE_KEY\n} from '@icp-sdk/auth/client';\nimport type {DelegationChain, ECDSAKeyIdentity} from '@icp-sdk/core/identity';\n\nexport class AuthClientStore {\n static #instance: AuthClientStore | undefined;\n\n #authClient: AuthClient | undefined | null;\n\n private constructor() {}\n\n static getInstance(): AuthClientStore {\n if (isNullish(this.#instance)) {\n this.#instance = new AuthClientStore();\n }\n\n return this.#instance;\n }\n\n createAuthClient = async (): Promise<AuthClient> => {\n this.#authClient = await AuthClient.create({\n idleOptions: {\n disableIdle: true,\n disableDefaultIdleCallback: true\n }\n });\n\n return this.#authClient;\n };\n\n safeCreateAuthClient = async (): Promise<AuthClient> => {\n // Since AgentJS persists the identity key in IndexedDB by default,\n // it can be tampered with and affect the next login with Internet Identity or NFID.\n // To ensure each session starts clean and safe, we clear the stored keys before creating a new AuthClient\n // in case the user is not authenticated.\n const storage = new IdbStorage();\n await storage.remove(KEY_STORAGE_KEY);\n\n return await this.createAuthClient();\n };\n\n getAuthClient = (): AuthClient | undefined | null => this.#authClient;\n\n logout = async (): Promise<void> => {\n await this.#authClient?.logout();\n\n // Reset local object otherwise next sign in (sign in - sign out - sign in) might not work out - i.e. agent-js might not recreate the delegation or identity if not resetted\n // Technically we do not need this since we recreate the agent below. We just keep it to make the reset explicit.\n this.#authClient = null;\n };\n\n setAuthClientStorage = async ({\n delegationChain,\n sessionKey\n }: {\n delegationChain: DelegationChain;\n sessionKey: ECDSAKeyIdentity;\n }) => {\n const storage = new IdbStorage();\n\n await Promise.all([\n storage.set(KEY_STORAGE_KEY, sessionKey.getKeyPair()),\n storage.set(KEY_STORAGE_DELEGATION, JSON.stringify(delegationChain.toJSON()))\n ]);\n };\n}\n", "import {IdbStorage, KEY_STORAGE_DELEGATION} from '@icp-sdk/auth/client';\nimport {DelegationChain, isDelegationValid} from '@icp-sdk/core/identity';\nimport {AUTH_TIMER_INTERVAL} from '../constants/auth.constants';\nimport {AuthClientStore} from '../stores/auth-client.store';\nimport type {PostMessage, PostMessageDataRequest} from '../types/post-message';\n\nexport const onAuthMessage = ({data}: MessageEvent<PostMessage<PostMessageDataRequest>>) => {\n const {msg} = data;\n\n switch (msg) {\n case 'junoStartAuthTimer':\n startTimer();\n return;\n case 'junoStopAuthTimer':\n stopTimer();\n }\n};\n\nlet timer: NodeJS.Timeout | undefined = undefined;\n\n/**\n * The timer is executed only if user has signed in\n */\nexport const startTimer = () =>\n (timer = setInterval(async () => await onTimerSignOut(), AUTH_TIMER_INTERVAL));\n\nexport const stopTimer = () => {\n if (!timer) {\n return;\n }\n\n clearInterval(timer);\n timer = undefined;\n};\n\n/**\n * \u2139\uFE0F Exported for test purpose only.\n */\nexport const onTimerSignOut = async () => {\n const [auth, chain] = await Promise.all([checkAuthentication(), checkDelegationChain()]);\n\n // Both identity and delegation are alright, so all good\n if (auth && chain.valid && chain.delegation !== null) {\n emitExpirationTime(chain.delegation);\n return;\n }\n\n logout();\n};\n\n/**\n * If user is not authenticated - i.e. no identity or anonymous and there is no valid delegation chain, then identity is not valid\n *\n * @returns true if authenticated\n */\nconst checkAuthentication = async (): Promise<boolean> => {\n const authClient = await AuthClientStore.getInstance().createAuthClient();\n return authClient.isAuthenticated();\n};\n\n/**\n * If there is no delegation or if not valid, then delegation is not valid.\n *\n * @returns Object true if delegation is valid and delegation\n */\nconst checkDelegationChain = async (): Promise<{\n valid: boolean;\n delegation: DelegationChain | null;\n}> => {\n const idbStorage: IdbStorage = new IdbStorage();\n const delegationChain: string | null = await idbStorage.get(KEY_STORAGE_DELEGATION);\n\n const delegation = delegationChain !== null ? DelegationChain.fromJSON(delegationChain) : null;\n\n return {\n valid: delegation !== null && isDelegationValid(delegation),\n delegation\n };\n};\n\nconst logout = () => {\n // Clear timer to not emit sign-out multiple times\n stopTimer();\n\n postMessage({msg: 'junoSignOutAuthTimer'});\n};\n\nconst emitExpirationTime = (delegation: DelegationChain) => {\n const expirationTime: bigint | undefined = delegation.delegations[0]?.delegation.expiration;\n\n // That would be unexpected here because the delegation has just been tested and is valid\n if (expirationTime === undefined) {\n return;\n }\n\n // 1_000_000 as NANO_SECONDS_IN_MILLISECOND. Constant not imported to not break prod build.\n const authRemainingTime =\n new Date(Number(expirationTime / BigInt(1_000_000))).getTime() - Date.now();\n\n postMessage({\n msg: 'junoDelegationRemainingTime',\n data: {\n authRemainingTime\n }\n });\n};\n", "import type {PostMessage, PostMessageDataRequest} from '../auth/types/post-message';\nimport {onAuthMessage} from '../auth/workers/auth.worker';\n\nonmessage = (params: MessageEvent<PostMessage<PostMessageDataRequest>>) => {\n onAuthMessage(params);\n};\n"],
5
+ "mappings": "mBAAA,IAAMA,GAAW,mCAGXC,GAAsC,OAAO,OAAO,IAAI,EAC9D,QAASC,EAAI,EAAGA,EAAIF,GAAS,OAAQE,IACnCD,GAAYD,GAASE,CAAC,CAAC,EAAIA,EAI7BD,GAAY,CAAG,EAAIA,GAAY,EAC/BA,GAAY,CAAG,EAAIA,GAAY,EAMzB,SAAUE,GAAaC,EAAiB,CAE5C,IAAIC,EAAO,EAEPC,EAAO,EAGPC,EAAS,GAEb,SAASC,EAAWC,EAAY,CAS9B,OARIJ,EAAO,EAETC,GAAQG,GAAQ,CAACJ,EAGjBC,EAAQG,GAAQJ,EAAQ,IAGtBA,EAAO,GAETA,GAAQ,EACD,IAGLA,EAAO,IAETE,GAAUP,GAASM,GAAQ,CAAC,EAC5BD,GAAQ,GAGH,EACT,CAEA,QAASH,EAAI,EAAGA,EAAIE,EAAM,QACxBF,GAAKM,EAAWJ,EAAMF,CAAC,CAAC,EAG1B,OAAOK,GAAUF,EAAO,EAAIL,GAASM,GAAQ,CAAC,EAAI,GACpD,CAKM,SAAUI,GAAaN,EAAa,CAExC,IAAIC,EAAO,EAEPI,EAAO,EAELF,EAAS,IAAI,WAAaH,EAAM,OAAS,EAAK,EAAK,CAAC,EACtD,EAAI,EAER,SAASO,EAAWC,EAAY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BACHC,GAAU,CACd,CACF,EAEIC,GAKSF,GAAa,IACvBE,GAAQ,YAAY,SAAY,MAAMC,GAAe,EAAGC,EAAmB,EAEjEH,GAAY,IAAM,CACxBC,KAIL,cAAcA,EAAK,EACnBA,GAAQ,OACV,EAKaC,GAAiB,SAAY,CACxC,GAAM,CAACE,EAAMC,CAAK,EAAI,MAAM,QAAQ,IAAI,CAACC,GAAoB,EAAGC,GAAqB,CAAC,CAAC,EAGvF,GAAIH,GAAQC,EAAM,OAASA,EAAM,aAAe,KAAM,CACpDG,GAAmBH,EAAM,UAAU,EACnC,MACF,CAEAI,GAAO,CACT,EAOMH,GAAsB,UACP,MAAMI,GAAgB,YAAY,EAAE,iBAAiB,GACtD,gBAAgB,EAQ9BH,GAAuB,SAGvB,CAEJ,IAAMI,EAAiC,MADR,IAAIC,EAAW,EACU,IAAIC,CAAsB,EAE5EC,EAAaH,IAAoB,KAAOI,GAAgB,SAASJ,CAAe,EAAI,KAE1F,MAAO,CACL,MAAOG,IAAe,MAAQE,GAAkBF,CAAU,EAC1D,WAAAA,CACF,CACF,EAEML,GAAS,IAAM,CAEnBT,GAAU,EAEV,YAAY,CAAC,IAAK,sBAAsB,CAAC,CAC3C,EAEMQ,GAAsBM,GAAgC,CAC1D,IAAMG,EAAqCH,EAAW,YAAY,CAAC,GAAG,WAAW,WAGjF,GAAIG,IAAmB,OACrB,OAIF,IAAMC,EACJ,IAAI,KAAK,OAAOD,EAAiB,OAAO,GAAS,CAAC,CAAC,EAAE,QAAQ,EAAI,KAAK,IAAI,EAE5E,YAAY,CACV,IAAK,8BACL,KAAM,CACJ,kBAAAC,CACF,CACF,CAAC,CACH,ECtGA,UAAaC,GAA8D,CACzEC,GAAcD,CAAM,CACtB",
6
+ "names": ["alphabet", "lookupTable", "i", "base32Encode", "input", "skip", "bits", "output", "encodeByte", "byte", "base32Decode", "decodeChar", "char", "val", "c", "lookUpTable", "getCrc32", "buf", "crc", "i", "t", "crypto", "isBytes", "a", "anumber", "n", "abytes", "b", "lengths", "aexists", "instance", "checkFinished", "aoutput", "out", "abytes", "min", "clean", "arrays", "i", "createView", "arr", "rotr", "word", "shift", "hasHexBuiltin", "hexes", "_", "i", "bytesToHex", "bytes", "abytes", "hex", "asciis", "asciiToBase16", "ch", "hexToBytes", "hl", "al", "array", "ai", "hi", "n1", "n2", "char", "utf8ToBytes", "str", "toBytes", "data", "utf8ToBytes", "abytes", "concatBytes", "arrays", "sum", "i", "a", "abytes", "res", "pad", "Hash", "createHasher", "hashCons", "hashC", "msg", "toBytes", "tmp", "randomBytes", "bytesLength", "crypto", "setBigUint64", "view", "byteOffset", "value", "isLE", "_32n", "_u32_max", "wh", "wl", "h", "l", "Chi", "a", "b", "c", "Maj", "HashMD", "Hash", "blockLen", "outputLen", "padOffset", "createView", "data", "aexists", "toBytes", "abytes", "buffer", "len", "pos", "take", "dataView", "out", "aoutput", "clean", "i", "oview", "outLen", "state", "res", "to", "length", "finished", "destroyed", "SHA256_IV", "SHA224_IV", "SHA512_IV", "U32_MASK64", "_32n", "fromBig", "n", "le", "split", "lst", "len", "Ah", "Al", "i", "h", "l", "shrSH", "h", "_l", "s", "shrSL", "l", "rotrSH", "rotrSL", "rotrBH", "rotrBL", "add", "Ah", "Al", "Bh", "Bl", "l", "add3L", "Cl", "add3H", "low", "Ch", "add4L", "Dl", "add4H", "Dh", "add5L", "El", "add5H", "Eh", "SHA256_K", "SHA256_W", "SHA256", "HashMD", "outputLen", "SHA256_IV", "A", "B", "C", "D", "E", "F", "G", "H", "view", "offset", "i", "W15", "W2", "s0", "rotr", "s1", "sigma1", "T1", "Chi", "T2", "Maj", "clean", "SHA224", "SHA224_IV", "K512", "split", "n", "SHA512_Kh", "SHA512_Kl", "SHA512_W_H", "SHA512_W_L", "SHA512", "SHA512_IV", "Ah", "Al", "Bh", "Bl", "Ch", "Cl", "Dh", "Dl", "Eh", "El", "Fh", "Fl", "Gh", "Gl", "Hh", "Hl", "W15h", "W15l", "s0h", "rotrSH", "shrSH", "s0l", "rotrSL", "shrSL", "W2h", "W2l", "s1h", "rotrBH", "s1l", "rotrBL", "SUMl", "add4L", "SUMh", "add4H", "sigma1h", "sigma1l", "CHIh", "CHIl", "T1ll", "add5L", "T1h", "add5H", "T1l", "sigma0h", "sigma0l", "MAJh", "MAJl", "add", "All", "add3L", "add3H", "sha256", "createHasher", "SHA256", "sha224", "SHA224", "sha512", "SHA512", "JSON_KEY_PRINCIPAL", "SELF_AUTHENTICATING_SUFFIX", "ANONYMOUS_SUFFIX", "MANAGEMENT_CANISTER_PRINCIPAL_TEXT_STR", "Principal", "_Principal", "publicKey", "sha", "sha224", "other", "hex", "hexToBytes", "text", "maybePrincipal", "obj", "canisterIdNoDash", "arr", "base32Decode", "principal", "_arr", "bytesToHex", "checksumArrayBuf", "getCrc32", "checksum", "array", "matches", "base32Encode", "i", "cmp", "ErrorKindEnum", "ErrorCode", "isCertified", "errorMessage", "bytesToHex", "AgentError", "_AgentError", "code", "kind", "ErrorKind", "InputError", "_InputError", "ErrorKind", "code", "ErrorKindEnum", "DerDecodeLengthMismatchErrorCode", "_DerDecodeLengthMismatchErrorCode", "ErrorCode", "expectedLength", "actualLength", "DerDecodeErrorCode", "_DerDecodeErrorCode", "error", "DerEncodeErrorCode", "_DerEncodeErrorCode", "HashValueErrorCode", "_HashValueErrorCode", "ErrorCode", "value", "UNREACHABLE_ERROR", "PipeArrayBuffer", "checkPoint", "buffer", "length", "uint8FromBufLike", "num", "result", "buf", "offset", "amount", "b", "v", "bufLike", "compare", "u1", "u2", "i", "uint8Equals", "ilog2", "n", "nBig", "lebEncode", "value", "byteLength", "ilog2", "pipe", "PipeArrayBuffer", "i", "uint8FromBufLike", "bufLike", "uint8Equals", "a", "b", "i", "hashValue", "value", "hashString", "sha256", "lebEncode", "uint8FromBufLike", "vals", "concatBytes", "hashOfMap", "InputError", "HashValueErrorCode", "encoded", "requestIdOf", "request", "map", "sorted", "key", "hashedKey", "hashedValue", "k1", "k2", "compare", "concatenated", "x", "IC_STATE_ROOT_DOMAIN_SEPARATOR", "IC_REQUEST_DOMAIN_SEPARATOR", "IC_RESPONSE_DOMAIN_SEPARATOR", "IC_REQUEST_AUTH_DELEGATION_DOMAIN_SEPARATOR", "SignIdentity", "Principal", "request", "body", "fields", "requestId", "requestIdOf", "concatBytes", "IC_REQUEST_DOMAIN_SEPARATOR", "AnonymousIdentity", "_0n", "_1n", "_abool2", "value", "title", "prefix", "_abytes2", "length", "bytes", "isBytes", "len", "needsLen", "ofLen", "got", "hexToNumber", "hex", "_0n", "bytesToNumberBE", "bytes", "bytesToHex", "bytesToNumberLE", "abytes", "numberToBytesBE", "n", "len", "hexToBytes", "numberToBytesLE", "ensureBytes", "title", "hex", "expectedLength", "res", "hexToBytes", "e", "isBytes", "len", "equalBytes", "a", "b", "diff", "i", "copyBytes", "bytes", "isPosBig", "n", "_0n", "inRange", "min", "max", "aInRange", "title", "bitLen", "len", "_1n", "bitMask", "n", "_1n", "_validateObject", "object", "fields", "optFields", "checkField", "fieldName", "expectedType", "isOpt", "val", "current", "k", "v", "notImplemented", "memoized", "fn", "map", "arg", "args", "computed", "_0n", "_1n", "_2n", "_3n", "_4n", "_5n", "_7n", "_8n", "_9n", "_16n", "mod", "a", "b", "result", "pow2", "x", "power", "modulo", "res", "_0n", "invert", "number", "a", "mod", "b", "y", "_1n", "u", "v", "q", "r", "m", "n", "assertIsSquare", "Fp", "root", "sqrt3mod4", "p1div4", "_4n", "sqrt5mod8", "p5div8", "_5n", "_8n", "n2", "_2n", "nv", "sqrt9mod16", "P", "Fp_", "Field", "tn", "tonelliShanks", "c1", "c2", "c3", "c4", "_7n", "_16n", "tv1", "tv2", "tv3", "tv4", "e1", "e2", "e3", "_3n", "Q", "S", "Z", "_Fp", "FpLegendre", "cc", "Q1div2", "M", "c", "t", "R", "i", "t_tmp", "exponent", "FpSqrt", "_9n", "isNegativeLE", "num", "FIELD_FIELDS", "validateField", "field", "initial", "opts", "map", "val", "_validateObject", "FpPow", "p", "d", "FpInvertBatch", "nums", "passZero", "inverted", "multipliedAcc", "acc", "invertedAcc", "FpLegendre", "Fp", "n", "p1mod2", "_1n", "_2n", "powered", "yes", "zero", "no", "nLength", "n", "nBitLength", "anumber", "_nBitLength", "nByteLength", "Field", "ORDER", "bitLenOrOpts", "isLE", "opts", "_0n", "_nbitLength", "_sqrt", "modFromBytes", "allowedLengths", "_opts", "BITS", "BYTES", "sqrtP", "f", "bitMask", "_1n", "num", "mod", "lhs", "rhs", "power", "FpPow", "invert", "FpSqrt", "numberToBytesLE", "numberToBytesBE", "bytes", "skipValidation", "padded", "scalar", "bytesToNumberLE", "bytesToNumberBE", "lst", "FpInvertBatch", "a", "b", "c", "_0n", "_1n", "negateCt", "condition", "item", "neg", "normalizeZ", "c", "points", "invertedZs", "FpInvertBatch", "p", "i", "validateW", "W", "bits", "calcWOpts", "scalarBits", "windows", "windowSize", "maxNumber", "mask", "bitMask", "shiftBy", "calcOffsets", "n", "window", "wOpts", "wbits", "nextN", "offsetStart", "offset", "isZero", "isNeg", "isNegF", "validateMSMPoints", "validateMSMScalars", "scalars", "field", "s", "pointPrecomputes", "pointWindowSizes", "getW", "P", "assert0", "wNAF", "Point", "elm", "d", "point", "base", "precomputes", "f", "wo", "offsetF", "acc", "transform", "comp", "scalar", "prev", "pippenger", "c", "fieldN", "points", "scalars", "validateMSMPoints", "validateMSMScalars", "plength", "slength", "zero", "wbits", "bitLen", "windowSize", "MASK", "bitMask", "buckets", "lastBits", "sum", "i", "j", "scalar", "resI", "sumI", "createField", "order", "field", "isLE", "validateField", "Field", "_createCurveFields", "type", "CURVE", "curveOpts", "FpFnLE", "p", "val", "_0n", "Fp", "Fn", "params", "_0n", "_1n", "_2n", "_8n", "isEdValidXY", "Fp", "CURVE", "x", "y", "x2", "y2", "left", "right", "edwards", "params", "extraOpts", "validated", "_createCurveFields", "Fn", "cofactor", "_validateObject", "MASK", "modP", "n", "uvRatio", "u", "v", "acoord", "title", "banZero", "min", "aInRange", "aextpoint", "other", "Point", "toAffineMemo", "memoized", "p", "iz", "X", "Y", "Z", "is0", "zz", "assertValidMemo", "a", "d", "T", "X2", "Y2", "Z2", "Z4", "aX2", "XY", "ZT", "bytes", "zip215", "len", "copyBytes", "_abytes2", "_abool2", "normed", "lastByte", "bytesToNumberLE", "max", "isValid", "isXOdd", "isLastByteOdd", "ensureBytes", "windowSize", "isLazy", "wnaf", "X1", "Y1", "Z1", "X1Z2", "X2Z1", "Y1Z2", "Y2Z1", "A", "B", "C", "D", "x1y1", "E", "G", "F", "H", "X3", "Y3", "T3", "Z3", "T1", "T2", "scalar", "f", "normalizeZ", "acc", "invertedZ", "bytesToHex", "points", "scalars", "pippenger", "wNAF", "PrimeEdwardsPoint", "ep", "_bytes", "notImplemented", "_hex", "eddsa", "cHash", "eddsaOpts", "prehash", "BASE", "randomBytes", "adjustScalarBytes", "domain", "data", "ctx", "phflag", "modN_LE", "hash", "getPrivateScalar", "key", "lengths", "hashed", "head", "prefix", "getExtendedPublicKey", "secretKey", "point", "pointBytes", "getPublicKey", "hashDomainToScalar", "context", "msgs", "msg", "concatBytes", "sign", "options", "r", "R", "k", "s", "rs", "verifyOpts", "verify", "sig", "publicKey", "mid", "SB", "_size", "randomSecretKey", "seed", "keygen", "utils", "isValidSecretKey", "isBytes", "isValidPublicKey", "size", "is25519", "_eddsa_legacy_opts_to_new", "c", "Field", "curveOpts", "_eddsa_new_output_to_legacy", "twistedEdwards", "EDDSA", "_0n", "_1n", "_2n", "_3n", "_5n", "_8n", "ed25519_CURVE_p", "ed25519_CURVE", "ed25519_pow_2_252_3", "x", "_10n", "_20n", "_40n", "_80n", "P", "b2", "b4", "pow2", "b5", "b10", "b20", "b40", "b80", "b160", "b240", "b250", "adjustScalarBytes", "bytes", "ED25519_SQRT_M1", "uvRatio", "u", "v", "v3", "mod", "v7", "pow", "vx2", "root1", "root2", "useRoot1", "useRoot2", "noRoot", "isNegativeLE", "Fp", "Field", "Fn", "ed25519Defaults", "sha512", "ed25519", "twistedEdwards", "SQRT_M1", "ED25519_SQRT_M1", "SQRT_AD_MINUS_ONE", "INVSQRT_A_MINUS_D", "ONE_MINUS_D_SQ", "D_MINUS_ONE_SQ", "invertSqrt", "number", "uvRatio", "_1n", "MAX_255B", "bytes255ToNumberLE", "bytes", "ed25519", "bytesToNumberLE", "calcElligatorRistrettoMap", "r0", "d", "ed25519_CURVE", "P", "ed25519_CURVE_p", "mod", "n", "Fp", "r", "Ns", "c", "D", "Ns_D_is_sq", "s", "s_", "isNegativeLE", "Nt", "s2", "W0", "W1", "W2", "W3", "ristretto255_map", "abytes", "r1", "R1", "r2", "R2", "_RistrettoPoint", "__RistrettoPoint", "PrimeEdwardsPoint", "ep", "ap", "other", "hex", "ensureBytes", "a", "equalBytes", "u1", "u2", "u1_2", "u2_2", "v", "isValid", "I", "Dx", "Dy", "x", "y", "t", "_0n", "points", "scalars", "pippenger", "X", "Y", "Z", "T", "u2sq", "invsqrt", "D1", "D2", "zInv", "_x", "_y", "X1", "Y1", "X2", "Y2", "one", "two", "Fn", "encodeLenBytes", "len", "InputError", "DerEncodeErrorCode", "encodeLen", "buf", "offset", "decodeLenBytes", "DerDecodeErrorCode", "decodeLen", "lenBytes", "DER_COSE_OID", "ED25519_OID", "SECP256K1_OID", "BLS12_381_G2_OID", "wrapDER", "payload", "oid", "bitStringHeaderLength", "unwrapDER", "derEncoded", "expect", "n", "msg", "uint8Equals", "payloadLen", "result", "DerDecodeLengthMismatchErrorCode", "isObject", "value", "Ed25519PublicKey", "_Ed25519PublicKey", "maybeKey", "key", "hexToBytes", "view", "uint8FromBufLike", "rawKey", "derKey", "publicKey", "wrapDER", "ED25519_OID", "unwrapped", "unwrapDER", "#rawKey", "#derKey", "Ed25519KeyIdentity", "_Ed25519KeyIdentity", "SignIdentity", "seed", "ed25519", "uint8Equals", "sk", "i", "pk", "obj", "publicKeyDer", "privateKeyRaw", "json", "parsed", "privateKey", "secretKey", "#publicKey", "#privateKey", "bytesToHex", "challenge", "signature", "sig", "msg", "message", "x", "CryptoError", "_CryptoError", "message", "_getEffectiveCrypto", "subtleCrypto", "ECDSAKeyIdentity", "_ECDSAKeyIdentity", "SignIdentity", "options", "extractable", "keyUsages", "effectiveCrypto", "keyPair", "derKey", "uint8FromBufLike", "key", "challenge", "params", "signature", "PartialIdentity", "#inner", "Principal", "inner", "safeBytesToHex", "data", "bytesToHex", "_parseBlob", "value", "hexToBytes", "Delegation", "pubkey", "expiration", "targets", "p", "_createSingleDelegation", "from", "to", "delegation", "challenge", "IC_REQUEST_AUTH_DELEGATION_DOMAIN_SEPARATOR", "requestIdOf", "signature", "DelegationChain", "_DelegationChain", "options", "json", "publicKey", "delegations", "parsedDelegations", "signedDelegation", "t", "Principal", "DelegationIdentity", "SignIdentity", "key", "_inner", "_delegation", "blob", "request", "body", "fields", "requestId", "IC_REQUEST_DOMAIN_SEPARATOR", "PartialDelegationIdentity", "_PartialDelegationIdentity", "PartialIdentity", "#delegation", "inner", "isDelegationValid", "chain", "checks", "scopes", "maybeScope", "s", "scope", "none", "target", "events", "IdleManager", "_IdleManager", "options", "onIdle", "idleTimeout", "_resetTimer", "name", "debounce", "func", "wait", "timeout", "args", "context", "later", "scroll", "callback", "cb", "exit", "instanceOfAny", "object", "constructors", "c", "idbProxyableTypes", "cursorAdvanceMethods", "getIdbProxyableTypes", "getCursorAdvanceMethods", "cursorRequestMap", "transactionDoneMap", "transactionStoreNamesMap", "transformCache", "reverseTransformCache", "promisifyRequest", "request", "promise", "resolve", "reject", "unlisten", "success", "error", "wrap", "value", "cacheDonePromiseForTransaction", "tx", "done", "complete", "idbProxyTraps", "target", "prop", "receiver", "replaceTraps", "callback", "wrapFunction", "func", "storeNames", "args", "unwrap", "transformCachableValue", "newValue", "openDB", "name", "version", "blocked", "upgrade", "blocking", "terminated", "request", "openPromise", "wrap", "event", "db", "readMethods", "writeMethods", "cachedMethods", "getMethod", "target", "prop", "targetFuncName", "useIndex", "isWrite", "method", "storeName", "args", "tx", "replaceTraps", "oldTraps", "receiver", "AUTH_DB_NAME", "OBJECT_STORE_NAME", "_openDbStore", "dbName", "storeName", "version", "KEY_STORAGE_DELEGATION", "KEY_STORAGE_KEY", "openDB", "database", "_getValue", "db", "key", "_setValue", "value", "_removeValue", "IdbKeyVal", "_IdbKeyVal", "_db", "_storeName", "options", "DB_VERSION", "KEY_STORAGE_KEY", "KEY_STORAGE_DELEGATION", "KEY_VECTOR", "DB_VERSION", "LocalStorage", "prefix", "_localStorage", "key", "value", "ls", "IdbStorage", "#options", "options", "resolve", "reject", "IdbKeyVal", "db", "NANOSECONDS_PER_SECOND", "SECONDS_PER_HOUR", "NANOSECONDS_PER_HOUR", "IDENTITY_PROVIDER_DEFAULT", "IDENTITY_PROVIDER_ENDPOINT", "DEFAULT_MAX_TIME_TO_LIVE", "ECDSA_KEY_LABEL", "ED25519_KEY_LABEL", "INTERRUPT_CHECK_INTERVAL", "ERROR_USER_INTERRUPT", "AuthClient", "_AuthClient", "_identity", "_key", "_chain", "_storage", "idleManager", "_createOptions", "_idpWindow", "_eventHandler", "options", "storage", "IdbStorage", "keyType", "key", "maybeIdentityStorage", "KEY_STORAGE_KEY", "fallbackLocalStorage", "LocalStorage", "localChain", "KEY_STORAGE_DELEGATION", "localKey", "error", "Ed25519KeyIdentity", "ECDSAKeyIdentity", "identity", "AnonymousIdentity", "chain", "chainStorage", "DelegationChain", "isDelegationValid", "PartialDelegationIdentity", "DelegationIdentity", "_deleteStorage", "e", "IdleManager", "persistKey", "idleOptions", "message", "onSuccess", "delegations", "signedDelegation", "Delegation", "delegationChain", "loginOptions", "mergeLoginOptions", "maxTimeToLive", "identityProviderUrl", "checkInterruption", "event", "request", "err", "errorMessage", "onError", "KEY_VECTOR", "otherLoginOptions", "customValues", "toStoredKey", "serialized", "DELEGATION_IDENTITY_EXPIRATION", "AUTH_TIMER_INTERVAL", "FromStringToTokenError", "E8S_PER_TOKEN", "isNullish", "argument", "ALPHABET", "LOOKUP_TABLE", "i", "lookUpTable", "AuthClientStore", "_AuthClientStore", "#instance", "#authClient", "u", "AuthClient", "IdbStorage", "KEY_STORAGE_KEY", "delegationChain", "sessionKey", "storage", "KEY_STORAGE_DELEGATION", "onAuthMessage", "data", "msg", "startTimer", "stopTimer", "timer", "onTimerSignOut", "AUTH_TIMER_INTERVAL", "auth", "chain", "checkAuthentication", "checkDelegationChain", "emitExpirationTime", "logout", "AuthClientStore", "delegationChain", "IdbStorage", "KEY_STORAGE_DELEGATION", "delegation", "DelegationChain", "isDelegationValid", "expirationTime", "authRemainingTime", "params", "onAuthMessage"]
7
7
  }