UNPKG

randomness-js

Version:

A library for consuming, verifying and using randomness from the dcipher network

4 lines 4.5 MB
{ "version": 3, "sources": ["../../node_modules/@noble/hashes/src/crypto.ts", "../../node_modules/@noble/hashes/src/utils.ts", "../../node_modules/@noble/curves/src/abstract/utils.ts", "../../node_modules/@noble/curves/src/abstract/modular.ts", "../../node_modules/@noble/curves/src/abstract/hash-to-curve.ts", "../../node_modules/@noble/curves/src/abstract/curve.ts", "../../node_modules/@noble/curves/src/abstract/weierstrass.ts", "../../node_modules/@noble/curves/src/abstract/bls.ts", "../../node_modules/@noble/curves/src/abstract/tower.ts", "../../node_modules/@noble/hashes/src/_assert.ts", "../../node_modules/@noble/hashes/src/_u64.ts", "../../node_modules/@noble/hashes/src/sha3.ts", "../../node_modules/@kevincharm/noble-bn254-drand/dist/src/bn254.js", "../../node_modules/@kevincharm/noble-bn254-drand/dist/src/index.js", "../../node_modules/ethers/src.ts/ethers.ts", "../../node_modules/ethers/src.ts/_version.ts", "../../node_modules/ethers/src.ts/utils/properties.ts", "../../node_modules/ethers/src.ts/utils/errors.ts", "../../node_modules/ethers/src.ts/utils/data.ts", "../../node_modules/ethers/src.ts/utils/maths.ts", "../../node_modules/ethers/src.ts/utils/base58.ts", "../../node_modules/ethers/src.ts/utils/base64-browser.ts", "../../node_modules/ethers/src.ts/utils/events.ts", "../../node_modules/ethers/src.ts/utils/utf8.ts", "../../node_modules/ethers/src.ts/utils/geturl-browser.ts", "../../node_modules/ethers/src.ts/utils/fetch.ts", "../../node_modules/ethers/src.ts/utils/fixednumber.ts", "../../node_modules/ethers/src.ts/utils/rlp-decode.ts", "../../node_modules/ethers/src.ts/utils/rlp-encode.ts", "../../node_modules/ethers/src.ts/utils/units.ts", "../../node_modules/ethers/src.ts/utils/uuid.ts", "../../node_modules/ethers/src.ts/abi/coders/abstract-coder.ts", "../../node_modules/@noble/hashes/src/_assert.ts", "../../node_modules/@noble/hashes/src/crypto.ts", "../../node_modules/@noble/hashes/src/utils.ts", "../../node_modules/@noble/hashes/src/hmac.ts", "../../node_modules/@noble/hashes/src/pbkdf2.ts", "../../node_modules/@noble/hashes/src/_sha2.ts", "../../node_modules/@noble/hashes/src/sha256.ts", "../../node_modules/@noble/hashes/src/_u64.ts", "../../node_modules/@noble/hashes/src/sha512.ts", "../../node_modules/ethers/src.ts/crypto/crypto-browser.ts", "../../node_modules/ethers/src.ts/crypto/hmac.ts", "../../node_modules/@noble/hashes/src/sha3.ts", "../../node_modules/ethers/src.ts/crypto/keccak.ts", "../../node_modules/@noble/hashes/src/ripemd160.ts", "../../node_modules/ethers/src.ts/crypto/ripemd160.ts", "../../node_modules/ethers/src.ts/crypto/pbkdf2.ts", "../../node_modules/ethers/src.ts/crypto/random.ts", "../../node_modules/@noble/hashes/src/scrypt.ts", "../../node_modules/ethers/src.ts/crypto/scrypt.ts", "../../node_modules/ethers/src.ts/crypto/sha2.ts", "../../node_modules/ethers/node_modules/@noble/curves/src/abstract/utils.ts", "../../node_modules/ethers/node_modules/@noble/curves/src/abstract/modular.ts", "../../node_modules/ethers/node_modules/@noble/curves/src/abstract/curve.ts", "../../node_modules/ethers/node_modules/@noble/curves/src/abstract/weierstrass.ts", "../../node_modules/ethers/node_modules/@noble/curves/src/_shortw_utils.ts", "../../node_modules/ethers/node_modules/@noble/curves/src/secp256k1.ts", "../../node_modules/ethers/src.ts/constants/addresses.ts", "../../node_modules/ethers/src.ts/constants/hashes.ts", "../../node_modules/ethers/src.ts/constants/numbers.ts", "../../node_modules/ethers/src.ts/constants/strings.ts", "../../node_modules/ethers/src.ts/crypto/signature.ts", "../../node_modules/ethers/src.ts/crypto/signing-key.ts", "../../node_modules/ethers/src.ts/crypto/index.ts", "../../node_modules/ethers/src.ts/address/address.ts", "../../node_modules/ethers/src.ts/address/contract-address.ts", "../../node_modules/ethers/src.ts/address/checks.ts", "../../node_modules/ethers/src.ts/abi/typed.ts", "../../node_modules/ethers/src.ts/abi/coders/address.ts", "../../node_modules/ethers/src.ts/abi/coders/anonymous.ts", "../../node_modules/ethers/src.ts/abi/coders/array.ts", "../../node_modules/ethers/src.ts/abi/coders/boolean.ts", "../../node_modules/ethers/src.ts/abi/coders/bytes.ts", "../../node_modules/ethers/src.ts/abi/coders/fixed-bytes.ts", "../../node_modules/ethers/src.ts/abi/coders/null.ts", "../../node_modules/ethers/src.ts/abi/coders/number.ts", "../../node_modules/ethers/src.ts/abi/coders/string.ts", "../../node_modules/ethers/src.ts/abi/coders/tuple.ts", "../../node_modules/ethers/src.ts/hash/id.ts", "../../node_modules/@adraffy/ens-normalize/dist/index.mjs", "../../node_modules/ethers/src.ts/hash/namehash.ts", "../../node_modules/ethers/src.ts/transaction/accesslist.ts", "../../node_modules/ethers/src.ts/transaction/address.ts", "../../node_modules/ethers/src.ts/transaction/transaction.ts", "../../node_modules/ethers/src.ts/hash/message.ts", "../../node_modules/ethers/src.ts/hash/solidity.ts", "../../node_modules/ethers/src.ts/hash/typed-data.ts", "../../node_modules/ethers/src.ts/abi/fragments.ts", "../../node_modules/ethers/src.ts/abi/abi-coder.ts", "../../node_modules/ethers/src.ts/abi/bytes32.ts", "../../node_modules/ethers/src.ts/abi/interface.ts", "../../node_modules/ethers/src.ts/providers/provider.ts", "../../node_modules/ethers/src.ts/contract/wrappers.ts", "../../node_modules/ethers/src.ts/contract/contract.ts", "../../node_modules/ethers/src.ts/contract/factory.ts", "../../node_modules/ethers/src.ts/providers/ens-resolver.ts", "../../node_modules/ethers/src.ts/providers/format.ts", "../../node_modules/ethers/src.ts/providers/plugins-network.ts", "../../node_modules/ethers/src.ts/providers/network.ts", "../../node_modules/ethers/src.ts/providers/subscriber-polling.ts", "../../node_modules/ethers/src.ts/providers/abstract-provider.ts", "../../node_modules/ethers/src.ts/providers/abstract-signer.ts", "../../node_modules/ethers/src.ts/providers/community.ts", "../../node_modules/ethers/src.ts/providers/subscriber-filterid.ts", "../../node_modules/ethers/src.ts/providers/provider-jsonrpc.ts", "../../node_modules/ethers/src.ts/providers/provider-ankr.ts", "../../node_modules/ethers/src.ts/providers/provider-alchemy.ts", "../../node_modules/ethers/src.ts/providers/provider-chainstack.ts", "../../node_modules/ethers/src.ts/providers/provider-cloudflare.ts", "../../node_modules/ethers/src.ts/providers/provider-etherscan.ts", "../../node_modules/ethers/src.ts/providers/ws-browser.ts", "../../node_modules/ethers/src.ts/providers/provider-socket.ts", "../../node_modules/ethers/src.ts/providers/provider-websocket.ts", "../../node_modules/ethers/src.ts/providers/provider-infura.ts", "../../node_modules/ethers/src.ts/providers/provider-quicknode.ts", "../../node_modules/ethers/src.ts/providers/provider-fallback.ts", "../../node_modules/ethers/src.ts/providers/default-provider.ts", "../../node_modules/ethers/src.ts/providers/signer-noncemanager.ts", "../../node_modules/ethers/src.ts/providers/provider-browser.ts", "../../node_modules/ethers/src.ts/providers/provider-pocket.ts", "../../node_modules/ethers/src.ts/providers/provider-ipcsocket-browser.ts", "../../node_modules/ethers/src.ts/wallet/base-wallet.ts", "../../node_modules/ethers/src.ts/wordlists/decode-owl.ts", "../../node_modules/ethers/src.ts/wordlists/wordlist.ts", "../../node_modules/ethers/src.ts/wordlists/wordlist-owl.ts", "../../node_modules/ethers/src.ts/wordlists/lang-en.ts", "../../node_modules/ethers/src.ts/wallet/mnemonic.ts", "../../node_modules/aes-js/src.ts/aes.ts", "../../node_modules/aes-js/src.ts/mode.ts", "../../node_modules/aes-js/src.ts/mode-cbc.ts", "../../node_modules/aes-js/src.ts/mode-ctr.ts", "../../node_modules/aes-js/src.ts/padding.ts", "../../node_modules/ethers/src.ts/wallet/utils.ts", "../../node_modules/ethers/src.ts/wallet/json-keystore.ts", "../../node_modules/ethers/src.ts/wallet/hdwallet.ts", "../../node_modules/ethers/src.ts/wallet/json-crowdsale.ts", "../../node_modules/ethers/src.ts/wallet/wallet.ts", "../../node_modules/ethers/src.ts/wordlists/bit-reader.ts", "../../node_modules/ethers/src.ts/wordlists/decode-owla.ts", "../../node_modules/ethers/src.ts/wordlists/wordlist-owla.ts", "../../node_modules/ethers/src.ts/wordlists/wordlists-browser.ts", "../../src/index.ts", "../../node_modules/@noble/curves/src/abstract/utils.ts", "../../src/ethers-helpers.ts", "../../src/generated/factories/Base.t.sol/Base__factory.ts", "../../src/generated/factories/ChainlinkVRFV2_5Integration_DirectFunding.t.sol/ChainlinkVRFV2_5Integration_DirectFundingTest__factory.ts", "../../src/generated/factories/ChainlinkVRFV2_5Integration_Subscription.t.sol/ChainlinkVRFV2_5Integration_SubscriptionTest__factory.ts", "../../src/generated/factories/Deployment.t.sol/Deployment__factory.ts", "../../src/generated/factories/DirectFunding.t.sol/DirectFundingTest__factory.ts", "../../src/generated/factories/Randomness.t.sol/RandomnessTest__factory.ts", "../../src/generated/factories/StdError.sol/StdError__factory.ts", "../../src/generated/factories/StdStorage.sol/StdStorageSafe__factory.ts", "../../src/generated/factories/SubscriptionFunding.t.sol/SubscriptionFundingTest__factory.ts", "../../src/generated/factories/Vm.sol/Vm__factory.ts", "../../src/generated/factories/Vm.sol/VmSafe__factory.ts", "../../src/generated/factories/draft-IERC1822.sol/IERC1822Proxiable__factory.ts", "../../src/generated/factories/AccessControl__factory.ts", "../../src/generated/factories/AccessControlEnumerableUpgradeable__factory.ts", "../../src/generated/factories/AccessControlUpgradeable__factory.ts", "../../src/generated/factories/Address__factory.ts", "../../src/generated/factories/BLS__factory.ts", "../../src/generated/factories/BLSTest__factory.ts", "../../src/generated/factories/BN254SignatureScheme__factory.ts", "../../src/generated/factories/BytesLib__factory.ts", "../../src/generated/factories/ChainlinkVRFCoordinatorV2_5Adapter__factory.ts", "../../src/generated/factories/ChainlinkVRFDirectFundingConsumer__factory.ts", "../../src/generated/factories/ChainlinkVRFSubscriptionConsumer__factory.ts", "../../src/generated/factories/ChainlinkVRFV2PlusWrapperAdapter__factory.ts", "../../src/generated/factories/ChainlinkVRFV2PlusWrapperConsumerBaseStub__factory.ts", "../../src/generated/factories/ConfirmedOwner__factory.ts", "../../src/generated/factories/ConfirmedOwnerWithProposal__factory.ts", "../../src/generated/factories/ContextUpgradeable__factory.ts", "../../src/generated/factories/ERC165__factory.ts", "../../src/generated/factories/ERC165Upgradeable__factory.ts", "../../src/generated/factories/ERC1967Proxy__factory.ts", "../../src/generated/factories/ERC1967Utils__factory.ts", "../../src/generated/factories/Errors__factory.ts", "../../src/generated/factories/Factory__factory.ts", "../../src/generated/factories/FeeCollector__factory.ts", "../../src/generated/factories/FeistelShuffleOptimised__factory.ts", "../../src/generated/factories/IAccessControl__factory.ts", "../../src/generated/factories/IAccessControlEnumerable__factory.ts", "../../src/generated/factories/IBeacon__factory.ts", "../../src/generated/factories/IERC165__factory.ts", "../../src/generated/factories/IERC1967__factory.ts", "../../src/generated/factories/IMulticall3__factory.ts", "../../src/generated/factories/IOwnable__factory.ts", "../../src/generated/factories/IRandomnessReceiver__factory.ts", "../../src/generated/factories/IRandomnessSender__factory.ts", "../../src/generated/factories/ISignatureReceiver__factory.ts", "../../src/generated/factories/ISignatureScheme__factory.ts", "../../src/generated/factories/ISignatureSchemeAddressProvider__factory.ts", "../../src/generated/factories/ISignatureSender__factory.ts", "../../src/generated/factories/ISubscription__factory.ts", "../../src/generated/factories/ITypeAndVersion__factory.ts", "../../src/generated/factories/IVRFCoordinatorV2Plus__factory.ts", "../../src/generated/factories/IVRFMigratableConsumerV2Plus__factory.ts", "../../src/generated/factories/IVRFSubscriptionV2Plus__factory.ts", "../../src/generated/factories/IVRFV2PlusWrapper__factory.ts", "../../src/generated/factories/Initializable__factory.ts", "../../src/generated/factories/LinkTokenInterface__factory.ts", "../../src/generated/factories/MockRandomnessReceiver__factory.ts", "../../src/generated/factories/MockRevertingRandomnessReceiver__factory.ts", "../../src/generated/factories/Multicall__factory.ts", "../../src/generated/factories/Proxy__factory.ts", "../../src/generated/factories/Randomness__factory.ts", "../../src/generated/factories/RandomnessReceiverBase__factory.ts", "../../src/generated/factories/RandomnessSender__factory.ts", "../../src/generated/factories/ReentrancyGuard__factory.ts", "../../src/generated/factories/SignatureReceiverBase__factory.ts", "../../src/generated/factories/SignatureSchemeAddressProvider__factory.ts", "../../src/generated/factories/SignatureSchemeBase__factory.ts", "../../src/generated/factories/SignatureSender__factory.ts", "../../src/generated/factories/StdAssertions__factory.ts", "../../src/generated/factories/StdInvariant__factory.ts", "../../src/generated/factories/SubscriptionAPI__factory.ts", "../../src/generated/factories/Test__factory.ts", "../../src/generated/factories/UUPSProxy__factory.ts", "../../src/generated/factories/UUPSUpgradeable__factory.ts", "../../src/generated/factories/VRFConsumerBaseV2Plus__factory.ts", "../../src/generated/factories/VRFV2PlusClient__factory.ts", "../../src/generated/factories/VRFV2PlusWrapperConsumerBase__factory.ts", "../../src/networks.ts"], "sourcesContent": ["// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// See utils.ts for details.\ndeclare const globalThis: Record<string, any> | undefined;\nexport const crypto =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\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, we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\nconst u8a = (a: any): a is Uint8Array => a instanceof Uint8Array;\n// Cast array to different type\nexport const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr: TypedArray) =>\n new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\n// Cast array to view\nexport const createView = (arr: TypedArray) =>\n new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word: number, shift: number) => (word << (32 - shift)) | (word >>> shift);\n\n// big-endian hardware is rare. Just in case someone still decides to run hashes:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE) throw new Error('Non little-endian hardware is not supported');\n\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n if (!u8a(bytes)) throw new Error('Uint8Array expected');\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/**\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 const len = hex.length;\n if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n const array = new Uint8Array(len / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\n\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => {};\n\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters: number, tick: number, cb: (i: number) => 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 in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\nexport type Input = Uint8Array | string;\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 if (!u8a(data)) throw new Error(`expected Uint8Array, got ${typeof data}`);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n let pad = 0; // walk through each item, ensure they have proper type\n arrays.forEach((a) => {\n if (!u8a(a)) throw new Error('Uint8Array expected');\n r.set(a, pad);\n pad += a.length;\n });\n return r;\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 clone(): T {\n return this._cloneInto();\n }\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\nconst toStr = {}.toString;\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && toStr.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\nexport type CHash = ReturnType<typeof wrapConstructor>;\n\nexport function wrapConstructor<T extends Hash<T>>(hashCons: () => Hash<T>) {\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 wrapConstructorWithOpts<H extends Hash<H>, T extends Object>(\n hashCons: (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 wrapXOFConstructorWithOpts<H extends HashXOF<H>, T extends Object>(\n hashCons: (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}\n\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n", "/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nexport 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 isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\nexport function abytes(item: unknown): void {\n if (!isBytes(item)) throw new Error('Uint8Array expected');\n}\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// 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 * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\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// 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 * @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 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// 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. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: 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/**\n * Copies several Uint8Arrays into one.\n */\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\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// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([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// 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 */\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 => (_2n << BigInt(n - 1)) - _1n;\n\n// DRBG\n\nconst u8n = (data?: any) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr: any) => Uint8Array.from(arr); // another shortcut\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 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()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000) 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\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 finite fields.\n * A finite field over 11 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 bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from './utils.js';\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), _8n = /* @__PURE__ */ BigInt(8);\n// prettier-ignore\nconst _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 * @todo use field version && remove\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (modulo <= _0n) throw new Error('invalid modulus');\n if (modulo === _1n) return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n) res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\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\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) \u2261 1 if a is a square (mod p)\n // (a | p) \u2261 -1 if a is not a square (mod p)\n // (a | p) \u2261 0 if a \u2261 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n\n let Q: bigint, S: number, Z: bigint;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++);\n\n // Step 2: Select a non-square z such that (z | p) \u2261 -1 and set c \u2261 zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++) {\n // Crash instead of infinity loop, we cannot reasonable count until P.\n if (Z > 1000) throw new Error('Cannot find square root: likely non-prime P');\n }\n\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast<T>(Fp: IField<T>, n: T) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow<T>(Fp: IField<T>, n: T): T {\n // Step 0: Check that n is indeed a square: (n | p) should not be \u2261 -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE)) break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\n\n/**\n * Square root for a finite field. It will try to check if optimizations are applicable and fall back to 4:\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)\n // \u221An = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4<T>(Fp: IField<T>, n: T) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Atkin algorithm for q \u2261 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8<T>(Fp: IField<T>, n: T) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // P \u2261 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\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 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 // legendre?(num: T): T;\n pow(lhs: T, power: bigint): T;\n invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array): 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: 'isSafeInteger',\n BITS: 'isSafeInteger',\n } as Record<string, string>;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\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>(f: IField<T>, num: T, power: bigint): T {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return f.ONE;\n if (power === _1n) return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch<T>(f: IField<T>, nums: T[]): T[] {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\n\nexport function FpDiv<T>(f: IField<T>, lhs: T, rhs: T | bigint): T {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\n\n/**\n * Legendre symbol.\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(order: bigint): <T>(f: IField<T>, x: T) => T {\n const legendreConst = (order - _1n) / _2n; // Integer arithmetic\n return <T>(f: IField<T>, x: T): T => f.pow(x, legendreConst);\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare<T>(f: IField<T>): (x: T) => boolean {\n const legendre = FpLegendre(f.ORDER);\n return (x: T): boolean => {\n const p = legendre(f, x);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n\n// CURVE.n lengths\nexport function nLength(\n n: bigint,\n nBitLength?: number\n): {\n nBitLength: number;\n nByteLength: number;\n} {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;\n/**\n * Initializes a finite field over prime.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * 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 * @param ORDER prime pos