From 95dbf208c39bbc53b560a5fadeed688ece00c15d Mon Sep 17 00:00:00 2001 From: tornadocontrib Date: Thu, 19 Sep 2024 17:49:25 +0000 Subject: [PATCH] tornado-core 1.0.3 * Removed polygon gas oracle and use default oracle provided by ethers.js * Simplify events saving process * Use codeberg.org to fetch dependencies * Update dependencies --- .npmrc | 1 - dist/events/base.d.ts | 10 +- dist/events/types.d.ts | 3 + dist/index.js | 6425 +++-- dist/index.mjs | 6427 +++-- dist/index.umd.js | 37861 ++++++++++++-------------- dist/merkleTreeWorker.js | 18865 +------------ dist/merkleTreeWorker.umd.js | 28146 +++++++++---------- dist/networkConfig.d.ts | 4 +- dist/providers.d.ts | 8 +- dist/typechain/factories/index.d.ts | 1 - dist/typechain/index.d.ts | 2 - dist/utils.d.ts | 2 - package.json | 48 +- rollup.config.mjs | 2 +- src/abi/GasPriceOracle.json | 189 - src/events/base.ts | 16 +- src/events/types.ts | 4 + src/networkConfig.ts | 3 - src/providers.ts | 132 +- src/schemas/index.ts | 2 +- src/typechain/factories/index.ts | 1 - src/typechain/index.ts | 2 - tsconfig.json | 2 +- webpack.config.js | 2 - yarn.lock | 1629 +- 26 files changed, 37280 insertions(+), 62507 deletions(-) delete mode 100644 .npmrc delete mode 100644 src/abi/GasPriceOracle.json diff --git a/.npmrc b/.npmrc deleted file mode 100644 index 05ba80e..0000000 --- a/.npmrc +++ /dev/null @@ -1 +0,0 @@ -@tornado:registry=https://git.tornado.ws/api/packages/tornado-packages/npm/ \ No newline at end of file diff --git a/dist/events/base.d.ts b/dist/events/base.d.ts index 7e8379e..36fd0b3 100644 --- a/dist/events/base.d.ts +++ b/dist/events/base.d.ts @@ -3,7 +3,7 @@ import type { Tornado, TornadoRouter, TornadoProxyLight, Governance, RelayerRegi import { BatchEventsService, BatchBlockService, BatchTransactionService, BatchEventOnProgress, BatchBlockOnProgress } from '../batch'; import { fetchDataOptions } from '../providers'; import type { NetIdType } from '../networkConfig'; -import type { BaseEvents, MinimalEvents, DepositsEvents, WithdrawalsEvents, EncryptedNotesEvents, AllGovernanceEvents, RegistersEvents, EchoEvents } from './types'; +import type { BaseEvents, CachedEvents, MinimalEvents, DepositsEvents, WithdrawalsEvents, EncryptedNotesEvents, AllGovernanceEvents, RegistersEvents, EchoEvents } from './types'; export declare const DEPOSIT = "deposit"; export declare const WITHDRAWAL = "withdrawal"; export type BaseEventsServiceConstructor = { @@ -38,7 +38,6 @@ export declare class BaseEventsService { deployedBlock: number; batchEventsService: BatchEventsService; fetchDataOptions?: fetchDataOptions; - saveEventsPromise?: Promise; constructor({ netId, provider, graphApi, subgraphName, contract, type, deployedBlock, fetchDataOptions, }: BaseEventsServiceConstructor); getInstanceName(): string; getType(): string; @@ -53,8 +52,11 @@ export declare class BaseEventsService { * Get saved or cached events */ getEventsFromDB(): Promise>; - getEventsFromCache(): Promise>; - getSavedEvents(): Promise>; + /** + * Events from remote cache (Either from local cache, CDN, or from IPFS) + */ + getEventsFromCache(): Promise>; + getSavedEvents(): Promise | CachedEvents>; /** * Get latest events */ diff --git a/dist/events/types.d.ts b/dist/events/types.d.ts index 51cadee..1fa73a5 100644 --- a/dist/events/types.d.ts +++ b/dist/events/types.d.ts @@ -3,6 +3,9 @@ export interface BaseEvents { events: T[]; lastBlock: number | null; } +export interface CachedEvents extends BaseEvents { + fromCache: boolean; +} export interface BaseGraphEvents { events: T[]; lastSyncBlock: number; diff --git a/dist/index.js b/dist/index.js index 8e022e6..1e154d1 100644 --- a/dist/index.js +++ b/dist/index.js @@ -31,7 +31,3013 @@ function _interopNamespaceDefault(e) { var websnarkUtils__namespace = /*#__PURE__*/_interopNamespaceDefault(websnarkUtils); -const _abi$6 = [ +BigInt.prototype.toJSON = function() { + return this.toString(); +}; +const isNode = !process.browser && typeof globalThis.window === "undefined"; +const crypto = isNode ? crypto$1.webcrypto : globalThis.crypto; +const chunk = (arr, size) => [...Array(Math.ceil(arr.length / size))].map((_, i) => arr.slice(size * i, size + size * i)); +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} +function validateUrl(url, protocols) { + try { + const parsedUrl = new URL(url); + if (protocols && protocols.length) { + return protocols.map((p) => p.toLowerCase()).includes(parsedUrl.protocol); + } + return true; + } catch (e) { + return false; + } +} +function concatBytes(...arrays) { + const totalSize = arrays.reduce((acc, e) => acc + e.length, 0); + const merged = new Uint8Array(totalSize); + arrays.forEach((array, i, arrays2) => { + const offset = arrays2.slice(0, i).reduce((acc, e) => acc + e.length, 0); + merged.set(array, offset); + }); + return merged; +} +function bufferToBytes(b) { + return new Uint8Array(b.buffer); +} +function bytesToBase64(bytes) { + return btoa(String.fromCharCode.apply(null, Array.from(bytes))); +} +function base64ToBytes(base64) { + return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)); +} +function bytesToHex(bytes) { + return "0x" + Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""); +} +function hexToBytes(hexString) { + if (hexString.slice(0, 2) === "0x") { + hexString = hexString.replace("0x", ""); + } + if (hexString.length % 2 !== 0) { + hexString = "0" + hexString; + } + return Uint8Array.from(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); +} +function bytesToBN(bytes) { + return BigInt(bytesToHex(bytes)); +} +function bnToBytes(bigint) { + let hexString = typeof bigint === "bigint" ? bigint.toString(16) : bigint; + if (hexString.startsWith("0x")) { + hexString = hexString.replace("0x", ""); + } + if (hexString.length % 2 !== 0) { + hexString = "0" + hexString; + } + return Uint8Array.from(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); +} +function leBuff2Int(bytes) { + return new BN(bytes, 16, "le"); +} +function leInt2Buff(bigint) { + return Uint8Array.from(new BN(bigint).toArray("le", 31)); +} +function toFixedHex(numberish, length = 32) { + return "0x" + BigInt(numberish).toString(16).padStart(length * 2, "0"); +} +function toFixedLength(string, length = 32) { + string = string.replace("0x", ""); + return "0x" + string.padStart(length * 2, "0"); +} +function rBigInt(nbytes = 31) { + return bytesToBN(crypto.getRandomValues(new Uint8Array(nbytes))); +} +function bigIntReplacer(key, value) { + return typeof value === "bigint" ? value.toString() : value; +} +function substring(str, length = 10) { + if (str.length < length * 2) { + return str; + } + return `${str.substring(0, length)}...${str.substring(str.length - length)}`; +} + +var __defProp$4 = Object.defineProperty; +var __defProps$3 = Object.defineProperties; +var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols; +var __getProtoOf$1 = Object.getPrototypeOf; +var __hasOwnProp$4 = Object.prototype.hasOwnProperty; +var __propIsEnum$4 = Object.prototype.propertyIsEnumerable; +var __reflectGet$1 = Reflect.get; +var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$4 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$4.call(b, prop)) + __defNormalProp$4(a, prop, b[prop]); + if (__getOwnPropSymbols$4) + for (var prop of __getOwnPropSymbols$4(b)) { + if (__propIsEnum$4.call(b, prop)) + __defNormalProp$4(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b)); +var __superGet$1 = (cls, obj, key) => __reflectGet$1(__getProtoOf$1(cls), key, obj); +var __async$c = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +const defaultUserAgent = "Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/115.0"; +const fetch = crossFetch; +function getHttpAgent({ + fetchUrl, + proxyUrl, + torPort, + retry +}) { + const { HttpProxyAgent } = require("http-proxy-agent"); + const { HttpsProxyAgent } = require("https-proxy-agent"); + const { SocksProxyAgent } = require("socks-proxy-agent"); + if (torPort) { + return new SocksProxyAgent(`socks5h://tor${retry}@127.0.0.1:${torPort}`); + } + if (!proxyUrl) { + return; + } + const isHttps = fetchUrl.includes("https://"); + if (proxyUrl.includes("socks://") || proxyUrl.includes("socks4://") || proxyUrl.includes("socks5://")) { + return new SocksProxyAgent(proxyUrl); + } + if (proxyUrl.includes("http://") || proxyUrl.includes("https://")) { + if (isHttps) { + return new HttpsProxyAgent(proxyUrl); + } + return new HttpProxyAgent(proxyUrl); + } +} +function fetchData(_0) { + return __async$c(this, arguments, function* (url, options = {}) { + var _a, _b, _c; + const MAX_RETRY = (_a = options.maxRetry) != null ? _a : 3; + const RETRY_ON = (_b = options.retryOn) != null ? _b : 500; + const userAgent = (_c = options.userAgent) != null ? _c : defaultUserAgent; + let retry = 0; + let errorObject; + if (!options.method) { + if (!options.body) { + options.method = "GET"; + } else { + options.method = "POST"; + } + } + if (!options.headers) { + options.headers = {}; + } + if (isNode && !options.headers["User-Agent"]) { + options.headers["User-Agent"] = userAgent; + } + while (retry < MAX_RETRY + 1) { + let timeout; + if (!options.signal && options.timeout) { + const controller = new AbortController(); + options.signal = controller.signal; + timeout = setTimeout(() => { + controller.abort(); + }, options.timeout); + } + if (!options.agent && isNode && (options.proxy || options.torPort)) { + options.agent = getHttpAgent({ + fetchUrl: url, + proxyUrl: options.proxy, + torPort: options.torPort, + retry + }); + } + if (options.debug && typeof options.debug === "function") { + options.debug("request", { + url, + retry, + errorObject, + options + }); + } + try { + const resp = yield fetch(url, { + method: options.method, + headers: options.headers, + body: options.body, + redirect: options.redirect, + signal: options.signal, + agent: options.agent + }); + if (options.debug && typeof options.debug === "function") { + options.debug("response", resp); + } + if (!resp.ok) { + const errMsg = `Request to ${url} failed with error code ${resp.status}: +` + (yield resp.text()); + throw new Error(errMsg); + } + if (options.returnResponse) { + return resp; + } + const contentType = resp.headers.get("content-type"); + if (contentType == null ? void 0 : contentType.includes("application/json")) { + return yield resp.json(); + } + if (contentType == null ? void 0 : contentType.includes("text")) { + return yield resp.text(); + } + return resp; + } catch (error) { + if (timeout) { + clearTimeout(timeout); + } + errorObject = error; + retry++; + yield sleep(RETRY_ON); + } finally { + if (timeout) { + clearTimeout(timeout); + } + } + } + if (options.debug && typeof options.debug === "function") { + options.debug("error", errorObject); + } + throw errorObject; + }); +} +const fetchGetUrlFunc = (options = {}) => (req, _signal) => __async$c(void 0, null, function* () { + let signal; + if (_signal) { + const controller = new AbortController(); + signal = controller.signal; + _signal.addListener(() => { + controller.abort(); + }); + } + const init = __spreadProps$3(__spreadValues$4({}, options), { + method: req.method || "POST", + headers: req.headers, + body: req.body || void 0, + signal, + returnResponse: true + }); + const resp = yield fetchData(req.url, init); + const headers = {}; + resp.headers.forEach((value, key) => { + headers[key.toLowerCase()] = value; + }); + const respBody = yield resp.arrayBuffer(); + const body = respBody == null ? null : new Uint8Array(respBody); + return { + statusCode: resp.status, + statusMessage: resp.statusText, + headers, + body + }; +}); +function getProvider(rpcUrl, fetchOptions) { + return __async$c(this, null, function* () { + const fetchReq = new ethers.FetchRequest(rpcUrl); + fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); + const staticNetwork = yield new ethers.JsonRpcProvider(fetchReq).getNetwork(); + const provider = new ethers.JsonRpcProvider(fetchReq, staticNetwork, { + staticNetwork, + pollingInterval: (fetchOptions == null ? void 0 : fetchOptions.pollingInterval) || 1e3 + }); + return provider; + }); +} +function getProviderWithNetId(netId, rpcUrl, config, fetchOptions) { + const { networkName, reverseRecordsContract, pollInterval } = config; + const hasEns = Boolean(reverseRecordsContract); + const fetchReq = new ethers.FetchRequest(rpcUrl); + fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); + const staticNetwork = new ethers.Network(networkName, netId); + if (hasEns) { + staticNetwork.attachPlugin(new ethers.EnsPlugin(null, Number(netId))); + } + staticNetwork.attachPlugin(new ethers.GasCostPlugin()); + const provider = new ethers.JsonRpcProvider(fetchReq, staticNetwork, { + staticNetwork, + pollingInterval: (fetchOptions == null ? void 0 : fetchOptions.pollingInterval) || pollInterval * 1e3 + }); + return provider; +} +const populateTransaction = (signer, tx) => __async$c(void 0, null, function* () { + const provider = signer.provider; + if (!tx.from) { + tx.from = signer.address; + } else if (tx.from !== signer.address) { + const errMsg = `populateTransaction: signer mismatch for tx, wants ${tx.from} have ${signer.address}`; + throw new Error(errMsg); + } + const [feeData, nonce] = yield Promise.all([ + (() => __async$c(void 0, null, function* () { + if (tx.maxFeePerGas && tx.maxPriorityFeePerGas) { + return new ethers.FeeData(null, BigInt(tx.maxFeePerGas), BigInt(tx.maxPriorityFeePerGas)); + } + if (tx.gasPrice) { + return new ethers.FeeData(BigInt(tx.gasPrice), null, null); + } + const fetchedFeeData = yield provider.getFeeData(); + if (fetchedFeeData.maxFeePerGas && fetchedFeeData.maxPriorityFeePerGas) { + return new ethers.FeeData( + null, + fetchedFeeData.maxFeePerGas * (BigInt(1e4) + BigInt(signer.gasPriceBump)) / BigInt(1e4), + fetchedFeeData.maxPriorityFeePerGas + ); + } else { + return new ethers.FeeData( + fetchedFeeData.gasPrice * (BigInt(1e4) + BigInt(signer.gasPriceBump)) / BigInt(1e4), + null, + null + ); + } + }))(), + (() => __async$c(void 0, null, function* () { + if (tx.nonce) { + return tx.nonce; + } + let fetchedNonce = yield provider.getTransactionCount(signer.address, "pending"); + if (signer.bumpNonce && signer.nonce && signer.nonce >= fetchedNonce) { + console.log( + `populateTransaction: bumping nonce from ${fetchedNonce} to ${fetchedNonce + 1} for ${signer.address}` + ); + fetchedNonce++; + } + return fetchedNonce; + }))() + ]); + tx.nonce = nonce; + if (feeData.maxFeePerGas && feeData.maxPriorityFeePerGas) { + tx.maxFeePerGas = feeData.maxFeePerGas; + tx.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; + if (!tx.type) { + tx.type = 2; + } + delete tx.gasPrice; + } else if (feeData.gasPrice) { + tx.gasPrice = feeData.gasPrice; + if (!tx.type) { + tx.type = 0; + } + delete tx.maxFeePerGas; + delete tx.maxPriorityFeePerGas; + } + tx.gasLimit = tx.gasLimit || (yield (() => __async$c(void 0, null, function* () { + try { + const gasLimit = yield provider.estimateGas(tx); + return gasLimit === BigInt(21e3) ? gasLimit : gasLimit * (BigInt(1e4) + BigInt(signer.gasLimitBump)) / BigInt(1e4); + } catch (err) { + if (signer.gasFailover) { + console.log("populateTransaction: warning gas estimation failed falling back to 3M gas"); + return BigInt("3000000"); + } + throw err; + } + }))()); + return tx; +}); +class TornadoWallet extends ethers.Wallet { + constructor(key, provider, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce } = {}) { + super(key, provider); + this.gasPriceBump = gasPriceBump != null ? gasPriceBump : 0; + this.gasLimitBump = gasLimitBump != null ? gasLimitBump : 3e3; + this.gasFailover = gasFailover != null ? gasFailover : false; + this.bumpNonce = bumpNonce != null ? bumpNonce : false; + } + static fromMnemonic(mneomnic, provider, index = 0, options) { + const defaultPath = `m/44'/60'/0'/0/${index}`; + const { privateKey } = ethers.HDNodeWallet.fromPhrase(mneomnic, void 0, defaultPath); + return new TornadoWallet(privateKey, provider, options); + } + populateTransaction(tx) { + return __async$c(this, null, function* () { + const txObject = yield populateTransaction(this, tx); + this.nonce = txObject.nonce; + return __superGet$1(TornadoWallet.prototype, this, "populateTransaction").call(this, txObject); + }); + } +} +class TornadoVoidSigner extends ethers.VoidSigner { + constructor(address, provider, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce } = {}) { + super(address, provider); + this.gasPriceBump = gasPriceBump != null ? gasPriceBump : 0; + this.gasLimitBump = gasLimitBump != null ? gasLimitBump : 3e3; + this.gasFailover = gasFailover != null ? gasFailover : false; + this.bumpNonce = bumpNonce != null ? bumpNonce : false; + } + populateTransaction(tx) { + return __async$c(this, null, function* () { + const txObject = yield populateTransaction(this, tx); + this.nonce = txObject.nonce; + return __superGet$1(TornadoVoidSigner.prototype, this, "populateTransaction").call(this, txObject); + }); + } +} +class TornadoRpcSigner extends ethers.JsonRpcSigner { + constructor(provider, address, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce } = {}) { + super(provider, address); + this.gasPriceBump = gasPriceBump != null ? gasPriceBump : 0; + this.gasLimitBump = gasLimitBump != null ? gasLimitBump : 3e3; + this.gasFailover = gasFailover != null ? gasFailover : false; + this.bumpNonce = bumpNonce != null ? bumpNonce : false; + } + sendUncheckedTransaction(tx) { + return __async$c(this, null, function* () { + return __superGet$1(TornadoRpcSigner.prototype, this, "sendUncheckedTransaction").call(this, yield populateTransaction(this, tx)); + }); + } +} +class TornadoBrowserProvider extends ethers.BrowserProvider { + constructor(ethereum, network, options) { + super(ethereum, network); + this.options = options; + } + getSigner(address) { + return __async$c(this, null, function* () { + var _a, _b, _c, _d, _e, _f, _g, _h, _i; + const signerAddress = (yield __superGet$1(TornadoBrowserProvider.prototype, this, "getSigner").call(this, address)).address; + if (((_a = this.options) == null ? void 0 : _a.webChainId) && ((_b = this.options) == null ? void 0 : _b.connectWallet) && Number(yield __superGet$1(TornadoBrowserProvider.prototype, this, "send").call(this, "eth_chainId", [])) !== Number((_c = this.options) == null ? void 0 : _c.webChainId)) { + yield this.options.connectWallet(); + } + if ((_d = this.options) == null ? void 0 : _d.handleNetworkChanges) { + (_e = window == null ? void 0 : window.ethereum) == null ? void 0 : _e.on("chainChanged", this.options.handleNetworkChanges); + } + if ((_f = this.options) == null ? void 0 : _f.handleAccountChanges) { + (_g = window == null ? void 0 : window.ethereum) == null ? void 0 : _g.on("accountsChanged", this.options.handleAccountChanges); + } + if ((_h = this.options) == null ? void 0 : _h.handleAccountDisconnect) { + (_i = window == null ? void 0 : window.ethereum) == null ? void 0 : _i.on("disconnect", this.options.handleAccountDisconnect); + } + return new TornadoRpcSigner(this, signerAddress, this.options); + }); + } +} + +const GET_STATISTIC = ` + query getStatistic($currency: String!, $amount: String!, $first: Int, $orderBy: BigInt, $orderDirection: String) { + deposits(first: $first, orderBy: $orderBy, orderDirection: $orderDirection, where: { currency: $currency, amount: $amount }) { + index + timestamp + blockNumber + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const _META = ` + query getMeta { + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_REGISTERED = ` + query getRegistered($first: Int, $fromBlock: Int) { + relayers(first: $first, orderBy: blockRegistration, orderDirection: asc, where: { + blockRegistration_gte: $fromBlock + }) { + id + address + ensName + blockRegistration + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_DEPOSITS = ` + query getDeposits($currency: String!, $amount: String!, $first: Int, $fromBlock: Int) { + deposits(first: $first, orderBy: index, orderDirection: asc, where: { + amount: $amount, + currency: $currency, + blockNumber_gte: $fromBlock + }) { + id + blockNumber + commitment + index + timestamp + from + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_WITHDRAWALS = ` + query getWithdrawals($currency: String!, $amount: String!, $first: Int, $fromBlock: Int!) { + withdrawals(first: $first, orderBy: blockNumber, orderDirection: asc, where: { + currency: $currency, + amount: $amount, + blockNumber_gte: $fromBlock + }) { + id + blockNumber + nullifier + to + fee + timestamp + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_NOTE_ACCOUNTS = ` + query getNoteAccount($address: String!) { + noteAccounts(where: { address: $address }) { + id + index + address + encryptedAccount + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_ECHO_EVENTS = ` + query getNoteAccounts($first: Int, $fromBlock: Int) { + noteAccounts(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + id + blockNumber + address + encryptedAccount + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_ENCRYPTED_NOTES = ` + query getEncryptedNotes($first: Int, $fromBlock: Int) { + encryptedNotes(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + index + transactionHash + encryptedNote + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_GOVERNANCE_EVENTS = ` + query getGovernanceEvents($first: Int, $fromBlock: Int) { + proposals(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + logIndex + transactionHash + proposalId + proposer + target + startTime + endTime + description + } + votes(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + logIndex + transactionHash + proposalId + voter + support + votes + from + input + } + delegates(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + logIndex + transactionHash + account + delegateTo + } + undelegates(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + logIndex + transactionHash + account + delegateFrom + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_GOVERNANCE_APY = ` + stakeDailyBurns(first: 30, orderBy: date, orderDirection: desc) { + id + date + dailyAmountBurned + } +`; + +var __defProp$3 = Object.defineProperty; +var __defProps$2 = Object.defineProperties; +var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols; +var __hasOwnProp$3 = Object.prototype.hasOwnProperty; +var __propIsEnum$3 = Object.prototype.propertyIsEnumerable; +var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$3 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$3.call(b, prop)) + __defNormalProp$3(a, prop, b[prop]); + if (__getOwnPropSymbols$3) + for (var prop of __getOwnPropSymbols$3(b)) { + if (__propIsEnum$3.call(b, prop)) + __defNormalProp$3(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b)); +var __async$b = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +const isEmptyArray = (arr) => !Array.isArray(arr) || !arr.length; +const GRAPHQL_LIMIT = 1e3; +function queryGraph(_0) { + return __async$b(this, arguments, function* ({ + graphApi, + subgraphName, + query, + variables, + fetchDataOptions: fetchDataOptions2 + }) { + var _a; + const graphUrl = `${graphApi}/subgraphs/name/${subgraphName}`; + const { data, errors } = yield fetchData(graphUrl, __spreadProps$2(__spreadValues$3({}, fetchDataOptions2), { + method: "POST", + headers: { + "Content-Type": "application/json" + }, + body: JSON.stringify({ + query, + variables + }) + })); + if (errors) { + throw new Error(JSON.stringify(errors)); + } + if ((_a = data == null ? void 0 : data._meta) == null ? void 0 : _a.hasIndexingErrors) { + throw new Error("Subgraph has indexing errors"); + } + return data; + }); +} +function getStatistic(_0) { + return __async$b(this, arguments, function* ({ + graphApi, + subgraphName, + currency, + amount, + fetchDataOptions: fetchDataOptions2 + }) { + try { + const { + deposits, + _meta: { + block: { number: lastSyncBlock } + } + } = yield queryGraph({ + graphApi, + subgraphName, + query: GET_STATISTIC, + variables: { + currency, + first: 10, + orderBy: "index", + orderDirection: "desc", + amount + }, + fetchDataOptions: fetchDataOptions2 + }); + const events = deposits.map((e) => ({ + timestamp: Number(e.timestamp), + leafIndex: Number(e.index), + blockNumber: Number(e.blockNumber) + })).reverse(); + const [lastEvent] = events.slice(-1); + return { + events, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getStatistic query"); + console.log(err); + return { + events: [], + lastSyncBlock: null + }; + } + }); +} +function getMeta(_0) { + return __async$b(this, arguments, function* ({ graphApi, subgraphName, fetchDataOptions: fetchDataOptions2 }) { + try { + const { + _meta: { + block: { number: lastSyncBlock }, + hasIndexingErrors + } + } = yield queryGraph({ + graphApi, + subgraphName, + query: _META, + fetchDataOptions: fetchDataOptions2 + }); + return { + lastSyncBlock, + hasIndexingErrors + }; + } catch (err) { + console.log("Error from getMeta query"); + console.log(err); + return { + lastSyncBlock: null, + hasIndexingErrors: null + }; + } + }); +} +function getRegisters({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_REGISTERED, + variables: { + first: GRAPHQL_LIMIT, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllRegisters(_0) { + return __async$b(this, arguments, function* ({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + relayers: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getRegisters({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "Registers", + fromBlock: Number(firstEvent.blockRegistration), + toBlock: Number(lastEvent.blockRegistration), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockRegistration }) => blockRegistration !== lastEvent.blockRegistration); + fromBlock = Number(lastEvent.blockRegistration); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map(({ id, address, ensName, blockRegistration }) => { + const [transactionHash, logIndex] = id.split("-"); + return { + blockNumber: Number(blockRegistration), + logIndex: Number(logIndex), + transactionHash, + ensName, + relayerAddress: ethers.getAddress(address) + }; + }); + return { + events: result, + lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllRegisters query"); + console.log(err); + return { events: [], lastSyncBlock: fromBlock }; + } + }); +} +function getDeposits({ + graphApi, + subgraphName, + currency, + amount, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_DEPOSITS, + variables: { + currency, + amount, + first: GRAPHQL_LIMIT, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllDeposits(_0) { + return __async$b(this, arguments, function* ({ + graphApi, + subgraphName, + currency, + amount, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + deposits: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getDeposits({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent2] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "Deposits", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map(({ id, blockNumber, commitment, index, timestamp, from }) => { + const [transactionHash, logIndex] = id.split("-"); + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + commitment, + leafIndex: Number(index), + timestamp: Number(timestamp), + from: ethers.getAddress(from) + }; + }); + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllDeposits query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} +function getWithdrawals({ + graphApi, + subgraphName, + currency, + amount, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_WITHDRAWALS, + variables: { + currency, + amount, + first: GRAPHQL_LIMIT, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllWithdrawals(_0) { + return __async$b(this, arguments, function* ({ + graphApi, + subgraphName, + currency, + amount, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + withdrawals: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getWithdrawals({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent2] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "Withdrawals", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map(({ id, blockNumber, nullifier, to, fee, timestamp }) => { + const [transactionHash, logIndex] = id.split("-"); + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + nullifierHash: nullifier, + to: ethers.getAddress(to), + fee, + timestamp: Number(timestamp) + }; + }); + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllWithdrawals query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} +function getNoteAccounts(_0) { + return __async$b(this, arguments, function* ({ + graphApi, + subgraphName, + address, + fetchDataOptions: fetchDataOptions2 + }) { + try { + const { + noteAccounts: events, + _meta: { + block: { number: lastSyncBlock } + } + } = yield queryGraph({ + graphApi, + subgraphName, + query: GET_NOTE_ACCOUNTS, + variables: { + address: address.toLowerCase() + }, + fetchDataOptions: fetchDataOptions2 + }); + return { + events, + lastSyncBlock + }; + } catch (err) { + console.log("Error from getNoteAccounts query"); + console.log(err); + return { + events: [], + lastSyncBlock: null + }; + } + }); +} +function getGraphEchoEvents({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_ECHO_EVENTS, + variables: { + first: GRAPHQL_LIMIT, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllGraphEchoEvents(_0) { + return __async$b(this, arguments, function* ({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + noteAccounts: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getGraphEchoEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent2] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "EchoEvents", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map((e) => { + const [transactionHash, logIndex] = e.id.split("-"); + return { + blockNumber: Number(e.blockNumber), + logIndex: Number(logIndex), + transactionHash, + address: ethers.getAddress(e.address), + encryptedAccount: e.encryptedAccount + }; + }); + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllGraphEchoEvents query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} +function getEncryptedNotes({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_ENCRYPTED_NOTES, + variables: { + first: GRAPHQL_LIMIT, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllEncryptedNotes(_0) { + return __async$b(this, arguments, function* ({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + encryptedNotes: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getEncryptedNotes({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent2] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "EncryptedNotes", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map((e) => ({ + blockNumber: Number(e.blockNumber), + logIndex: Number(e.index), + transactionHash: e.transactionHash, + encryptedNote: e.encryptedNote + })); + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllEncryptedNotes query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} +function getGovernanceEvents({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_GOVERNANCE_EVENTS, + variables: { + first: GRAPHQL_LIMIT, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllGovernanceEvents(_0) { + return __async$b(this, arguments, function* ({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const result = []; + let lastSyncBlock = fromBlock; + while (true) { + const { + proposals, + votes, + delegates, + undelegates, + _meta: { + block: { number: currentBlock } + } + } = yield getGovernanceEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + const eventsLength = proposals.length + votes.length + delegates.length + undelegates.length; + if (eventsLength === 0) { + break; + } + const formattedProposals = proposals.map( + ({ blockNumber, logIndex, transactionHash, proposalId, proposer, target, startTime, endTime, description }) => { + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + event: "ProposalCreated", + id: Number(proposalId), + proposer: ethers.getAddress(proposer), + target: ethers.getAddress(target), + startTime: Number(startTime), + endTime: Number(endTime), + description + }; + } + ); + const formattedVotes = votes.map( + ({ blockNumber, logIndex, transactionHash, proposalId, voter, support, votes: votes2, from, input }) => { + if (!input || input.length > 2048) { + input = ""; + } + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + event: "Voted", + proposalId: Number(proposalId), + voter: ethers.getAddress(voter), + support, + votes: votes2, + from: ethers.getAddress(from), + input + }; + } + ); + const formattedDelegates = delegates.map( + ({ blockNumber, logIndex, transactionHash, account, delegateTo }) => { + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + event: "Delegated", + account: ethers.getAddress(account), + delegateTo: ethers.getAddress(delegateTo) + }; + } + ); + const formattedUndelegates = undelegates.map( + ({ blockNumber, logIndex, transactionHash, account, delegateFrom }) => { + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + event: "Undelegated", + account: ethers.getAddress(account), + delegateFrom: ethers.getAddress(delegateFrom) + }; + } + ); + let formattedEvents = [ + ...formattedProposals, + ...formattedVotes, + ...formattedDelegates, + ...formattedUndelegates + ].sort((a, b) => { + if (a.blockNumber === b.blockNumber) { + return a.logIndex - b.logIndex; + } + return a.blockNumber - b.blockNumber; + }); + if (eventsLength < 900) { + result.push(...formattedEvents); + break; + } + const [firstEvent] = formattedEvents; + const [lastEvent2] = formattedEvents.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "Governance Events", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: eventsLength + }); + } + formattedEvents = formattedEvents.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + result.push(...formattedEvents); + } + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllGovernance query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} + +var graph = /*#__PURE__*/Object.freeze({ + __proto__: null, + GET_DEPOSITS: GET_DEPOSITS, + GET_ECHO_EVENTS: GET_ECHO_EVENTS, + GET_ENCRYPTED_NOTES: GET_ENCRYPTED_NOTES, + GET_GOVERNANCE_APY: GET_GOVERNANCE_APY, + GET_GOVERNANCE_EVENTS: GET_GOVERNANCE_EVENTS, + GET_NOTE_ACCOUNTS: GET_NOTE_ACCOUNTS, + GET_REGISTERED: GET_REGISTERED, + GET_STATISTIC: GET_STATISTIC, + GET_WITHDRAWALS: GET_WITHDRAWALS, + _META: _META, + getAllDeposits: getAllDeposits, + getAllEncryptedNotes: getAllEncryptedNotes, + getAllGovernanceEvents: getAllGovernanceEvents, + getAllGraphEchoEvents: getAllGraphEchoEvents, + getAllRegisters: getAllRegisters, + getAllWithdrawals: getAllWithdrawals, + getDeposits: getDeposits, + getEncryptedNotes: getEncryptedNotes, + getGovernanceEvents: getGovernanceEvents, + getGraphEchoEvents: getGraphEchoEvents, + getMeta: getMeta, + getNoteAccounts: getNoteAccounts, + getRegisters: getRegisters, + getStatistic: getStatistic, + getWithdrawals: getWithdrawals, + queryGraph: queryGraph +}); + +var __async$a = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +class BatchBlockService { + constructor({ + provider, + onProgress, + concurrencySize = 10, + batchSize = 10, + shouldRetry = true, + retryMax = 5, + retryOn = 500 + }) { + this.provider = provider; + this.onProgress = onProgress; + this.concurrencySize = concurrencySize; + this.batchSize = batchSize; + this.shouldRetry = shouldRetry; + this.retryMax = retryMax; + this.retryOn = retryOn; + } + getBlock(blockTag) { + return __async$a(this, null, function* () { + const blockObject = yield this.provider.getBlock(blockTag); + if (!blockObject) { + const errMsg = `No block for ${blockTag}`; + throw new Error(errMsg); + } + return blockObject; + }); + } + createBatchRequest(batchArray) { + return batchArray.map((blocks, index) => __async$a(this, null, function* () { + yield sleep(20 * index); + return (() => __async$a(this, null, function* () { + let retries = 0; + let err; + while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { + try { + return yield Promise.all(blocks.map((b) => this.getBlock(b))); + } catch (e) { + retries++; + err = e; + yield sleep(this.retryOn); + } + } + throw err; + }))(); + })); + } + getBatchBlocks(blocks) { + return __async$a(this, null, function* () { + let blockCount = 0; + const results = []; + for (const chunks of chunk(blocks, this.concurrencySize * this.batchSize)) { + const chunksResult = (yield Promise.all(this.createBatchRequest(chunk(chunks, this.batchSize)))).flat(); + results.push(...chunksResult); + blockCount += chunks.length; + if (typeof this.onProgress === "function") { + this.onProgress({ + percentage: blockCount / blocks.length, + currentIndex: blockCount, + totalIndex: blocks.length + }); + } + } + return results; + }); + } +} +class BatchTransactionService { + constructor({ + provider, + onProgress, + concurrencySize = 10, + batchSize = 10, + shouldRetry = true, + retryMax = 5, + retryOn = 500 + }) { + this.provider = provider; + this.onProgress = onProgress; + this.concurrencySize = concurrencySize; + this.batchSize = batchSize; + this.shouldRetry = shouldRetry; + this.retryMax = retryMax; + this.retryOn = retryOn; + } + getTransaction(txHash) { + return __async$a(this, null, function* () { + const txObject = yield this.provider.getTransaction(txHash); + if (!txObject) { + const errMsg = `No transaction for ${txHash}`; + throw new Error(errMsg); + } + return txObject; + }); + } + createBatchRequest(batchArray) { + return batchArray.map((txs, index) => __async$a(this, null, function* () { + yield sleep(20 * index); + return (() => __async$a(this, null, function* () { + let retries = 0; + let err; + while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { + try { + return yield Promise.all(txs.map((tx) => this.getTransaction(tx))); + } catch (e) { + retries++; + err = e; + yield sleep(this.retryOn); + } + } + throw err; + }))(); + })); + } + getBatchTransactions(txs) { + return __async$a(this, null, function* () { + let txCount = 0; + const results = []; + for (const chunks of chunk(txs, this.concurrencySize * this.batchSize)) { + const chunksResult = (yield Promise.all(this.createBatchRequest(chunk(chunks, this.batchSize)))).flat(); + results.push(...chunksResult); + txCount += chunks.length; + if (typeof this.onProgress === "function") { + this.onProgress({ percentage: txCount / txs.length, currentIndex: txCount, totalIndex: txs.length }); + } + } + return results; + }); + } +} +class BatchEventsService { + constructor({ + provider, + contract, + onProgress, + concurrencySize = 10, + blocksPerRequest = 2e3, + shouldRetry = true, + retryMax = 5, + retryOn = 500 + }) { + this.provider = provider; + this.contract = contract; + this.onProgress = onProgress; + this.concurrencySize = concurrencySize; + this.blocksPerRequest = blocksPerRequest; + this.shouldRetry = shouldRetry; + this.retryMax = retryMax; + this.retryOn = retryOn; + } + getPastEvents(_0) { + return __async$a(this, arguments, function* ({ fromBlock, toBlock, type }) { + let err; + let retries = 0; + while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { + try { + return yield this.contract.queryFilter(type, fromBlock, toBlock); + } catch (e) { + err = e; + retries++; + if (e.message.includes("after last accepted block")) { + const acceptedBlock = parseInt(e.message.split("after last accepted block ")[1]); + toBlock = acceptedBlock; + } + yield sleep(this.retryOn); + } + } + throw err; + }); + } + createBatchRequest(batchArray) { + return batchArray.map((event, index) => __async$a(this, null, function* () { + yield sleep(20 * index); + return this.getPastEvents(event); + })); + } + getBatchEvents(_0) { + return __async$a(this, arguments, function* ({ fromBlock, toBlock, type = "*" }) { + if (!toBlock) { + toBlock = yield this.provider.getBlockNumber(); + } + const eventsToSync = []; + for (let i = fromBlock; i < toBlock; i += this.blocksPerRequest) { + const j = i + this.blocksPerRequest - 1 > toBlock ? toBlock : i + this.blocksPerRequest - 1; + eventsToSync.push({ fromBlock: i, toBlock: j, type }); + } + const events = []; + const eventChunk = chunk(eventsToSync, this.concurrencySize); + let chunkCount = 0; + for (const chunk2 of eventChunk) { + chunkCount++; + const fetchedEvents = (yield Promise.all(this.createBatchRequest(chunk2))).flat(); + events.push(...fetchedEvents); + if (typeof this.onProgress === "function") { + this.onProgress({ + percentage: chunkCount / eventChunk.length, + type, + fromBlock: chunk2[0].fromBlock, + toBlock: chunk2[chunk2.length - 1].toBlock, + count: fetchedEvents.length + }); + } + } + return events; + }); + } +} + +var __defProp$2 = Object.defineProperty; +var __defProps$1 = Object.defineProperties; +var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp$2 = Object.prototype.hasOwnProperty; +var __propIsEnum$2 = Object.prototype.propertyIsEnumerable; +var __reflectGet = Reflect.get; +var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$2 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$2.call(b, prop)) + __defNormalProp$2(a, prop, b[prop]); + if (__getOwnPropSymbols$2) + for (var prop of __getOwnPropSymbols$2(b)) { + if (__propIsEnum$2.call(b, prop)) + __defNormalProp$2(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b)); +var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj); +var __async$9 = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +const DEPOSIT = "deposit"; +const WITHDRAWAL = "withdrawal"; +class BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + contract, + type = "", + deployedBlock = 0, + fetchDataOptions: fetchDataOptions2 + }) { + this.netId = netId; + this.provider = provider; + this.graphApi = graphApi; + this.subgraphName = subgraphName; + this.fetchDataOptions = fetchDataOptions2; + this.contract = contract; + this.type = type; + this.deployedBlock = deployedBlock; + this.batchEventsService = new BatchEventsService({ + provider, + contract, + onProgress: this.updateEventProgress + }); + } + getInstanceName() { + return ""; + } + getType() { + return this.type || ""; + } + getGraphMethod() { + return ""; + } + getGraphParams() { + return { + graphApi: this.graphApi || "", + subgraphName: this.subgraphName || "", + fetchDataOptions: this.fetchDataOptions, + onProgress: this.updateGraphProgress + }; + } + /* eslint-disable @typescript-eslint/no-unused-vars */ + updateEventProgress({ percentage, type, fromBlock, toBlock, count }) { + } + updateBlockProgress({ percentage, currentIndex, totalIndex }) { + } + updateTransactionProgress({ percentage, currentIndex, totalIndex }) { + } + updateGraphProgress({ type, fromBlock, toBlock, count }) { + } + /* eslint-enable @typescript-eslint/no-unused-vars */ + formatEvents(events) { + return __async$9(this, null, function* () { + return yield new Promise((resolve) => resolve(events)); + }); + } + /** + * Get saved or cached events + */ + getEventsFromDB() { + return __async$9(this, null, function* () { + return { + events: [], + lastBlock: null + }; + }); + } + /** + * Events from remote cache (Either from local cache, CDN, or from IPFS) + */ + getEventsFromCache() { + return __async$9(this, null, function* () { + return { + events: [], + lastBlock: null, + fromCache: true + }; + }); + } + getSavedEvents() { + return __async$9(this, null, function* () { + let cachedEvents = yield this.getEventsFromDB(); + if (!cachedEvents || !cachedEvents.events.length) { + cachedEvents = yield this.getEventsFromCache(); + } + return cachedEvents; + }); + } + /** + * Get latest events + */ + getEventsFromGraph(_0) { + return __async$9(this, arguments, function* ({ + fromBlock, + methodName = "" + }) { + if (!this.graphApi || !this.subgraphName) { + return { + events: [], + lastBlock: fromBlock + }; + } + const { events, lastSyncBlock } = yield graph[methodName || this.getGraphMethod()](__spreadValues$2({ + fromBlock + }, this.getGraphParams())); + return { + events, + lastBlock: lastSyncBlock + }; + }); + } + getEventsFromRpc(_0) { + return __async$9(this, arguments, function* ({ + fromBlock, + toBlock + }) { + try { + if (!toBlock) { + toBlock = yield this.provider.getBlockNumber(); + } + if (fromBlock >= toBlock) { + return { + events: [], + lastBlock: toBlock + }; + } + this.updateEventProgress({ percentage: 0, type: this.getType() }); + const events = yield this.formatEvents( + yield this.batchEventsService.getBatchEvents({ fromBlock, toBlock, type: this.getType() }) + ); + if (!events.length) { + return { + events, + lastBlock: toBlock + }; + } + return { + events, + lastBlock: toBlock + }; + } catch (err) { + console.log(err); + return { + events: [], + lastBlock: fromBlock + }; + } + }); + } + getLatestEvents(_0) { + return __async$9(this, arguments, function* ({ fromBlock }) { + const allEvents = []; + const graphEvents = yield this.getEventsFromGraph({ fromBlock }); + const lastSyncBlock = graphEvents.lastBlock && graphEvents.lastBlock >= fromBlock ? graphEvents.lastBlock : fromBlock; + const rpcEvents = yield this.getEventsFromRpc({ fromBlock: lastSyncBlock }); + allEvents.push(...graphEvents.events); + allEvents.push(...rpcEvents.events); + const lastBlock = rpcEvents ? rpcEvents.lastBlock : allEvents[allEvents.length - 1] ? allEvents[allEvents.length - 1].blockNumber : fromBlock; + return { + events: allEvents, + lastBlock + }; + }); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + validateEvents({ events, lastBlock }) { + } + /** + * Handle saving events + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + saveEvents(_0) { + return __async$9(this, arguments, function* ({ events, lastBlock }) { + }); + } + /** + * Trigger saving and receiving latest events + */ + updateEvents() { + return __async$9(this, null, function* () { + const savedEvents = yield this.getSavedEvents(); + let fromBlock = this.deployedBlock; + if (savedEvents && savedEvents.lastBlock) { + fromBlock = savedEvents.lastBlock + 1; + } + const newEvents = yield this.getLatestEvents({ fromBlock }); + const eventSet = /* @__PURE__ */ new Set(); + let allEvents = []; + allEvents.push(...savedEvents.events); + allEvents.push(...newEvents.events); + allEvents = allEvents.sort((a, b) => { + if (a.blockNumber === b.blockNumber) { + return a.logIndex - b.logIndex; + } + return a.blockNumber - b.blockNumber; + }).filter(({ transactionHash, logIndex }) => { + const eventKey = `${transactionHash}_${logIndex}`; + const hasEvent = eventSet.has(eventKey); + eventSet.add(eventKey); + return !hasEvent; + }); + const lastBlock = newEvents ? newEvents.lastBlock : allEvents[allEvents.length - 1] ? allEvents[allEvents.length - 1].blockNumber : null; + this.validateEvents({ events: allEvents, lastBlock }); + if (savedEvents.fromCache || newEvents.events.length) { + yield this.saveEvents({ events: allEvents, lastBlock }); + } + return { + events: allEvents, + lastBlock + }; + }); + } +} +class BaseTornadoService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Tornado, + type, + amount, + currency, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: Tornado, type, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + this.amount = amount; + this.currency = currency; + this.batchTransactionService = new BatchTransactionService({ + provider, + onProgress: this.updateTransactionProgress + }); + this.batchBlockService = new BatchBlockService({ + provider, + onProgress: this.updateBlockProgress + }); + } + getInstanceName() { + return `${this.getType().toLowerCase()}s_${this.netId}_${this.currency}_${this.amount}`; + } + getGraphMethod() { + return `getAll${this.getType()}s`; + } + getGraphParams() { + return { + graphApi: this.graphApi || "", + subgraphName: this.subgraphName || "", + amount: this.amount, + currency: this.currency, + fetchDataOptions: this.fetchDataOptions, + onProgress: this.updateGraphProgress + }; + } + formatEvents(events) { + return __async$9(this, null, function* () { + const type = this.getType().toLowerCase(); + if (type === DEPOSIT) { + const formattedEvents = events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const { commitment, leafIndex, timestamp } = args; + return { + blockNumber, + logIndex, + transactionHash, + commitment, + leafIndex: Number(leafIndex), + timestamp: Number(timestamp) + }; + }); + const txs = yield this.batchTransactionService.getBatchTransactions([ + ...new Set(formattedEvents.map(({ transactionHash }) => transactionHash)) + ]); + return formattedEvents.map((event) => { + const { from } = txs.find(({ hash }) => hash === event.transactionHash); + return __spreadProps$1(__spreadValues$2({}, event), { + from + }); + }); + } else { + const formattedEvents = events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const { nullifierHash, to, fee } = args; + return { + blockNumber, + logIndex, + transactionHash, + nullifierHash: String(nullifierHash), + to: ethers.getAddress(to), + fee: String(fee) + }; + }); + const blocks = yield this.batchBlockService.getBatchBlocks([ + ...new Set(formattedEvents.map(({ blockNumber }) => blockNumber)) + ]); + return formattedEvents.map((event) => { + const { timestamp } = blocks.find(({ number }) => number === event.blockNumber); + return __spreadProps$1(__spreadValues$2({}, event), { + timestamp + }); + }); + } + }); + } + validateEvents({ events }) { + if (events.length && this.getType().toLowerCase() === DEPOSIT) { + const lastEvent = events[events.length - 1]; + if (lastEvent.leafIndex !== events.length - 1) { + const errMsg = `Deposit events invalid wants ${events.length - 1} leafIndex have ${lastEvent.leafIndex}`; + throw new Error(errMsg); + } + } + } +} +class BaseEchoService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Echoer, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: Echoer, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + } + getInstanceName() { + return `echo_${this.netId}`; + } + getType() { + return "Echo"; + } + getGraphMethod() { + return "getAllGraphEchoEvents"; + } + formatEvents(events) { + return __async$9(this, null, function* () { + return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const { who, data } = args; + if (who && data) { + const eventObjects = { + blockNumber, + logIndex, + transactionHash + }; + return __spreadProps$1(__spreadValues$2({}, eventObjects), { + address: who, + encryptedAccount: data + }); + } + }).filter((e) => e); + }); + } + getEventsFromGraph(_0) { + return __async$9(this, arguments, function* ({ fromBlock }) { + if (!this.graphApi || this.graphApi.includes("api.thegraph.com")) { + return { + events: [], + lastBlock: fromBlock + }; + } + return __superGet(BaseEchoService.prototype, this, "getEventsFromGraph").call(this, { fromBlock }); + }); + } +} +class BaseEncryptedNotesService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Router, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: Router, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + } + getInstanceName() { + return `encrypted_notes_${this.netId}`; + } + getType() { + return "EncryptedNote"; + } + getGraphMethod() { + return "getAllEncryptedNotes"; + } + formatEvents(events) { + return __async$9(this, null, function* () { + return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const { encryptedNote } = args; + if (encryptedNote) { + const eventObjects = { + blockNumber, + logIndex, + transactionHash + }; + return __spreadProps$1(__spreadValues$2({}, eventObjects), { + encryptedNote + }); + } + }).filter((e) => e); + }); + } +} +class BaseGovernanceService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Governance, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: Governance, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + this.batchTransactionService = new BatchTransactionService({ + provider, + onProgress: this.updateTransactionProgress + }); + } + getInstanceName() { + return `governance_${this.netId}`; + } + getType() { + return "*"; + } + getGraphMethod() { + return "getAllGovernanceEvents"; + } + formatEvents(events) { + return __async$9(this, null, function* () { + const proposalEvents = []; + const votedEvents = []; + const delegatedEvents = []; + const undelegatedEvents = []; + events.forEach(({ blockNumber, index: logIndex, transactionHash, args, eventName: event }) => { + const eventObjects = { + blockNumber, + logIndex, + transactionHash, + event + }; + if (event === "ProposalCreated") { + const { id, proposer, target, startTime, endTime, description } = args; + proposalEvents.push(__spreadProps$1(__spreadValues$2({}, eventObjects), { + id: Number(id), + proposer, + target, + startTime: Number(startTime), + endTime: Number(endTime), + description + })); + } + if (event === "Voted") { + const { proposalId, voter, support, votes } = args; + votedEvents.push(__spreadProps$1(__spreadValues$2({}, eventObjects), { + proposalId: Number(proposalId), + voter, + support, + votes, + from: "", + input: "" + })); + } + if (event === "Delegated") { + const { account, to: delegateTo } = args; + delegatedEvents.push(__spreadProps$1(__spreadValues$2({}, eventObjects), { + account, + delegateTo + })); + } + if (event === "Undelegated") { + const { account, from: delegateFrom } = args; + undelegatedEvents.push(__spreadProps$1(__spreadValues$2({}, eventObjects), { + account, + delegateFrom + })); + } + }); + if (votedEvents.length) { + this.updateTransactionProgress({ percentage: 0 }); + const txs = yield this.batchTransactionService.getBatchTransactions([ + ...new Set(votedEvents.map(({ transactionHash }) => transactionHash)) + ]); + votedEvents.forEach((event, index) => { + let { data: input, from } = txs.find((t) => t.hash === event.transactionHash); + if (!input || input.length > 2048) { + input = ""; + } + votedEvents[index].from = from; + votedEvents[index].input = input; + }); + } + return [...proposalEvents, ...votedEvents, ...delegatedEvents, ...undelegatedEvents]; + }); + } + getEventsFromGraph(_0) { + return __async$9(this, arguments, function* ({ fromBlock }) { + if (!this.graphApi || !this.subgraphName || this.graphApi.includes("api.thegraph.com")) { + return { + events: [], + lastBlock: fromBlock + }; + } + return __superGet(BaseGovernanceService.prototype, this, "getEventsFromGraph").call(this, { fromBlock }); + }); + } +} +class BaseRegistryService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + RelayerRegistry, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: RelayerRegistry, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + } + getInstanceName() { + return `registered_${this.netId}`; + } + // Name of type used for events + getType() { + return "RelayerRegistered"; + } + // Name of method used for graph + getGraphMethod() { + return "getAllRegisters"; + } + formatEvents(events) { + return __async$9(this, null, function* () { + return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const eventObjects = { + blockNumber, + logIndex, + transactionHash + }; + return __spreadProps$1(__spreadValues$2({}, eventObjects), { + ensName: args.ensName, + relayerAddress: args.relayerAddress + }); + }); + }); + } + fetchRelayers() { + return __async$9(this, null, function* () { + return (yield this.updateEvents()).events; + }); + } +} + +var __defProp$1 = Object.defineProperty; +var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols; +var __hasOwnProp$1 = Object.prototype.hasOwnProperty; +var __propIsEnum$1 = Object.prototype.propertyIsEnumerable; +var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$1 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$1.call(b, prop)) + __defNormalProp$1(a, prop, b[prop]); + if (__getOwnPropSymbols$1) + for (var prop of __getOwnPropSymbols$1(b)) { + if (__propIsEnum$1.call(b, prop)) + __defNormalProp$1(a, prop, b[prop]); + } + return a; +}; +var NetId = /* @__PURE__ */ ((NetId2) => { + NetId2[NetId2["MAINNET"] = 1] = "MAINNET"; + NetId2[NetId2["BSC"] = 56] = "BSC"; + NetId2[NetId2["POLYGON"] = 137] = "POLYGON"; + NetId2[NetId2["OPTIMISM"] = 10] = "OPTIMISM"; + NetId2[NetId2["ARBITRUM"] = 42161] = "ARBITRUM"; + NetId2[NetId2["GNOSIS"] = 100] = "GNOSIS"; + NetId2[NetId2["AVALANCHE"] = 43114] = "AVALANCHE"; + NetId2[NetId2["SEPOLIA"] = 11155111] = "SEPOLIA"; + return NetId2; +})(NetId || {}); +const theGraph = { + name: "Hosted Graph", + url: "https://api.thegraph.com" +}; +const tornado = { + name: "Tornado Subgraphs", + url: "https://tornadocash-rpc.com" +}; +const defaultConfig = { + [1 /* MAINNET */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 80, + fast: 50, + standard: 25, + low: 8 + }, + nativeCurrency: "eth", + currencyName: "ETH", + explorerUrl: "https://etherscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Ethereum Mainnet", + deployedBlock: 9116966, + rpcUrls: { + tornadoRPC: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/mainnet" + }, + mevblockerRPC: { + name: "MevblockerRPC", + url: "https://rpc.mevblocker.io" + }, + oneRPC: { + name: "1RPC", + url: "https://1rpc.io/eth" + } + }, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0xd90e2f925DA726b50C4Ed8D0Fb90Ad053324F31b", + echoContract: "0x9B27DD5Bb15d42DC224FCD0B7caEbBe16161Df42", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornContract: "0x77777FeDdddFfC19Ff86DB637967013e6C6A116C", + governanceContract: "0x5efda50f22d34F262c29268506C5Fa42cB56A1Ce", + stakingRewardsContract: "0x5B3f656C80E8ddb9ec01Dd9018815576E9238c29", + registryContract: "0x58E8dCC13BE9780fC42E8723D8EaD4CF46943dF2", + aggregatorContract: "0xE8F47A78A6D52D317D0D2FFFac56739fE14D1b49", + reverseRecordsContract: "0x3671aE578E63FdF66ad4F3E12CC0c0d71Ac7510C", + tornadoSubgraph: "tornadocash/mainnet-tornado-subgraph", + registrySubgraph: "tornadocash/tornado-relayer-registry", + governanceSubgraph: "tornadocash/tornado-governance", + subgraphs: { + tornado, + theGraph + }, + tokens: { + eth: { + instanceAddress: { + "0.1": "0x12D66f87A04A9E220743712cE6d9bB1B5616B8Fc", + "1": "0x47CE0C6eD5B0Ce3d3A51fdb1C52DC66a7c3c2936", + "10": "0x910Cbd523D972eb0a6f4cAe4618aD62622b39DbF", + "100": "0xA160cdAB225685dA1d56aa342Ad8841c3b53f291" + }, + symbol: "ETH", + decimals: 18 + }, + dai: { + instanceAddress: { + "100": "0xD4B88Df4D29F5CedD6857912842cff3b20C8Cfa3", + "1000": "0xFD8610d20aA15b7B2E3Be39B396a1bC3516c7144", + "10000": "0x07687e702b410Fa43f4cB4Af7FA097918ffD2730", + "100000": "0x23773E65ed146A459791799d01336DB287f25334" + }, + tokenAddress: "0x6B175474E89094C44Da98b954EedeAC495271d0F", + tokenGasLimit: 7e4, + symbol: "DAI", + decimals: 18, + gasLimit: 7e5 + }, + cdai: { + instanceAddress: { + "5000": "0x22aaA7720ddd5388A3c0A3333430953C68f1849b", + "50000": "0x03893a7c7463AE47D46bc7f091665f1893656003", + "500000": "0x2717c5e28cf931547B621a5dddb772Ab6A35B701", + "5000000": "0xD21be7248e0197Ee08E0c20D4a96DEBdaC3D20Af" + }, + tokenAddress: "0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643", + tokenGasLimit: 2e5, + symbol: "cDAI", + decimals: 8, + gasLimit: 7e5 + }, + usdc: { + instanceAddress: { + "100": "0xd96f2B1c14Db8458374d9Aca76E26c3D18364307", + "1000": "0x4736dCf1b7A3d580672CcE6E7c65cd5cc9cFBa9D" + }, + tokenAddress: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", + tokenGasLimit: 7e4, + symbol: "USDC", + decimals: 6, + gasLimit: 7e5 + }, + usdt: { + instanceAddress: { + "100": "0x169AD27A470D064DEDE56a2D3ff727986b15D52B", + "1000": "0x0836222F2B2B24A3F36f98668Ed8F0B38D1a872f" + }, + tokenAddress: "0xdAC17F958D2ee523a2206206994597C13D831ec7", + tokenGasLimit: 7e4, + symbol: "USDT", + decimals: 6, + gasLimit: 7e5 + }, + wbtc: { + instanceAddress: { + "0.1": "0x178169B423a011fff22B9e3F3abeA13414dDD0F1", + "1": "0x610B717796ad172B316836AC95a2ffad065CeaB4", + "10": "0xbB93e510BbCD0B7beb5A853875f9eC60275CF498" + }, + tokenAddress: "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599", + tokenGasLimit: 7e4, + symbol: "WBTC", + decimals: 8, + gasLimit: 7e5 + } + }, + relayerEnsSubdomain: "mainnet-tornado", + pollInterval: 15, + constants: { + GOVERNANCE_BLOCK: 11474695, + NOTE_ACCOUNT_BLOCK: 11842486, + ENCRYPTED_NOTES_BLOCK: 12143762, + REGISTRY_BLOCK: 14173129, + MINING_BLOCK_TIME: 15 + } + }, + [56 /* BSC */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 5, + fast: 5, + standard: 5, + low: 5 + }, + nativeCurrency: "bnb", + currencyName: "BNB", + explorerUrl: "https://bscscan.com", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Binance Smart Chain", + deployedBlock: 8158799, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornadoSubgraph: "tornadocash/bsc-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + tornadoRPC: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/bsc" + }, + oneRPC: { + name: "1RPC", + url: "https://1rpc.io/bnb" + } + }, + tokens: { + bnb: { + instanceAddress: { + "0.1": "0x84443CFd09A48AF6eF360C6976C5392aC5023a1F", + "1": "0xd47438C816c9E7f2E2888E060936a499Af9582b3", + "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD" + }, + symbol: "BNB", + decimals: 18 + } + }, + relayerEnsSubdomain: "bsc-tornado", + pollInterval: 10, + constants: { + NOTE_ACCOUNT_BLOCK: 8159269, + ENCRYPTED_NOTES_BLOCK: 8159269 + } + }, + [137 /* POLYGON */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 100, + fast: 75, + standard: 50, + low: 30 + }, + nativeCurrency: "matic", + currencyName: "MATIC", + explorerUrl: "https://polygonscan.com", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Polygon (Matic) Network", + deployedBlock: 16257962, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornadoSubgraph: "tornadocash/matic-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + oneRpc: { + name: "1RPC", + url: "https://1rpc.io/matic" + } + }, + tokens: { + matic: { + instanceAddress: { + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD", + "1000": "0xdf231d99Ff8b6c6CBF4E9B9a945CBAcEF9339178", + "10000": "0xaf4c0B70B2Ea9FB7487C7CbB37aDa259579fe040", + "100000": "0xa5C2254e4253490C54cef0a4347fddb8f75A4998" + }, + symbol: "MATIC", + decimals: 18 + } + }, + relayerEnsSubdomain: "polygon-tornado", + pollInterval: 10, + constants: { + NOTE_ACCOUNT_BLOCK: 16257996, + ENCRYPTED_NOTES_BLOCK: 16257996 + } + }, + [10 /* OPTIMISM */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 1e-3, + fast: 1e-3, + standard: 1e-3, + low: 1e-3 + }, + nativeCurrency: "eth", + currencyName: "ETH", + explorerUrl: "https://optimistic.etherscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Optimism", + deployedBlock: 2243689, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + ovmGasPriceOracleContract: "0x420000000000000000000000000000000000000F", + tornadoSubgraph: "tornadocash/optimism-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + tornadoRPC: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/op" + }, + oneRpc: { + name: "1RPC", + url: "https://1rpc.io/op" + } + }, + tokens: { + eth: { + instanceAddress: { + "0.1": "0x84443CFd09A48AF6eF360C6976C5392aC5023a1F", + "1": "0xd47438C816c9E7f2E2888E060936a499Af9582b3", + "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD" + }, + symbol: "ETH", + decimals: 18 + } + }, + relayerEnsSubdomain: "optimism-tornado", + pollInterval: 15, + constants: { + NOTE_ACCOUNT_BLOCK: 2243694, + ENCRYPTED_NOTES_BLOCK: 2243694 + } + }, + [42161 /* ARBITRUM */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 4, + fast: 3, + standard: 2.52, + low: 2.29 + }, + nativeCurrency: "eth", + currencyName: "ETH", + explorerUrl: "https://arbiscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Arbitrum One", + deployedBlock: 3430648, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornadoSubgraph: "tornadocash/arbitrum-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + oneRpc: { + name: "1rpc", + url: "https://1rpc.io/arb" + }, + Arbitrum: { + name: "Arbitrum RPC", + url: "https://arb1.arbitrum.io/rpc" + } + }, + tokens: { + eth: { + instanceAddress: { + "0.1": "0x84443CFd09A48AF6eF360C6976C5392aC5023a1F", + "1": "0xd47438C816c9E7f2E2888E060936a499Af9582b3", + "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD" + }, + symbol: "ETH", + decimals: 18 + } + }, + relayerEnsSubdomain: "arbitrum-tornado", + pollInterval: 15, + constants: { + NOTE_ACCOUNT_BLOCK: 3430605, + ENCRYPTED_NOTES_BLOCK: 3430605 + } + }, + [100 /* GNOSIS */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 6, + fast: 5, + standard: 4, + low: 1 + }, + nativeCurrency: "xdai", + currencyName: "xDAI", + explorerUrl: "https://gnosisscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Gnosis Chain", + deployedBlock: 17754561, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornadoSubgraph: "tornadocash/xdai-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + tornadoRPC: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/gnosis" + }, + blockPi: { + name: "BlockPi", + url: "https://gnosis.blockpi.network/v1/rpc/public" + } + }, + tokens: { + xdai: { + instanceAddress: { + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD", + "1000": "0xdf231d99Ff8b6c6CBF4E9B9a945CBAcEF9339178", + "10000": "0xaf4c0B70B2Ea9FB7487C7CbB37aDa259579fe040", + "100000": "0xa5C2254e4253490C54cef0a4347fddb8f75A4998" + }, + symbol: "xDAI", + decimals: 18 + } + }, + relayerEnsSubdomain: "gnosis-tornado", + pollInterval: 15, + constants: { + NOTE_ACCOUNT_BLOCK: 17754564, + ENCRYPTED_NOTES_BLOCK: 17754564 + } + }, + [43114 /* AVALANCHE */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 225, + fast: 35, + standard: 25, + low: 25 + }, + nativeCurrency: "avax", + currencyName: "AVAX", + explorerUrl: "https://snowtrace.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Avalanche Mainnet", + deployedBlock: 4429818, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornadoSubgraph: "tornadocash/avalanche-tornado-subgraph", + subgraphs: { + theGraph + }, + rpcUrls: { + publicRpc: { + name: "Avalanche RPC", + url: "https://api.avax.network/ext/bc/C/rpc" + }, + meowRPC: { + name: "Meow RPC", + url: "https://avax.meowrpc.com" + }, + oneRPC: { + name: "OneRPC", + url: "https://1rpc.io/avax/c" + } + }, + tokens: { + avax: { + instanceAddress: { + "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD", + "500": "0xaf8d1839c3c67cf571aa74B5c12398d4901147B3" + }, + symbol: "AVAX", + decimals: 18 + } + }, + relayerEnsSubdomain: "avalanche-tornado", + pollInterval: 10, + constants: { + NOTE_ACCOUNT_BLOCK: 4429813, + ENCRYPTED_NOTES_BLOCK: 4429813 + } + }, + [11155111 /* SEPOLIA */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 2, + fast: 2, + standard: 2, + low: 2 + }, + nativeCurrency: "eth", + currencyName: "SepoliaETH", + explorerUrl: "https://sepolia.etherscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Ethereum Sepolia", + deployedBlock: 5594395, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x1572AFE6949fdF51Cb3E0856216670ae9Ee160Ee", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + tornContract: "0x3AE6667167C0f44394106E197904519D808323cA", + governanceContract: "0xe5324cD7602eeb387418e594B87aCADee08aeCAD", + stakingRewardsContract: "0x6d0018890751Efd31feb8166711B16732E2b496b", + registryContract: "0x1428e5d2356b13778A13108b10c440C83011dfB8", + aggregatorContract: "0x4088712AC9fad39ea133cdb9130E465d235e9642", + reverseRecordsContract: "0xEc29700C0283e5Be64AcdFe8077d6cC95dE23C23", + tornadoSubgraph: "tornadocash/sepolia-tornado-subgraph", + subgraphs: { + tornado + }, + rpcUrls: { + tornadoRPC: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/sepolia" + }, + sepolia: { + name: "Sepolia RPC", + url: "https://rpc.sepolia.org" + } + }, + tokens: { + eth: { + instanceAddress: { + "0.1": "0x8C4A04d872a6C1BE37964A21ba3a138525dFF50b", + "1": "0x8cc930096B4Df705A007c4A039BDFA1320Ed2508", + "10": "0x8D10d506D29Fc62ABb8A290B99F66dB27Fc43585", + "100": "0x44c5C92ed73dB43888210264f0C8b36Fd68D8379" + }, + symbol: "ETH", + decimals: 18 + }, + dai: { + instanceAddress: { + "100": "0x6921fd1a97441dd603a997ED6DDF388658daf754", + "1000": "0x50a637770F5d161999420F7d70d888DE47207145", + "10000": "0xecD649870407cD43923A816Cc6334a5bdf113621", + "100000": "0x73B4BD04bF83206B6e979BE2507098F92EDf4F90" + }, + tokenAddress: "0xFF34B3d4Aee8ddCd6F9AFFFB6Fe49bD371b8a357", + tokenGasLimit: 7e4, + symbol: "DAI", + decimals: 18, + gasLimit: 7e5 + } + }, + relayerEnsSubdomain: "sepolia-tornado", + pollInterval: 15, + constants: { + GOVERNANCE_BLOCK: 5594395, + NOTE_ACCOUNT_BLOCK: 5594395, + ENCRYPTED_NOTES_BLOCK: 5594395, + MINING_BLOCK_TIME: 15 + } + } +}; +const enabledChains = Object.values(NetId).filter((n) => typeof n === "number"); +exports.customConfig = {}; +function addNetwork(newConfig) { + enabledChains.push( + ...Object.keys(newConfig).map((netId) => Number(netId)).filter((netId) => !enabledChains.includes(netId)) + ); + exports.customConfig = __spreadValues$1(__spreadValues$1({}, exports.customConfig), newConfig); +} +function getNetworkConfig() { + const allConfig = __spreadValues$1(__spreadValues$1({}, defaultConfig), exports.customConfig); + return enabledChains.reduce((acc, curr) => { + acc[curr] = allConfig[curr]; + return acc; + }, {}); +} +function getConfig(netId) { + const allConfig = getNetworkConfig(); + const chainConfig = allConfig[netId]; + if (!chainConfig) { + const errMsg = `No config found for network ${netId}!`; + throw new Error(errMsg); + } + return chainConfig; +} +function getInstanceByAddress({ netId, address }) { + const { tokens } = getConfig(netId); + for (const [currency, { instanceAddress }] of Object.entries(tokens)) { + for (const [amount, instance] of Object.entries(instanceAddress)) { + if (instance === address) { + return { + amount, + currency + }; + } + } + } +} +function getSubdomains() { + const allConfig = getNetworkConfig(); + return enabledChains.map((chain) => allConfig[chain].relayerEnsSubdomain); +} + +const addressType = { type: "string", pattern: "^0x[a-fA-F0-9]{40}$" }; +const bnType = { type: "string", BN: true }; +const statusSchema = { + type: "object", + properties: { + rewardAccount: addressType, + gasPrices: { + type: "object", + properties: { + fast: { type: "number" }, + additionalProperties: { type: "number" } + }, + required: ["fast"] + }, + netId: { type: "integer" }, + tornadoServiceFee: { type: "number", maximum: 20, minimum: 0 }, + latestBlock: { type: "number" }, + version: { type: "string" }, + health: { + type: "object", + properties: { + status: { const: "true" }, + error: { type: "string" } + }, + required: ["status"] + }, + currentQueue: { type: "number" } + }, + required: ["rewardAccount", "instances", "netId", "tornadoServiceFee", "version", "health"] +}; +function getStatusSchema(netId, config) { + const { tokens, optionalTokens = [], nativeCurrency } = config; + const schema = JSON.parse(JSON.stringify(statusSchema)); + const instances = Object.keys(tokens).reduce( + (acc, token) => { + const { instanceAddress, tokenAddress, symbol, decimals, optionalInstances = [] } = tokens[token]; + const amounts = Object.keys(instanceAddress); + const instanceProperties = { + type: "object", + properties: { + instanceAddress: { + type: "object", + properties: amounts.reduce((acc2, cur) => { + acc2[cur] = addressType; + return acc2; + }, {}), + required: amounts.filter((amount) => !optionalInstances.includes(amount)) + }, + decimals: { enum: [decimals] } + }, + required: ["instanceAddress", "decimals"].concat( + tokenAddress ? ["tokenAddress"] : [], + symbol ? ["symbol"] : [] + ) + }; + if (tokenAddress) { + instanceProperties.properties.tokenAddress = addressType; + } + if (symbol) { + instanceProperties.properties.symbol = { enum: [symbol] }; + } + acc.properties[token] = instanceProperties; + if (!optionalTokens.includes(token)) { + acc.required.push(token); + } + return acc; + }, + { + type: "object", + properties: {}, + required: [] + } + ); + schema.properties.instances = instances; + if (netId === NetId.MAINNET) { + const _tokens = Object.keys(tokens).filter((t) => t !== nativeCurrency); + const ethPrices = { + type: "object", + properties: _tokens.reduce((acc, token) => { + acc[token] = bnType; + return acc; + }, {}) + // required: _tokens + }; + schema.properties.ethPrices = ethPrices; + } + return schema; +} + +const jobsSchema = { + type: "object", + properties: { + error: { type: "string" }, + id: { type: "string" }, + type: { type: "string" }, + status: { type: "string" }, + contract: { type: "string" }, + proof: { type: "string" }, + args: { + type: "array", + items: { type: "string" } + }, + txHash: { type: "string" }, + confirmations: { type: "number" }, + failedReason: { type: "string" } + }, + required: ["id", "status"] +}; + +const ajv = new Ajv({ allErrors: true }); +ajv.addKeyword({ + keyword: "BN", + // eslint-disable-next-line @typescript-eslint/no-explicit-any + validate: (schema, data) => { + try { + BigInt(data); + return true; + } catch (e) { + return false; + } + }, + errors: true +}); + +const _abi$5 = [ { constant: true, inputs: [ @@ -714,15 +3720,15 @@ const _abi$6 = [ ]; class ENS__factory { static createInterface() { - return new ethers.Interface(_abi$6); + return new ethers.Interface(_abi$5); } static connect(address, runner) { - return new ethers.Contract(address, _abi$6, runner); + return new ethers.Contract(address, _abi$5, runner); } } -ENS__factory.abi = _abi$6; +ENS__factory.abi = _abi$5; -const _abi$5 = [ +const _abi$4 = [ { constant: true, inputs: [], @@ -1024,205 +4030,6 @@ const _abi$5 = [ } ]; class ERC20__factory { - static createInterface() { - return new ethers.Interface(_abi$5); - } - static connect(address, runner) { - return new ethers.Contract(address, _abi$5, runner); - } -} -ERC20__factory.abi = _abi$5; - -const _abi$4 = [ - { - inputs: [], - stateMutability: "nonpayable", - type: "constructor" - }, - { - inputs: [], - name: "GAS_UNIT", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [ - { - internalType: "uint32", - name: "_derivationThresold", - type: "uint32" - } - ], - name: "changeDerivationThresold", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [ - { - internalType: "uint32", - name: "_gasUnit", - type: "uint32" - } - ], - name: "changeGasUnit", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [ - { - internalType: "uint32", - name: "_heartbeat", - type: "uint32" - } - ], - name: "changeHeartbeat", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [ - { - internalType: "address", - name: "_owner", - type: "address" - } - ], - name: "changeOwnership", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [], - name: "derivationThresold", - outputs: [ - { - internalType: "uint32", - name: "", - type: "uint32" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [], - name: "gasPrice", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [], - name: "heartbeat", - outputs: [ - { - internalType: "uint32", - name: "", - type: "uint32" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [], - name: "maxFeePerGas", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [], - name: "maxPriorityFeePerGas", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [], - name: "owner", - outputs: [ - { - internalType: "address", - name: "", - type: "address" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [], - name: "pastGasPrice", - outputs: [ - { - internalType: "uint32", - name: "", - type: "uint32" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [ - { - internalType: "uint32", - name: "_gasPrice", - type: "uint32" - } - ], - name: "setGasPrice", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [], - name: "timestamp", - outputs: [ - { - internalType: "uint32", - name: "", - type: "uint32" - } - ], - stateMutability: "view", - type: "function" - } -]; -class GasPriceOracle__factory { static createInterface() { return new ethers.Interface(_abi$4); } @@ -1230,7 +4037,7 @@ class GasPriceOracle__factory { return new ethers.Contract(address, _abi$4, runner); } } -GasPriceOracle__factory.abi = _abi$4; +ERC20__factory.abi = _abi$4; const _abi$3 = [ { @@ -2561,1854 +5368,12 @@ var index = /*#__PURE__*/Object.freeze({ __proto__: null, ENS__factory: ENS__factory, ERC20__factory: ERC20__factory, - GasPriceOracle__factory: GasPriceOracle__factory, Multicall__factory: Multicall__factory, OffchainOracle__factory: OffchainOracle__factory, OvmGasPriceOracle__factory: OvmGasPriceOracle__factory, ReverseRecords__factory: ReverseRecords__factory }); -BigInt.prototype.toJSON = function() { - return this.toString(); -}; -const isNode = !process.browser && typeof globalThis.window === "undefined"; -const crypto = isNode ? crypto$1.webcrypto : globalThis.crypto; -const chunk = (arr, size) => [...Array(Math.ceil(arr.length / size))].map((_, i) => arr.slice(size * i, size + size * i)); -function sleep(ms) { - return new Promise((resolve) => setTimeout(resolve, ms)); -} -function validateUrl(url, protocols) { - try { - const parsedUrl = new URL(url); - if (protocols && protocols.length) { - return protocols.map((p) => p.toLowerCase()).includes(parsedUrl.protocol); - } - return true; - } catch (e) { - return false; - } -} -function concatBytes(...arrays) { - const totalSize = arrays.reduce((acc, e) => acc + e.length, 0); - const merged = new Uint8Array(totalSize); - arrays.forEach((array, i, arrays2) => { - const offset = arrays2.slice(0, i).reduce((acc, e) => acc + e.length, 0); - merged.set(array, offset); - }); - return merged; -} -function bufferToBytes(b) { - return new Uint8Array(b.buffer); -} -function bytesToBase64(bytes) { - return btoa(String.fromCharCode.apply(null, Array.from(bytes))); -} -function base64ToBytes(base64) { - return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)); -} -function bytesToHex(bytes) { - return "0x" + Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""); -} -function hexToBytes(hexString) { - if (hexString.slice(0, 2) === "0x") { - hexString = hexString.replace("0x", ""); - } - if (hexString.length % 2 !== 0) { - hexString = "0" + hexString; - } - return Uint8Array.from(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); -} -function bytesToBN(bytes) { - return BigInt(bytesToHex(bytes)); -} -function bnToBytes(bigint) { - let hexString = typeof bigint === "bigint" ? bigint.toString(16) : bigint; - if (hexString.startsWith("0x")) { - hexString = hexString.replace("0x", ""); - } - if (hexString.length % 2 !== 0) { - hexString = "0" + hexString; - } - return Uint8Array.from(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); -} -function leBuff2Int(bytes) { - return new BN(bytes, 16, "le"); -} -function leInt2Buff(bigint) { - return Uint8Array.from(new BN(bigint).toArray("le", 31)); -} -function toFixedHex(numberish, length = 32) { - return "0x" + BigInt(numberish).toString(16).padStart(length * 2, "0"); -} -function toFixedLength(string, length = 32) { - string = string.replace("0x", ""); - return "0x" + string.padStart(length * 2, "0"); -} -function rBigInt(nbytes = 31) { - return bytesToBN(crypto.getRandomValues(new Uint8Array(nbytes))); -} -function bigIntReplacer(key, value) { - return typeof value === "bigint" ? value.toString() : value; -} -function substring(str, length = 10) { - if (str.length < length * 2) { - return str; - } - return `${str.substring(0, length)}...${str.substring(str.length - length)}`; -} - -var __async$c = (__this, __arguments, generator) => { - return new Promise((resolve, reject) => { - var fulfilled = (value) => { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - }; - var rejected = (value) => { - try { - step(generator.throw(value)); - } catch (e) { - reject(e); - } - }; - var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); - step((generator = generator.apply(__this, __arguments)).next()); - }); -}; -function multicall(Multicall2, calls) { - return __async$c(this, null, function* () { - const calldata = calls.map((call) => { - var _a, _b, _c; - const target = ((_a = call.contract) == null ? void 0 : _a.target) || call.address; - const callInterface = ((_b = call.contract) == null ? void 0 : _b.interface) || call.interface; - return { - target, - callData: callInterface.encodeFunctionData(call.name, call.params), - allowFailure: (_c = call.allowFailure) != null ? _c : false - }; - }); - const returnData = yield Multicall2.aggregate3.staticCall(calldata); - const res = returnData.map((call, i) => { - var _a; - const callInterface = ((_a = calls[i].contract) == null ? void 0 : _a.interface) || calls[i].interface; - const [result, data] = call; - const decodeResult = result && data && data !== "0x" ? callInterface.decodeFunctionResult(calls[i].name, data) : null; - return !decodeResult ? null : decodeResult.length === 1 ? decodeResult[0] : decodeResult; - }); - return res; - }); -} - -var __defProp$4 = Object.defineProperty; -var __defProps$3 = Object.defineProperties; -var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors; -var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols; -var __getProtoOf$1 = Object.getPrototypeOf; -var __hasOwnProp$4 = Object.prototype.hasOwnProperty; -var __propIsEnum$4 = Object.prototype.propertyIsEnumerable; -var __reflectGet$1 = Reflect.get; -var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __spreadValues$4 = (a, b) => { - for (var prop in b || (b = {})) - if (__hasOwnProp$4.call(b, prop)) - __defNormalProp$4(a, prop, b[prop]); - if (__getOwnPropSymbols$4) - for (var prop of __getOwnPropSymbols$4(b)) { - if (__propIsEnum$4.call(b, prop)) - __defNormalProp$4(a, prop, b[prop]); - } - return a; -}; -var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b)); -var __superGet$1 = (cls, obj, key) => __reflectGet$1(__getProtoOf$1(cls), key, obj); -var __async$b = (__this, __arguments, generator) => { - return new Promise((resolve, reject) => { - var fulfilled = (value) => { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - }; - var rejected = (value) => { - try { - step(generator.throw(value)); - } catch (e) { - reject(e); - } - }; - var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); - step((generator = generator.apply(__this, __arguments)).next()); - }); -}; -const defaultUserAgent = "Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/115.0"; -const fetch = crossFetch; -function getHttpAgent({ - fetchUrl, - proxyUrl, - torPort, - retry -}) { - const { HttpProxyAgent } = require("http-proxy-agent"); - const { HttpsProxyAgent } = require("https-proxy-agent"); - const { SocksProxyAgent } = require("socks-proxy-agent"); - if (torPort) { - return new SocksProxyAgent(`socks5h://tor${retry}@127.0.0.1:${torPort}`); - } - if (!proxyUrl) { - return; - } - const isHttps = fetchUrl.includes("https://"); - if (proxyUrl.includes("socks://") || proxyUrl.includes("socks4://") || proxyUrl.includes("socks5://")) { - return new SocksProxyAgent(proxyUrl); - } - if (proxyUrl.includes("http://") || proxyUrl.includes("https://")) { - if (isHttps) { - return new HttpsProxyAgent(proxyUrl); - } - return new HttpProxyAgent(proxyUrl); - } -} -function fetchData(_0) { - return __async$b(this, arguments, function* (url, options = {}) { - var _a, _b, _c; - const MAX_RETRY = (_a = options.maxRetry) != null ? _a : 3; - const RETRY_ON = (_b = options.retryOn) != null ? _b : 500; - const userAgent = (_c = options.userAgent) != null ? _c : defaultUserAgent; - let retry = 0; - let errorObject; - if (!options.method) { - if (!options.body) { - options.method = "GET"; - } else { - options.method = "POST"; - } - } - if (!options.headers) { - options.headers = {}; - } - if (isNode && !options.headers["User-Agent"]) { - options.headers["User-Agent"] = userAgent; - } - while (retry < MAX_RETRY + 1) { - let timeout; - if (!options.signal && options.timeout) { - const controller = new AbortController(); - options.signal = controller.signal; - timeout = setTimeout(() => { - controller.abort(); - }, options.timeout); - } - if (!options.agent && isNode && (options.proxy || options.torPort)) { - options.agent = getHttpAgent({ - fetchUrl: url, - proxyUrl: options.proxy, - torPort: options.torPort, - retry - }); - } - if (options.debug && typeof options.debug === "function") { - options.debug("request", { - url, - retry, - errorObject, - options - }); - } - try { - const resp = yield fetch(url, { - method: options.method, - headers: options.headers, - body: options.body, - redirect: options.redirect, - signal: options.signal, - agent: options.agent - }); - if (options.debug && typeof options.debug === "function") { - options.debug("response", resp); - } - if (!resp.ok) { - const errMsg = `Request to ${url} failed with error code ${resp.status}: -` + (yield resp.text()); - throw new Error(errMsg); - } - if (options.returnResponse) { - return resp; - } - const contentType = resp.headers.get("content-type"); - if (contentType == null ? void 0 : contentType.includes("application/json")) { - return yield resp.json(); - } - if (contentType == null ? void 0 : contentType.includes("text")) { - return yield resp.text(); - } - return resp; - } catch (error) { - if (timeout) { - clearTimeout(timeout); - } - errorObject = error; - retry++; - yield sleep(RETRY_ON); - } finally { - if (timeout) { - clearTimeout(timeout); - } - } - } - if (options.debug && typeof options.debug === "function") { - options.debug("error", errorObject); - } - throw errorObject; - }); -} -const fetchGetUrlFunc = (options = {}) => (req, _signal) => __async$b(void 0, null, function* () { - let signal; - if (_signal) { - const controller = new AbortController(); - signal = controller.signal; - _signal.addListener(() => { - controller.abort(); - }); - } - const init = __spreadProps$3(__spreadValues$4({}, options), { - method: req.method || "POST", - headers: req.headers, - body: req.body || void 0, - signal, - returnResponse: true - }); - const resp = yield fetchData(req.url, init); - const headers = {}; - resp.headers.forEach((value, key) => { - headers[key.toLowerCase()] = value; - }); - const respBody = yield resp.arrayBuffer(); - const body = respBody == null ? null : new Uint8Array(respBody); - return { - statusCode: resp.status, - statusMessage: resp.statusText, - headers, - body - }; -}); -const oracleMapper = /* @__PURE__ */ new Map(); -const multicallMapper = /* @__PURE__ */ new Map(); -function getGasOraclePlugin(networkKey, fetchOptions) { - const gasStationApi = (fetchOptions == null ? void 0 : fetchOptions.gasStationApi) || "https://gasstation.polygon.technology/v2"; - return new ethers.FetchUrlFeeDataNetworkPlugin(gasStationApi, (fetchFeeData, provider, request) => __async$b(this, null, function* () { - if (!oracleMapper.has(networkKey)) { - oracleMapper.set(networkKey, GasPriceOracle__factory.connect(fetchOptions == null ? void 0 : fetchOptions.gasPriceOracle, provider)); - } - if (!multicallMapper.has(networkKey)) { - multicallMapper.set( - networkKey, - Multicall__factory.connect("0xcA11bde05977b3631167028862bE2a173976CA11", provider) - ); - } - const Oracle = oracleMapper.get(networkKey); - const Multicall2 = multicallMapper.get(networkKey); - const [timestamp, heartbeat, feePerGas, priorityFeePerGas] = yield multicall(Multicall2, [ - { - contract: Oracle, - name: "timestamp" - }, - { - contract: Oracle, - name: "heartbeat" - }, - { - contract: Oracle, - name: "maxFeePerGas" - }, - { - contract: Oracle, - name: "maxPriorityFeePerGas" - } - ]); - const isOutdated = Number(timestamp) <= Date.now() / 1e3 - Number(heartbeat); - if (!isOutdated) { - const maxPriorityFeePerGas = priorityFeePerGas * BigInt(13) / BigInt(10); - const maxFeePerGas = feePerGas * BigInt(2) + maxPriorityFeePerGas; - return { - gasPrice: maxFeePerGas, - maxFeePerGas, - maxPriorityFeePerGas - }; - } - const fetchReq = new ethers.FetchRequest(gasStationApi); - fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); - if (isNode) { - fetchReq.setHeader("User-Agent", "ethers"); - } - const [ - { - bodyJson: { fast } - }, - { gasPrice } - ] = yield Promise.all([fetchReq.send(), fetchFeeData()]); - return { - gasPrice, - maxFeePerGas: ethers.parseUnits(`${fast.maxFee}`, 9), - maxPriorityFeePerGas: ethers.parseUnits(`${fast.maxPriorityFee}`, 9) - }; - })); -} -function getProvider(rpcUrl, fetchOptions) { - return __async$b(this, null, function* () { - const fetchReq = new ethers.FetchRequest(rpcUrl); - fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); - const _staticNetwork = yield new ethers.JsonRpcProvider(fetchReq).getNetwork(); - const ensPlugin = _staticNetwork.getPlugin("org.ethers.plugins.network.Ens"); - const gasCostPlugin = _staticNetwork.getPlugin("org.ethers.plugins.network.GasCost"); - const gasStationPlugin = _staticNetwork.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin"); - const staticNetwork = new ethers.Network(_staticNetwork.name, _staticNetwork.chainId); - if (ensPlugin) { - staticNetwork.attachPlugin(ensPlugin); - } - if (gasCostPlugin) { - staticNetwork.attachPlugin(gasCostPlugin); - } - if (fetchOptions == null ? void 0 : fetchOptions.gasPriceOracle) { - staticNetwork.attachPlugin(getGasOraclePlugin(`${_staticNetwork.chainId}_${rpcUrl}`, fetchOptions)); - } else if (gasStationPlugin) { - staticNetwork.attachPlugin(gasStationPlugin); - } - const provider = new ethers.JsonRpcProvider(fetchReq, staticNetwork, { - staticNetwork - }); - provider.pollingInterval = (fetchOptions == null ? void 0 : fetchOptions.pollingInterval) || 1e3; - return provider; - }); -} -function getProviderWithNetId(netId, rpcUrl, config, fetchOptions) { - const { networkName, reverseRecordsContract, gasPriceOracleContract, gasStationApi, pollInterval } = config; - const hasEns = Boolean(reverseRecordsContract); - const fetchReq = new ethers.FetchRequest(rpcUrl); - fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); - const staticNetwork = new ethers.Network(networkName, netId); - if (hasEns) { - staticNetwork.attachPlugin(new ethers.EnsPlugin(null, Number(netId))); - } - staticNetwork.attachPlugin(new ethers.GasCostPlugin()); - if (gasPriceOracleContract) { - staticNetwork.attachPlugin( - getGasOraclePlugin(`${netId}_${rpcUrl}`, { - gasPriceOracle: gasPriceOracleContract, - gasStationApi - }) - ); - } - const provider = new ethers.JsonRpcProvider(fetchReq, staticNetwork, { - staticNetwork - }); - provider.pollingInterval = (fetchOptions == null ? void 0 : fetchOptions.pollingInterval) || pollInterval * 1e3; - return provider; -} -const populateTransaction = (signer, tx) => __async$b(void 0, null, function* () { - const provider = signer.provider; - if (!tx.from) { - tx.from = signer.address; - } else if (tx.from !== signer.address) { - const errMsg = `populateTransaction: signer mismatch for tx, wants ${tx.from} have ${signer.address}`; - throw new Error(errMsg); - } - const [feeData, nonce] = yield Promise.all([ - (() => __async$b(void 0, null, function* () { - if (tx.maxFeePerGas && tx.maxPriorityFeePerGas) { - return new ethers.FeeData(null, BigInt(tx.maxFeePerGas), BigInt(tx.maxPriorityFeePerGas)); - } - if (tx.gasPrice) { - return new ethers.FeeData(BigInt(tx.gasPrice), null, null); - } - const fetchedFeeData = yield provider.getFeeData(); - if (fetchedFeeData.maxFeePerGas && fetchedFeeData.maxPriorityFeePerGas) { - return new ethers.FeeData( - null, - fetchedFeeData.maxFeePerGas * (BigInt(1e4) + BigInt(signer.gasPriceBump)) / BigInt(1e4), - fetchedFeeData.maxPriorityFeePerGas - ); - } else { - return new ethers.FeeData( - fetchedFeeData.gasPrice * (BigInt(1e4) + BigInt(signer.gasPriceBump)) / BigInt(1e4), - null, - null - ); - } - }))(), - (() => __async$b(void 0, null, function* () { - if (tx.nonce) { - return tx.nonce; - } - let fetchedNonce = yield provider.getTransactionCount(signer.address, "pending"); - if (signer.bumpNonce && signer.nonce && signer.nonce >= fetchedNonce) { - console.log( - `populateTransaction: bumping nonce from ${fetchedNonce} to ${fetchedNonce + 1} for ${signer.address}` - ); - fetchedNonce++; - } - return fetchedNonce; - }))() - ]); - tx.nonce = nonce; - if (feeData.maxFeePerGas && feeData.maxPriorityFeePerGas) { - tx.maxFeePerGas = feeData.maxFeePerGas; - tx.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; - if (!tx.type) { - tx.type = 2; - } - delete tx.gasPrice; - } else if (feeData.gasPrice) { - tx.gasPrice = feeData.gasPrice; - if (!tx.type) { - tx.type = 0; - } - delete tx.maxFeePerGas; - delete tx.maxPriorityFeePerGas; - } - tx.gasLimit = tx.gasLimit || (yield (() => __async$b(void 0, null, function* () { - try { - const gasLimit = yield provider.estimateGas(tx); - return gasLimit === BigInt(21e3) ? gasLimit : gasLimit * (BigInt(1e4) + BigInt(signer.gasLimitBump)) / BigInt(1e4); - } catch (err) { - if (signer.gasFailover) { - console.log("populateTransaction: warning gas estimation failed falling back to 3M gas"); - return BigInt("3000000"); - } - throw err; - } - }))()); - return tx; -}); -class TornadoWallet extends ethers.Wallet { - constructor(key, provider, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce } = {}) { - super(key, provider); - this.gasPriceBump = gasPriceBump != null ? gasPriceBump : 0; - this.gasLimitBump = gasLimitBump != null ? gasLimitBump : 3e3; - this.gasFailover = gasFailover != null ? gasFailover : false; - this.bumpNonce = bumpNonce != null ? bumpNonce : false; - } - static fromMnemonic(mneomnic, provider, index = 0, options) { - const defaultPath = `m/44'/60'/0'/0/${index}`; - const { privateKey } = ethers.HDNodeWallet.fromPhrase(mneomnic, void 0, defaultPath); - return new TornadoWallet(privateKey, provider, options); - } - populateTransaction(tx) { - return __async$b(this, null, function* () { - const txObject = yield populateTransaction(this, tx); - this.nonce = txObject.nonce; - return __superGet$1(TornadoWallet.prototype, this, "populateTransaction").call(this, txObject); - }); - } -} -class TornadoVoidSigner extends ethers.VoidSigner { - constructor(address, provider, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce } = {}) { - super(address, provider); - this.gasPriceBump = gasPriceBump != null ? gasPriceBump : 0; - this.gasLimitBump = gasLimitBump != null ? gasLimitBump : 3e3; - this.gasFailover = gasFailover != null ? gasFailover : false; - this.bumpNonce = bumpNonce != null ? bumpNonce : false; - } - populateTransaction(tx) { - return __async$b(this, null, function* () { - const txObject = yield populateTransaction(this, tx); - this.nonce = txObject.nonce; - return __superGet$1(TornadoVoidSigner.prototype, this, "populateTransaction").call(this, txObject); - }); - } -} -class TornadoRpcSigner extends ethers.JsonRpcSigner { - constructor(provider, address, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce } = {}) { - super(provider, address); - this.gasPriceBump = gasPriceBump != null ? gasPriceBump : 0; - this.gasLimitBump = gasLimitBump != null ? gasLimitBump : 3e3; - this.gasFailover = gasFailover != null ? gasFailover : false; - this.bumpNonce = bumpNonce != null ? bumpNonce : false; - } - sendUncheckedTransaction(tx) { - return __async$b(this, null, function* () { - return __superGet$1(TornadoRpcSigner.prototype, this, "sendUncheckedTransaction").call(this, yield populateTransaction(this, tx)); - }); - } -} -class TornadoBrowserProvider extends ethers.BrowserProvider { - constructor(ethereum, network, options) { - super(ethereum, network); - this.options = options; - } - getSigner(address) { - return __async$b(this, null, function* () { - var _a, _b, _c, _d, _e, _f, _g, _h, _i; - const signerAddress = (yield __superGet$1(TornadoBrowserProvider.prototype, this, "getSigner").call(this, address)).address; - if (((_a = this.options) == null ? void 0 : _a.webChainId) && ((_b = this.options) == null ? void 0 : _b.connectWallet) && Number(yield __superGet$1(TornadoBrowserProvider.prototype, this, "send").call(this, "eth_chainId", [])) !== Number((_c = this.options) == null ? void 0 : _c.webChainId)) { - yield this.options.connectWallet(); - } - if ((_d = this.options) == null ? void 0 : _d.handleNetworkChanges) { - (_e = window == null ? void 0 : window.ethereum) == null ? void 0 : _e.on("chainChanged", this.options.handleNetworkChanges); - } - if ((_f = this.options) == null ? void 0 : _f.handleAccountChanges) { - (_g = window == null ? void 0 : window.ethereum) == null ? void 0 : _g.on("accountsChanged", this.options.handleAccountChanges); - } - if ((_h = this.options) == null ? void 0 : _h.handleAccountDisconnect) { - (_i = window == null ? void 0 : window.ethereum) == null ? void 0 : _i.on("disconnect", this.options.handleAccountDisconnect); - } - return new TornadoRpcSigner(this, signerAddress, this.options); - }); - } -} - -const GET_STATISTIC = ` - query getStatistic($currency: String!, $amount: String!, $first: Int, $orderBy: BigInt, $orderDirection: String) { - deposits(first: $first, orderBy: $orderBy, orderDirection: $orderDirection, where: { currency: $currency, amount: $amount }) { - index - timestamp - blockNumber - } - _meta { - block { - number - } - hasIndexingErrors - } - } -`; -const _META = ` - query getMeta { - _meta { - block { - number - } - hasIndexingErrors - } - } -`; -const GET_REGISTERED = ` - query getRegistered($first: Int, $fromBlock: Int) { - relayers(first: $first, orderBy: blockRegistration, orderDirection: asc, where: { - blockRegistration_gte: $fromBlock - }) { - id - address - ensName - blockRegistration - } - _meta { - block { - number - } - hasIndexingErrors - } - } -`; -const GET_DEPOSITS = ` - query getDeposits($currency: String!, $amount: String!, $first: Int, $fromBlock: Int) { - deposits(first: $first, orderBy: index, orderDirection: asc, where: { - amount: $amount, - currency: $currency, - blockNumber_gte: $fromBlock - }) { - id - blockNumber - commitment - index - timestamp - from - } - _meta { - block { - number - } - hasIndexingErrors - } - } -`; -const GET_WITHDRAWALS = ` - query getWithdrawals($currency: String!, $amount: String!, $first: Int, $fromBlock: Int!) { - withdrawals(first: $first, orderBy: blockNumber, orderDirection: asc, where: { - currency: $currency, - amount: $amount, - blockNumber_gte: $fromBlock - }) { - id - blockNumber - nullifier - to - fee - timestamp - } - _meta { - block { - number - } - hasIndexingErrors - } - } -`; -const GET_NOTE_ACCOUNTS = ` - query getNoteAccount($address: String!) { - noteAccounts(where: { address: $address }) { - id - index - address - encryptedAccount - } - _meta { - block { - number - } - hasIndexingErrors - } - } -`; -const GET_ECHO_EVENTS = ` - query getNoteAccounts($first: Int, $fromBlock: Int) { - noteAccounts(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { - id - blockNumber - address - encryptedAccount - } - _meta { - block { - number - } - hasIndexingErrors - } - } -`; -const GET_ENCRYPTED_NOTES = ` - query getEncryptedNotes($first: Int, $fromBlock: Int) { - encryptedNotes(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { - blockNumber - index - transactionHash - encryptedNote - } - _meta { - block { - number - } - hasIndexingErrors - } - } -`; -const GET_GOVERNANCE_EVENTS = ` - query getGovernanceEvents($first: Int, $fromBlock: Int) { - proposals(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { - blockNumber - logIndex - transactionHash - proposalId - proposer - target - startTime - endTime - description - } - votes(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { - blockNumber - logIndex - transactionHash - proposalId - voter - support - votes - from - input - } - delegates(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { - blockNumber - logIndex - transactionHash - account - delegateTo - } - undelegates(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { - blockNumber - logIndex - transactionHash - account - delegateFrom - } - _meta { - block { - number - } - hasIndexingErrors - } - } -`; -const GET_GOVERNANCE_APY = ` - stakeDailyBurns(first: 30, orderBy: date, orderDirection: desc) { - id - date - dailyAmountBurned - } -`; - -var __defProp$3 = Object.defineProperty; -var __defProps$2 = Object.defineProperties; -var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors; -var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols; -var __hasOwnProp$3 = Object.prototype.hasOwnProperty; -var __propIsEnum$3 = Object.prototype.propertyIsEnumerable; -var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __spreadValues$3 = (a, b) => { - for (var prop in b || (b = {})) - if (__hasOwnProp$3.call(b, prop)) - __defNormalProp$3(a, prop, b[prop]); - if (__getOwnPropSymbols$3) - for (var prop of __getOwnPropSymbols$3(b)) { - if (__propIsEnum$3.call(b, prop)) - __defNormalProp$3(a, prop, b[prop]); - } - return a; -}; -var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b)); -var __async$a = (__this, __arguments, generator) => { - return new Promise((resolve, reject) => { - var fulfilled = (value) => { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - }; - var rejected = (value) => { - try { - step(generator.throw(value)); - } catch (e) { - reject(e); - } - }; - var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); - step((generator = generator.apply(__this, __arguments)).next()); - }); -}; -const isEmptyArray = (arr) => !Array.isArray(arr) || !arr.length; -const GRAPHQL_LIMIT = 1e3; -function queryGraph(_0) { - return __async$a(this, arguments, function* ({ - graphApi, - subgraphName, - query, - variables, - fetchDataOptions: fetchDataOptions2 - }) { - var _a; - const graphUrl = `${graphApi}/subgraphs/name/${subgraphName}`; - const { data, errors } = yield fetchData(graphUrl, __spreadProps$2(__spreadValues$3({}, fetchDataOptions2), { - method: "POST", - headers: { - "Content-Type": "application/json" - }, - body: JSON.stringify({ - query, - variables - }) - })); - if (errors) { - throw new Error(JSON.stringify(errors)); - } - if ((_a = data == null ? void 0 : data._meta) == null ? void 0 : _a.hasIndexingErrors) { - throw new Error("Subgraph has indexing errors"); - } - return data; - }); -} -function getStatistic(_0) { - return __async$a(this, arguments, function* ({ - graphApi, - subgraphName, - currency, - amount, - fetchDataOptions: fetchDataOptions2 - }) { - try { - const { - deposits, - _meta: { - block: { number: lastSyncBlock } - } - } = yield queryGraph({ - graphApi, - subgraphName, - query: GET_STATISTIC, - variables: { - currency, - first: 10, - orderBy: "index", - orderDirection: "desc", - amount - }, - fetchDataOptions: fetchDataOptions2 - }); - const events = deposits.map((e) => ({ - timestamp: Number(e.timestamp), - leafIndex: Number(e.index), - blockNumber: Number(e.blockNumber) - })).reverse(); - const [lastEvent] = events.slice(-1); - return { - events, - lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock - }; - } catch (err) { - console.log("Error from getStatistic query"); - console.log(err); - return { - events: [], - lastSyncBlock: null - }; - } - }); -} -function getMeta(_0) { - return __async$a(this, arguments, function* ({ graphApi, subgraphName, fetchDataOptions: fetchDataOptions2 }) { - try { - const { - _meta: { - block: { number: lastSyncBlock }, - hasIndexingErrors - } - } = yield queryGraph({ - graphApi, - subgraphName, - query: _META, - fetchDataOptions: fetchDataOptions2 - }); - return { - lastSyncBlock, - hasIndexingErrors - }; - } catch (err) { - console.log("Error from getMeta query"); - console.log(err); - return { - lastSyncBlock: null, - hasIndexingErrors: null - }; - } - }); -} -function getRegisters({ - graphApi, - subgraphName, - fromBlock, - fetchDataOptions: fetchDataOptions2 -}) { - return queryGraph({ - graphApi, - subgraphName, - query: GET_REGISTERED, - variables: { - first: GRAPHQL_LIMIT, - fromBlock - }, - fetchDataOptions: fetchDataOptions2 - }); -} -function getAllRegisters(_0) { - return __async$a(this, arguments, function* ({ - graphApi, - subgraphName, - fromBlock, - fetchDataOptions: fetchDataOptions2, - onProgress - }) { - try { - const events = []; - let lastSyncBlock = fromBlock; - while (true) { - let { - relayers: result2, - _meta: { - // eslint-disable-next-line prefer-const - block: { number: currentBlock } - } - } = yield getRegisters({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); - lastSyncBlock = currentBlock; - if (isEmptyArray(result2)) { - break; - } - const [firstEvent] = result2; - const [lastEvent] = result2.slice(-1); - if (typeof onProgress === "function") { - onProgress({ - type: "Registers", - fromBlock: Number(firstEvent.blockRegistration), - toBlock: Number(lastEvent.blockRegistration), - count: result2.length - }); - } - if (result2.length < 900) { - events.push(...result2); - break; - } - result2 = result2.filter(({ blockRegistration }) => blockRegistration !== lastEvent.blockRegistration); - fromBlock = Number(lastEvent.blockRegistration); - events.push(...result2); - } - if (!events.length) { - return { - events: [], - lastSyncBlock - }; - } - const result = events.map(({ id, address, ensName, blockRegistration }) => { - const [transactionHash, logIndex] = id.split("-"); - return { - blockNumber: Number(blockRegistration), - logIndex: Number(logIndex), - transactionHash, - ensName, - relayerAddress: ethers.getAddress(address) - }; - }); - return { - events: result, - lastSyncBlock - }; - } catch (err) { - console.log("Error from getAllRegisters query"); - console.log(err); - return { events: [], lastSyncBlock: fromBlock }; - } - }); -} -function getDeposits({ - graphApi, - subgraphName, - currency, - amount, - fromBlock, - fetchDataOptions: fetchDataOptions2 -}) { - return queryGraph({ - graphApi, - subgraphName, - query: GET_DEPOSITS, - variables: { - currency, - amount, - first: GRAPHQL_LIMIT, - fromBlock - }, - fetchDataOptions: fetchDataOptions2 - }); -} -function getAllDeposits(_0) { - return __async$a(this, arguments, function* ({ - graphApi, - subgraphName, - currency, - amount, - fromBlock, - fetchDataOptions: fetchDataOptions2, - onProgress - }) { - try { - const events = []; - let lastSyncBlock = fromBlock; - while (true) { - let { - deposits: result2, - _meta: { - // eslint-disable-next-line prefer-const - block: { number: currentBlock } - } - } = yield getDeposits({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions: fetchDataOptions2 }); - lastSyncBlock = currentBlock; - if (isEmptyArray(result2)) { - break; - } - const [firstEvent] = result2; - const [lastEvent2] = result2.slice(-1); - if (typeof onProgress === "function") { - onProgress({ - type: "Deposits", - fromBlock: Number(firstEvent.blockNumber), - toBlock: Number(lastEvent2.blockNumber), - count: result2.length - }); - } - if (result2.length < 900) { - events.push(...result2); - break; - } - result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); - fromBlock = Number(lastEvent2.blockNumber); - events.push(...result2); - } - if (!events.length) { - return { - events: [], - lastSyncBlock - }; - } - const result = events.map(({ id, blockNumber, commitment, index, timestamp, from }) => { - const [transactionHash, logIndex] = id.split("-"); - return { - blockNumber: Number(blockNumber), - logIndex: Number(logIndex), - transactionHash, - commitment, - leafIndex: Number(index), - timestamp: Number(timestamp), - from: ethers.getAddress(from) - }; - }); - const [lastEvent] = result.slice(-1); - return { - events: result, - lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock - }; - } catch (err) { - console.log("Error from getAllDeposits query"); - console.log(err); - return { - events: [], - lastSyncBlock: fromBlock - }; - } - }); -} -function getWithdrawals({ - graphApi, - subgraphName, - currency, - amount, - fromBlock, - fetchDataOptions: fetchDataOptions2 -}) { - return queryGraph({ - graphApi, - subgraphName, - query: GET_WITHDRAWALS, - variables: { - currency, - amount, - first: GRAPHQL_LIMIT, - fromBlock - }, - fetchDataOptions: fetchDataOptions2 - }); -} -function getAllWithdrawals(_0) { - return __async$a(this, arguments, function* ({ - graphApi, - subgraphName, - currency, - amount, - fromBlock, - fetchDataOptions: fetchDataOptions2, - onProgress - }) { - try { - const events = []; - let lastSyncBlock = fromBlock; - while (true) { - let { - withdrawals: result2, - _meta: { - // eslint-disable-next-line prefer-const - block: { number: currentBlock } - } - } = yield getWithdrawals({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions: fetchDataOptions2 }); - lastSyncBlock = currentBlock; - if (isEmptyArray(result2)) { - break; - } - const [firstEvent] = result2; - const [lastEvent2] = result2.slice(-1); - if (typeof onProgress === "function") { - onProgress({ - type: "Withdrawals", - fromBlock: Number(firstEvent.blockNumber), - toBlock: Number(lastEvent2.blockNumber), - count: result2.length - }); - } - if (result2.length < 900) { - events.push(...result2); - break; - } - result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); - fromBlock = Number(lastEvent2.blockNumber); - events.push(...result2); - } - if (!events.length) { - return { - events: [], - lastSyncBlock - }; - } - const result = events.map(({ id, blockNumber, nullifier, to, fee, timestamp }) => { - const [transactionHash, logIndex] = id.split("-"); - return { - blockNumber: Number(blockNumber), - logIndex: Number(logIndex), - transactionHash, - nullifierHash: nullifier, - to: ethers.getAddress(to), - fee, - timestamp: Number(timestamp) - }; - }); - const [lastEvent] = result.slice(-1); - return { - events: result, - lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock - }; - } catch (err) { - console.log("Error from getAllWithdrawals query"); - console.log(err); - return { - events: [], - lastSyncBlock: fromBlock - }; - } - }); -} -function getNoteAccounts(_0) { - return __async$a(this, arguments, function* ({ - graphApi, - subgraphName, - address, - fetchDataOptions: fetchDataOptions2 - }) { - try { - const { - noteAccounts: events, - _meta: { - block: { number: lastSyncBlock } - } - } = yield queryGraph({ - graphApi, - subgraphName, - query: GET_NOTE_ACCOUNTS, - variables: { - address: address.toLowerCase() - }, - fetchDataOptions: fetchDataOptions2 - }); - return { - events, - lastSyncBlock - }; - } catch (err) { - console.log("Error from getNoteAccounts query"); - console.log(err); - return { - events: [], - lastSyncBlock: null - }; - } - }); -} -function getGraphEchoEvents({ - graphApi, - subgraphName, - fromBlock, - fetchDataOptions: fetchDataOptions2 -}) { - return queryGraph({ - graphApi, - subgraphName, - query: GET_ECHO_EVENTS, - variables: { - first: GRAPHQL_LIMIT, - fromBlock - }, - fetchDataOptions: fetchDataOptions2 - }); -} -function getAllGraphEchoEvents(_0) { - return __async$a(this, arguments, function* ({ - graphApi, - subgraphName, - fromBlock, - fetchDataOptions: fetchDataOptions2, - onProgress - }) { - try { - const events = []; - let lastSyncBlock = fromBlock; - while (true) { - let { - noteAccounts: result2, - _meta: { - // eslint-disable-next-line prefer-const - block: { number: currentBlock } - } - } = yield getGraphEchoEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); - lastSyncBlock = currentBlock; - if (isEmptyArray(result2)) { - break; - } - const [firstEvent] = result2; - const [lastEvent2] = result2.slice(-1); - if (typeof onProgress === "function") { - onProgress({ - type: "EchoEvents", - fromBlock: Number(firstEvent.blockNumber), - toBlock: Number(lastEvent2.blockNumber), - count: result2.length - }); - } - if (result2.length < 900) { - events.push(...result2); - break; - } - result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); - fromBlock = Number(lastEvent2.blockNumber); - events.push(...result2); - } - if (!events.length) { - return { - events: [], - lastSyncBlock - }; - } - const result = events.map((e) => { - const [transactionHash, logIndex] = e.id.split("-"); - return { - blockNumber: Number(e.blockNumber), - logIndex: Number(logIndex), - transactionHash, - address: ethers.getAddress(e.address), - encryptedAccount: e.encryptedAccount - }; - }); - const [lastEvent] = result.slice(-1); - return { - events: result, - lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock - }; - } catch (err) { - console.log("Error from getAllGraphEchoEvents query"); - console.log(err); - return { - events: [], - lastSyncBlock: fromBlock - }; - } - }); -} -function getEncryptedNotes({ - graphApi, - subgraphName, - fromBlock, - fetchDataOptions: fetchDataOptions2 -}) { - return queryGraph({ - graphApi, - subgraphName, - query: GET_ENCRYPTED_NOTES, - variables: { - first: GRAPHQL_LIMIT, - fromBlock - }, - fetchDataOptions: fetchDataOptions2 - }); -} -function getAllEncryptedNotes(_0) { - return __async$a(this, arguments, function* ({ - graphApi, - subgraphName, - fromBlock, - fetchDataOptions: fetchDataOptions2, - onProgress - }) { - try { - const events = []; - let lastSyncBlock = fromBlock; - while (true) { - let { - encryptedNotes: result2, - _meta: { - // eslint-disable-next-line prefer-const - block: { number: currentBlock } - } - } = yield getEncryptedNotes({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); - lastSyncBlock = currentBlock; - if (isEmptyArray(result2)) { - break; - } - const [firstEvent] = result2; - const [lastEvent2] = result2.slice(-1); - if (typeof onProgress === "function") { - onProgress({ - type: "EncryptedNotes", - fromBlock: Number(firstEvent.blockNumber), - toBlock: Number(lastEvent2.blockNumber), - count: result2.length - }); - } - if (result2.length < 900) { - events.push(...result2); - break; - } - result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); - fromBlock = Number(lastEvent2.blockNumber); - events.push(...result2); - } - if (!events.length) { - return { - events: [], - lastSyncBlock - }; - } - const result = events.map((e) => ({ - blockNumber: Number(e.blockNumber), - logIndex: Number(e.index), - transactionHash: e.transactionHash, - encryptedNote: e.encryptedNote - })); - const [lastEvent] = result.slice(-1); - return { - events: result, - lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock - }; - } catch (err) { - console.log("Error from getAllEncryptedNotes query"); - console.log(err); - return { - events: [], - lastSyncBlock: fromBlock - }; - } - }); -} -function getGovernanceEvents({ - graphApi, - subgraphName, - fromBlock, - fetchDataOptions: fetchDataOptions2 -}) { - return queryGraph({ - graphApi, - subgraphName, - query: GET_GOVERNANCE_EVENTS, - variables: { - first: GRAPHQL_LIMIT, - fromBlock - }, - fetchDataOptions: fetchDataOptions2 - }); -} -function getAllGovernanceEvents(_0) { - return __async$a(this, arguments, function* ({ - graphApi, - subgraphName, - fromBlock, - fetchDataOptions: fetchDataOptions2, - onProgress - }) { - try { - const result = []; - let lastSyncBlock = fromBlock; - while (true) { - const { - proposals, - votes, - delegates, - undelegates, - _meta: { - block: { number: currentBlock } - } - } = yield getGovernanceEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); - lastSyncBlock = currentBlock; - const eventsLength = proposals.length + votes.length + delegates.length + undelegates.length; - if (eventsLength === 0) { - break; - } - const formattedProposals = proposals.map( - ({ blockNumber, logIndex, transactionHash, proposalId, proposer, target, startTime, endTime, description }) => { - return { - blockNumber: Number(blockNumber), - logIndex: Number(logIndex), - transactionHash, - event: "ProposalCreated", - id: Number(proposalId), - proposer: ethers.getAddress(proposer), - target: ethers.getAddress(target), - startTime: Number(startTime), - endTime: Number(endTime), - description - }; - } - ); - const formattedVotes = votes.map( - ({ blockNumber, logIndex, transactionHash, proposalId, voter, support, votes: votes2, from, input }) => { - if (!input || input.length > 2048) { - input = ""; - } - return { - blockNumber: Number(blockNumber), - logIndex: Number(logIndex), - transactionHash, - event: "Voted", - proposalId: Number(proposalId), - voter: ethers.getAddress(voter), - support, - votes: votes2, - from: ethers.getAddress(from), - input - }; - } - ); - const formattedDelegates = delegates.map( - ({ blockNumber, logIndex, transactionHash, account, delegateTo }) => { - return { - blockNumber: Number(blockNumber), - logIndex: Number(logIndex), - transactionHash, - event: "Delegated", - account: ethers.getAddress(account), - delegateTo: ethers.getAddress(delegateTo) - }; - } - ); - const formattedUndelegates = undelegates.map( - ({ blockNumber, logIndex, transactionHash, account, delegateFrom }) => { - return { - blockNumber: Number(blockNumber), - logIndex: Number(logIndex), - transactionHash, - event: "Undelegated", - account: ethers.getAddress(account), - delegateFrom: ethers.getAddress(delegateFrom) - }; - } - ); - let formattedEvents = [ - ...formattedProposals, - ...formattedVotes, - ...formattedDelegates, - ...formattedUndelegates - ].sort((a, b) => { - if (a.blockNumber === b.blockNumber) { - return a.logIndex - b.logIndex; - } - return a.blockNumber - b.blockNumber; - }); - if (eventsLength < 900) { - result.push(...formattedEvents); - break; - } - const [firstEvent] = formattedEvents; - const [lastEvent2] = formattedEvents.slice(-1); - if (typeof onProgress === "function") { - onProgress({ - type: "Governance Events", - fromBlock: Number(firstEvent.blockNumber), - toBlock: Number(lastEvent2.blockNumber), - count: eventsLength - }); - } - formattedEvents = formattedEvents.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); - fromBlock = Number(lastEvent2.blockNumber); - result.push(...formattedEvents); - } - const [lastEvent] = result.slice(-1); - return { - events: result, - lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock - }; - } catch (err) { - console.log("Error from getAllGovernance query"); - console.log(err); - return { - events: [], - lastSyncBlock: fromBlock - }; - } - }); -} - -var graph = /*#__PURE__*/Object.freeze({ - __proto__: null, - GET_DEPOSITS: GET_DEPOSITS, - GET_ECHO_EVENTS: GET_ECHO_EVENTS, - GET_ENCRYPTED_NOTES: GET_ENCRYPTED_NOTES, - GET_GOVERNANCE_APY: GET_GOVERNANCE_APY, - GET_GOVERNANCE_EVENTS: GET_GOVERNANCE_EVENTS, - GET_NOTE_ACCOUNTS: GET_NOTE_ACCOUNTS, - GET_REGISTERED: GET_REGISTERED, - GET_STATISTIC: GET_STATISTIC, - GET_WITHDRAWALS: GET_WITHDRAWALS, - _META: _META, - getAllDeposits: getAllDeposits, - getAllEncryptedNotes: getAllEncryptedNotes, - getAllGovernanceEvents: getAllGovernanceEvents, - getAllGraphEchoEvents: getAllGraphEchoEvents, - getAllRegisters: getAllRegisters, - getAllWithdrawals: getAllWithdrawals, - getDeposits: getDeposits, - getEncryptedNotes: getEncryptedNotes, - getGovernanceEvents: getGovernanceEvents, - getGraphEchoEvents: getGraphEchoEvents, - getMeta: getMeta, - getNoteAccounts: getNoteAccounts, - getRegisters: getRegisters, - getStatistic: getStatistic, - getWithdrawals: getWithdrawals, - queryGraph: queryGraph -}); - -var __async$9 = (__this, __arguments, generator) => { - return new Promise((resolve, reject) => { - var fulfilled = (value) => { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - }; - var rejected = (value) => { - try { - step(generator.throw(value)); - } catch (e) { - reject(e); - } - }; - var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); - step((generator = generator.apply(__this, __arguments)).next()); - }); -}; -class BatchBlockService { - constructor({ - provider, - onProgress, - concurrencySize = 10, - batchSize = 10, - shouldRetry = true, - retryMax = 5, - retryOn = 500 - }) { - this.provider = provider; - this.onProgress = onProgress; - this.concurrencySize = concurrencySize; - this.batchSize = batchSize; - this.shouldRetry = shouldRetry; - this.retryMax = retryMax; - this.retryOn = retryOn; - } - getBlock(blockTag) { - return __async$9(this, null, function* () { - const blockObject = yield this.provider.getBlock(blockTag); - if (!blockObject) { - const errMsg = `No block for ${blockTag}`; - throw new Error(errMsg); - } - return blockObject; - }); - } - createBatchRequest(batchArray) { - return batchArray.map((blocks, index) => __async$9(this, null, function* () { - yield sleep(20 * index); - return (() => __async$9(this, null, function* () { - let retries = 0; - let err; - while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { - try { - return yield Promise.all(blocks.map((b) => this.getBlock(b))); - } catch (e) { - retries++; - err = e; - yield sleep(this.retryOn); - } - } - throw err; - }))(); - })); - } - getBatchBlocks(blocks) { - return __async$9(this, null, function* () { - let blockCount = 0; - const results = []; - for (const chunks of chunk(blocks, this.concurrencySize * this.batchSize)) { - const chunksResult = (yield Promise.all(this.createBatchRequest(chunk(chunks, this.batchSize)))).flat(); - results.push(...chunksResult); - blockCount += chunks.length; - if (typeof this.onProgress === "function") { - this.onProgress({ - percentage: blockCount / blocks.length, - currentIndex: blockCount, - totalIndex: blocks.length - }); - } - } - return results; - }); - } -} -class BatchTransactionService { - constructor({ - provider, - onProgress, - concurrencySize = 10, - batchSize = 10, - shouldRetry = true, - retryMax = 5, - retryOn = 500 - }) { - this.provider = provider; - this.onProgress = onProgress; - this.concurrencySize = concurrencySize; - this.batchSize = batchSize; - this.shouldRetry = shouldRetry; - this.retryMax = retryMax; - this.retryOn = retryOn; - } - getTransaction(txHash) { - return __async$9(this, null, function* () { - const txObject = yield this.provider.getTransaction(txHash); - if (!txObject) { - const errMsg = `No transaction for ${txHash}`; - throw new Error(errMsg); - } - return txObject; - }); - } - createBatchRequest(batchArray) { - return batchArray.map((txs, index) => __async$9(this, null, function* () { - yield sleep(20 * index); - return (() => __async$9(this, null, function* () { - let retries = 0; - let err; - while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { - try { - return yield Promise.all(txs.map((tx) => this.getTransaction(tx))); - } catch (e) { - retries++; - err = e; - yield sleep(this.retryOn); - } - } - throw err; - }))(); - })); - } - getBatchTransactions(txs) { - return __async$9(this, null, function* () { - let txCount = 0; - const results = []; - for (const chunks of chunk(txs, this.concurrencySize * this.batchSize)) { - const chunksResult = (yield Promise.all(this.createBatchRequest(chunk(chunks, this.batchSize)))).flat(); - results.push(...chunksResult); - txCount += chunks.length; - if (typeof this.onProgress === "function") { - this.onProgress({ percentage: txCount / txs.length, currentIndex: txCount, totalIndex: txs.length }); - } - } - return results; - }); - } -} -class BatchEventsService { - constructor({ - provider, - contract, - onProgress, - concurrencySize = 10, - blocksPerRequest = 2e3, - shouldRetry = true, - retryMax = 5, - retryOn = 500 - }) { - this.provider = provider; - this.contract = contract; - this.onProgress = onProgress; - this.concurrencySize = concurrencySize; - this.blocksPerRequest = blocksPerRequest; - this.shouldRetry = shouldRetry; - this.retryMax = retryMax; - this.retryOn = retryOn; - } - getPastEvents(_0) { - return __async$9(this, arguments, function* ({ fromBlock, toBlock, type }) { - let err; - let retries = 0; - while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { - try { - return yield this.contract.queryFilter(type, fromBlock, toBlock); - } catch (e) { - err = e; - retries++; - if (e.message.includes("after last accepted block")) { - const acceptedBlock = parseInt(e.message.split("after last accepted block ")[1]); - toBlock = acceptedBlock; - } - yield sleep(this.retryOn); - } - } - throw err; - }); - } - createBatchRequest(batchArray) { - return batchArray.map((event, index) => __async$9(this, null, function* () { - yield sleep(20 * index); - return this.getPastEvents(event); - })); - } - getBatchEvents(_0) { - return __async$9(this, arguments, function* ({ fromBlock, toBlock, type = "*" }) { - if (!toBlock) { - toBlock = yield this.provider.getBlockNumber(); - } - const eventsToSync = []; - for (let i = fromBlock; i < toBlock; i += this.blocksPerRequest) { - const j = i + this.blocksPerRequest - 1 > toBlock ? toBlock : i + this.blocksPerRequest - 1; - eventsToSync.push({ fromBlock: i, toBlock: j, type }); - } - const events = []; - const eventChunk = chunk(eventsToSync, this.concurrencySize); - let chunkCount = 0; - for (const chunk2 of eventChunk) { - chunkCount++; - const fetchedEvents = (yield Promise.all(this.createBatchRequest(chunk2))).flat(); - events.push(...fetchedEvents); - if (typeof this.onProgress === "function") { - this.onProgress({ - percentage: chunkCount / eventChunk.length, - type, - fromBlock: chunk2[0].fromBlock, - toBlock: chunk2[chunk2.length - 1].toBlock, - count: fetchedEvents.length - }); - } - } - return events; - }); - } -} - -var __defProp$2 = Object.defineProperty; -var __defProps$1 = Object.defineProperties; -var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors; -var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp$2 = Object.prototype.hasOwnProperty; -var __propIsEnum$2 = Object.prototype.propertyIsEnumerable; -var __reflectGet = Reflect.get; -var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __spreadValues$2 = (a, b) => { - for (var prop in b || (b = {})) - if (__hasOwnProp$2.call(b, prop)) - __defNormalProp$2(a, prop, b[prop]); - if (__getOwnPropSymbols$2) - for (var prop of __getOwnPropSymbols$2(b)) { - if (__propIsEnum$2.call(b, prop)) - __defNormalProp$2(a, prop, b[prop]); - } - return a; -}; -var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b)); -var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj); var __async$8 = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { @@ -4429,1307 +5394,18 @@ var __async$8 = (__this, __arguments, generator) => { step((generator = generator.apply(__this, __arguments)).next()); }); }; -const DEPOSIT = "deposit"; -const WITHDRAWAL = "withdrawal"; -class BaseEventsService { - constructor({ - netId, - provider, - graphApi, - subgraphName, - contract, - type = "", - deployedBlock = 0, - fetchDataOptions: fetchDataOptions2 - }) { - this.netId = netId; - this.provider = provider; - this.graphApi = graphApi; - this.subgraphName = subgraphName; - this.fetchDataOptions = fetchDataOptions2; - this.contract = contract; - this.type = type; - this.deployedBlock = deployedBlock; - this.batchEventsService = new BatchEventsService({ - provider, - contract, - onProgress: this.updateEventProgress - }); - } - getInstanceName() { - return ""; - } - getType() { - return this.type || ""; - } - getGraphMethod() { - return ""; - } - getGraphParams() { - return { - graphApi: this.graphApi || "", - subgraphName: this.subgraphName || "", - fetchDataOptions: this.fetchDataOptions, - onProgress: this.updateGraphProgress - }; - } - /* eslint-disable @typescript-eslint/no-unused-vars */ - updateEventProgress({ percentage, type, fromBlock, toBlock, count }) { - } - updateBlockProgress({ percentage, currentIndex, totalIndex }) { - } - updateTransactionProgress({ percentage, currentIndex, totalIndex }) { - } - updateGraphProgress({ type, fromBlock, toBlock, count }) { - } - /* eslint-enable @typescript-eslint/no-unused-vars */ - formatEvents(events) { - return __async$8(this, null, function* () { - return yield new Promise((resolve) => resolve(events)); - }); - } - /** - * Get saved or cached events - */ - getEventsFromDB() { - return __async$8(this, null, function* () { - return { - events: [], - lastBlock: null - }; - }); - } - getEventsFromCache() { - return __async$8(this, null, function* () { - return { - events: [], - lastBlock: null - }; - }); - } - getSavedEvents() { - return __async$8(this, null, function* () { - let cachedEvents = yield this.getEventsFromDB(); - if (!cachedEvents || !cachedEvents.events.length) { - cachedEvents = yield this.getEventsFromCache(); - } - return cachedEvents; - }); - } - /** - * Get latest events - */ - getEventsFromGraph(_0) { - return __async$8(this, arguments, function* ({ - fromBlock, - methodName = "" - }) { - if (!this.graphApi || !this.subgraphName) { - return { - events: [], - lastBlock: fromBlock - }; - } - const { events, lastSyncBlock } = yield graph[methodName || this.getGraphMethod()](__spreadValues$2({ - fromBlock - }, this.getGraphParams())); - return { - events, - lastBlock: lastSyncBlock - }; - }); - } - getEventsFromRpc(_0) { - return __async$8(this, arguments, function* ({ - fromBlock, - toBlock - }) { - try { - if (!toBlock) { - toBlock = yield this.provider.getBlockNumber(); - } - if (fromBlock >= toBlock) { - return { - events: [], - lastBlock: toBlock - }; - } - this.updateEventProgress({ percentage: 0, type: this.getType() }); - const events = yield this.formatEvents( - yield this.batchEventsService.getBatchEvents({ fromBlock, toBlock, type: this.getType() }) - ); - if (!events.length) { - return { - events, - lastBlock: toBlock - }; - } - return { - events, - lastBlock: toBlock - }; - } catch (err) { - console.log(err); - return { - events: [], - lastBlock: fromBlock - }; - } - }); - } - getLatestEvents(_0) { - return __async$8(this, arguments, function* ({ fromBlock }) { - const allEvents = []; - const graphEvents = yield this.getEventsFromGraph({ fromBlock }); - const lastSyncBlock = graphEvents.lastBlock && graphEvents.lastBlock >= fromBlock ? graphEvents.lastBlock : fromBlock; - const rpcEvents = yield this.getEventsFromRpc({ fromBlock: lastSyncBlock }); - allEvents.push(...graphEvents.events); - allEvents.push(...rpcEvents.events); - const lastBlock = rpcEvents ? rpcEvents.lastBlock : allEvents[allEvents.length - 1] ? allEvents[allEvents.length - 1].blockNumber : fromBlock; - return { - events: allEvents, - lastBlock - }; - }); - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - validateEvents({ events, lastBlock }) { - } - /** - * Handle saving events - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - saveEvents(_0) { - return __async$8(this, arguments, function* ({ events, lastBlock }) { - }); - } - /** - * Trigger saving and receiving latest events - */ - updateEvents() { - return __async$8(this, null, function* () { - const savedEvents = yield this.getSavedEvents(); - let fromBlock = this.deployedBlock; - if (savedEvents && savedEvents.lastBlock) { - fromBlock = savedEvents.lastBlock + 1; - } - const newEvents = yield this.getLatestEvents({ fromBlock }); - const eventSet = /* @__PURE__ */ new Set(); - let allEvents = []; - allEvents.push(...savedEvents.events); - allEvents.push(...newEvents.events); - allEvents = allEvents.sort((a, b) => { - if (a.blockNumber === b.blockNumber) { - return a.logIndex - b.logIndex; - } - return a.blockNumber - b.blockNumber; - }).filter(({ transactionHash, logIndex }) => { - const eventKey = `${transactionHash}_${logIndex}`; - const hasEvent = eventSet.has(eventKey); - eventSet.add(eventKey); - return !hasEvent; - }); - const lastBlock = newEvents ? newEvents.lastBlock : allEvents[allEvents.length - 1] ? allEvents[allEvents.length - 1].blockNumber : null; - this.validateEvents({ events: allEvents, lastBlock }); - this.saveEventsPromise = this.saveEvents({ events: allEvents, lastBlock }); - return { - events: allEvents, - lastBlock - }; - }); - } -} -class BaseTornadoService extends BaseEventsService { - constructor({ - netId, - provider, - graphApi, - subgraphName, - Tornado, - type, - amount, - currency, - deployedBlock, - fetchDataOptions: fetchDataOptions2 - }) { - super({ netId, provider, graphApi, subgraphName, contract: Tornado, type, deployedBlock, fetchDataOptions: fetchDataOptions2 }); - this.amount = amount; - this.currency = currency; - this.batchTransactionService = new BatchTransactionService({ - provider, - onProgress: this.updateTransactionProgress - }); - this.batchBlockService = new BatchBlockService({ - provider, - onProgress: this.updateBlockProgress - }); - } - getInstanceName() { - return `${this.getType().toLowerCase()}s_${this.netId}_${this.currency}_${this.amount}`; - } - getGraphMethod() { - return `getAll${this.getType()}s`; - } - getGraphParams() { - return { - graphApi: this.graphApi || "", - subgraphName: this.subgraphName || "", - amount: this.amount, - currency: this.currency, - fetchDataOptions: this.fetchDataOptions, - onProgress: this.updateGraphProgress - }; - } - formatEvents(events) { - return __async$8(this, null, function* () { - const type = this.getType().toLowerCase(); - if (type === DEPOSIT) { - const formattedEvents = events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { - const { commitment, leafIndex, timestamp } = args; - return { - blockNumber, - logIndex, - transactionHash, - commitment, - leafIndex: Number(leafIndex), - timestamp: Number(timestamp) - }; - }); - const txs = yield this.batchTransactionService.getBatchTransactions([ - ...new Set(formattedEvents.map(({ transactionHash }) => transactionHash)) - ]); - return formattedEvents.map((event) => { - const { from } = txs.find(({ hash }) => hash === event.transactionHash); - return __spreadProps$1(__spreadValues$2({}, event), { - from - }); - }); - } else { - const formattedEvents = events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { - const { nullifierHash, to, fee } = args; - return { - blockNumber, - logIndex, - transactionHash, - nullifierHash: String(nullifierHash), - to: ethers.getAddress(to), - fee: String(fee) - }; - }); - const blocks = yield this.batchBlockService.getBatchBlocks([ - ...new Set(formattedEvents.map(({ blockNumber }) => blockNumber)) - ]); - return formattedEvents.map((event) => { - const { timestamp } = blocks.find(({ number }) => number === event.blockNumber); - return __spreadProps$1(__spreadValues$2({}, event), { - timestamp - }); - }); - } - }); - } - validateEvents({ events }) { - if (events.length && this.getType().toLowerCase() === DEPOSIT) { - const lastEvent = events[events.length - 1]; - if (lastEvent.leafIndex !== events.length - 1) { - const errMsg = `Deposit events invalid wants ${events.length - 1} leafIndex have ${lastEvent.leafIndex}`; - throw new Error(errMsg); - } - } - } -} -class BaseEchoService extends BaseEventsService { - constructor({ - netId, - provider, - graphApi, - subgraphName, - Echoer, - deployedBlock, - fetchDataOptions: fetchDataOptions2 - }) { - super({ netId, provider, graphApi, subgraphName, contract: Echoer, deployedBlock, fetchDataOptions: fetchDataOptions2 }); - } - getInstanceName() { - return `echo_${this.netId}`; - } - getType() { - return "Echo"; - } - getGraphMethod() { - return "getAllGraphEchoEvents"; - } - formatEvents(events) { - return __async$8(this, null, function* () { - return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { - const { who, data } = args; - if (who && data) { - const eventObjects = { - blockNumber, - logIndex, - transactionHash - }; - return __spreadProps$1(__spreadValues$2({}, eventObjects), { - address: who, - encryptedAccount: data - }); - } - }).filter((e) => e); - }); - } - getEventsFromGraph(_0) { - return __async$8(this, arguments, function* ({ fromBlock }) { - if (!this.graphApi || this.graphApi.includes("api.thegraph.com")) { - return { - events: [], - lastBlock: fromBlock - }; - } - return __superGet(BaseEchoService.prototype, this, "getEventsFromGraph").call(this, { fromBlock }); - }); - } -} -class BaseEncryptedNotesService extends BaseEventsService { - constructor({ - netId, - provider, - graphApi, - subgraphName, - Router, - deployedBlock, - fetchDataOptions: fetchDataOptions2 - }) { - super({ netId, provider, graphApi, subgraphName, contract: Router, deployedBlock, fetchDataOptions: fetchDataOptions2 }); - } - getInstanceName() { - return `encrypted_notes_${this.netId}`; - } - getType() { - return "EncryptedNote"; - } - getGraphMethod() { - return "getAllEncryptedNotes"; - } - formatEvents(events) { - return __async$8(this, null, function* () { - return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { - const { encryptedNote } = args; - if (encryptedNote) { - const eventObjects = { - blockNumber, - logIndex, - transactionHash - }; - return __spreadProps$1(__spreadValues$2({}, eventObjects), { - encryptedNote - }); - } - }).filter((e) => e); - }); - } -} -class BaseGovernanceService extends BaseEventsService { - constructor({ - netId, - provider, - graphApi, - subgraphName, - Governance, - deployedBlock, - fetchDataOptions: fetchDataOptions2 - }) { - super({ netId, provider, graphApi, subgraphName, contract: Governance, deployedBlock, fetchDataOptions: fetchDataOptions2 }); - this.batchTransactionService = new BatchTransactionService({ - provider, - onProgress: this.updateTransactionProgress - }); - } - getInstanceName() { - return `governance_${this.netId}`; - } - getType() { - return "*"; - } - getGraphMethod() { - return "getAllGovernanceEvents"; - } - formatEvents(events) { - return __async$8(this, null, function* () { - const proposalEvents = []; - const votedEvents = []; - const delegatedEvents = []; - const undelegatedEvents = []; - events.forEach(({ blockNumber, index: logIndex, transactionHash, args, eventName: event }) => { - const eventObjects = { - blockNumber, - logIndex, - transactionHash, - event - }; - if (event === "ProposalCreated") { - const { id, proposer, target, startTime, endTime, description } = args; - proposalEvents.push(__spreadProps$1(__spreadValues$2({}, eventObjects), { - id: Number(id), - proposer, - target, - startTime: Number(startTime), - endTime: Number(endTime), - description - })); - } - if (event === "Voted") { - const { proposalId, voter, support, votes } = args; - votedEvents.push(__spreadProps$1(__spreadValues$2({}, eventObjects), { - proposalId: Number(proposalId), - voter, - support, - votes, - from: "", - input: "" - })); - } - if (event === "Delegated") { - const { account, to: delegateTo } = args; - delegatedEvents.push(__spreadProps$1(__spreadValues$2({}, eventObjects), { - account, - delegateTo - })); - } - if (event === "Undelegated") { - const { account, from: delegateFrom } = args; - undelegatedEvents.push(__spreadProps$1(__spreadValues$2({}, eventObjects), { - account, - delegateFrom - })); - } - }); - if (votedEvents.length) { - this.updateTransactionProgress({ percentage: 0 }); - const txs = yield this.batchTransactionService.getBatchTransactions([ - ...new Set(votedEvents.map(({ transactionHash }) => transactionHash)) - ]); - votedEvents.forEach((event, index) => { - let { data: input, from } = txs.find((t) => t.hash === event.transactionHash); - if (!input || input.length > 2048) { - input = ""; - } - votedEvents[index].from = from; - votedEvents[index].input = input; - }); - } - return [...proposalEvents, ...votedEvents, ...delegatedEvents, ...undelegatedEvents]; - }); - } - getEventsFromGraph(_0) { - return __async$8(this, arguments, function* ({ fromBlock }) { - if (!this.graphApi || !this.subgraphName || this.graphApi.includes("api.thegraph.com")) { - return { - events: [], - lastBlock: fromBlock - }; - } - return __superGet(BaseGovernanceService.prototype, this, "getEventsFromGraph").call(this, { fromBlock }); - }); - } -} -class BaseRegistryService extends BaseEventsService { - constructor({ - netId, - provider, - graphApi, - subgraphName, - RelayerRegistry, - deployedBlock, - fetchDataOptions: fetchDataOptions2 - }) { - super({ netId, provider, graphApi, subgraphName, contract: RelayerRegistry, deployedBlock, fetchDataOptions: fetchDataOptions2 }); - } - getInstanceName() { - return `registered_${this.netId}`; - } - // Name of type used for events - getType() { - return "RelayerRegistered"; - } - // Name of method used for graph - getGraphMethod() { - return "getAllRegisters"; - } - formatEvents(events) { - return __async$8(this, null, function* () { - return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { - const eventObjects = { - blockNumber, - logIndex, - transactionHash - }; - return __spreadProps$1(__spreadValues$2({}, eventObjects), { - ensName: args.ensName, - relayerAddress: args.relayerAddress - }); - }); - }); - } - fetchRelayers() { - return __async$8(this, null, function* () { - return (yield this.updateEvents()).events; - }); - } -} - -var __defProp$1 = Object.defineProperty; -var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols; -var __hasOwnProp$1 = Object.prototype.hasOwnProperty; -var __propIsEnum$1 = Object.prototype.propertyIsEnumerable; -var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __spreadValues$1 = (a, b) => { - for (var prop in b || (b = {})) - if (__hasOwnProp$1.call(b, prop)) - __defNormalProp$1(a, prop, b[prop]); - if (__getOwnPropSymbols$1) - for (var prop of __getOwnPropSymbols$1(b)) { - if (__propIsEnum$1.call(b, prop)) - __defNormalProp$1(a, prop, b[prop]); - } - return a; -}; -var NetId = /* @__PURE__ */ ((NetId2) => { - NetId2[NetId2["MAINNET"] = 1] = "MAINNET"; - NetId2[NetId2["BSC"] = 56] = "BSC"; - NetId2[NetId2["POLYGON"] = 137] = "POLYGON"; - NetId2[NetId2["OPTIMISM"] = 10] = "OPTIMISM"; - NetId2[NetId2["ARBITRUM"] = 42161] = "ARBITRUM"; - NetId2[NetId2["GNOSIS"] = 100] = "GNOSIS"; - NetId2[NetId2["AVALANCHE"] = 43114] = "AVALANCHE"; - NetId2[NetId2["SEPOLIA"] = 11155111] = "SEPOLIA"; - return NetId2; -})(NetId || {}); -const theGraph = { - name: "Hosted Graph", - url: "https://api.thegraph.com" -}; -const tornado = { - name: "Tornado Subgraphs", - url: "https://tornadocash-rpc.com" -}; -const defaultConfig = { - [1 /* MAINNET */]: { - rpcCallRetryAttempt: 15, - gasPrices: { - instant: 80, - fast: 50, - standard: 25, - low: 8 - }, - nativeCurrency: "eth", - currencyName: "ETH", - explorerUrl: "https://etherscan.io", - merkleTreeHeight: 20, - emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", - networkName: "Ethereum Mainnet", - deployedBlock: 9116966, - rpcUrls: { - tornadoRPC: { - name: "Tornado RPC", - url: "https://tornadocash-rpc.com/mainnet" - }, - mevblockerRPC: { - name: "MevblockerRPC", - url: "https://rpc.mevblocker.io" - }, - oneRPC: { - name: "1RPC", - url: "https://1rpc.io/eth" - } - }, - multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", - routerContract: "0xd90e2f925DA726b50C4Ed8D0Fb90Ad053324F31b", - echoContract: "0x9B27DD5Bb15d42DC224FCD0B7caEbBe16161Df42", - offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", - tornContract: "0x77777FeDdddFfC19Ff86DB637967013e6C6A116C", - governanceContract: "0x5efda50f22d34F262c29268506C5Fa42cB56A1Ce", - stakingRewardsContract: "0x5B3f656C80E8ddb9ec01Dd9018815576E9238c29", - registryContract: "0x58E8dCC13BE9780fC42E8723D8EaD4CF46943dF2", - aggregatorContract: "0xE8F47A78A6D52D317D0D2FFFac56739fE14D1b49", - reverseRecordsContract: "0x3671aE578E63FdF66ad4F3E12CC0c0d71Ac7510C", - tornadoSubgraph: "tornadocash/mainnet-tornado-subgraph", - registrySubgraph: "tornadocash/tornado-relayer-registry", - governanceSubgraph: "tornadocash/tornado-governance", - subgraphs: { - tornado, - theGraph - }, - tokens: { - eth: { - instanceAddress: { - "0.1": "0x12D66f87A04A9E220743712cE6d9bB1B5616B8Fc", - "1": "0x47CE0C6eD5B0Ce3d3A51fdb1C52DC66a7c3c2936", - "10": "0x910Cbd523D972eb0a6f4cAe4618aD62622b39DbF", - "100": "0xA160cdAB225685dA1d56aa342Ad8841c3b53f291" - }, - symbol: "ETH", - decimals: 18 - }, - dai: { - instanceAddress: { - "100": "0xD4B88Df4D29F5CedD6857912842cff3b20C8Cfa3", - "1000": "0xFD8610d20aA15b7B2E3Be39B396a1bC3516c7144", - "10000": "0x07687e702b410Fa43f4cB4Af7FA097918ffD2730", - "100000": "0x23773E65ed146A459791799d01336DB287f25334" - }, - tokenAddress: "0x6B175474E89094C44Da98b954EedeAC495271d0F", - tokenGasLimit: 7e4, - symbol: "DAI", - decimals: 18, - gasLimit: 7e5 - }, - cdai: { - instanceAddress: { - "5000": "0x22aaA7720ddd5388A3c0A3333430953C68f1849b", - "50000": "0x03893a7c7463AE47D46bc7f091665f1893656003", - "500000": "0x2717c5e28cf931547B621a5dddb772Ab6A35B701", - "5000000": "0xD21be7248e0197Ee08E0c20D4a96DEBdaC3D20Af" - }, - tokenAddress: "0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643", - tokenGasLimit: 2e5, - symbol: "cDAI", - decimals: 8, - gasLimit: 7e5 - }, - usdc: { - instanceAddress: { - "100": "0xd96f2B1c14Db8458374d9Aca76E26c3D18364307", - "1000": "0x4736dCf1b7A3d580672CcE6E7c65cd5cc9cFBa9D" - }, - tokenAddress: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", - tokenGasLimit: 7e4, - symbol: "USDC", - decimals: 6, - gasLimit: 7e5 - }, - usdt: { - instanceAddress: { - "100": "0x169AD27A470D064DEDE56a2D3ff727986b15D52B", - "1000": "0x0836222F2B2B24A3F36f98668Ed8F0B38D1a872f" - }, - tokenAddress: "0xdAC17F958D2ee523a2206206994597C13D831ec7", - tokenGasLimit: 7e4, - symbol: "USDT", - decimals: 6, - gasLimit: 7e5 - }, - wbtc: { - instanceAddress: { - "0.1": "0x178169B423a011fff22B9e3F3abeA13414dDD0F1", - "1": "0x610B717796ad172B316836AC95a2ffad065CeaB4", - "10": "0xbB93e510BbCD0B7beb5A853875f9eC60275CF498" - }, - tokenAddress: "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599", - tokenGasLimit: 7e4, - symbol: "WBTC", - decimals: 8, - gasLimit: 7e5 - } - }, - relayerEnsSubdomain: "mainnet-tornado", - pollInterval: 15, - constants: { - GOVERNANCE_BLOCK: 11474695, - NOTE_ACCOUNT_BLOCK: 11842486, - ENCRYPTED_NOTES_BLOCK: 12143762, - REGISTRY_BLOCK: 14173129, - MINING_BLOCK_TIME: 15 - } - }, - [56 /* BSC */]: { - rpcCallRetryAttempt: 15, - gasPrices: { - instant: 5, - fast: 5, - standard: 5, - low: 5 - }, - nativeCurrency: "bnb", - currencyName: "BNB", - explorerUrl: "https://bscscan.com", - merkleTreeHeight: 20, - emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", - networkName: "Binance Smart Chain", - deployedBlock: 8158799, - multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", - routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", - echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", - offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", - tornadoSubgraph: "tornadocash/bsc-tornado-subgraph", - subgraphs: { - tornado, - theGraph - }, - rpcUrls: { - tornadoRPC: { - name: "Tornado RPC", - url: "https://tornadocash-rpc.com/bsc" - }, - oneRPC: { - name: "1RPC", - url: "https://1rpc.io/bnb" - } - }, - tokens: { - bnb: { - instanceAddress: { - "0.1": "0x84443CFd09A48AF6eF360C6976C5392aC5023a1F", - "1": "0xd47438C816c9E7f2E2888E060936a499Af9582b3", - "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", - "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD" - }, - symbol: "BNB", - decimals: 18 - } - }, - relayerEnsSubdomain: "bsc-tornado", - pollInterval: 10, - constants: { - NOTE_ACCOUNT_BLOCK: 8159269, - ENCRYPTED_NOTES_BLOCK: 8159269 - } - }, - [137 /* POLYGON */]: { - rpcCallRetryAttempt: 15, - gasPrices: { - instant: 100, - fast: 75, - standard: 50, - low: 30 - }, - nativeCurrency: "matic", - currencyName: "MATIC", - explorerUrl: "https://polygonscan.com", - merkleTreeHeight: 20, - emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", - networkName: "Polygon (Matic) Network", - deployedBlock: 16257962, - multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", - routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", - echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", - offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", - gasPriceOracleContract: "0xF81A8D8D3581985D3969fe53bFA67074aDFa8F3C", - tornadoSubgraph: "tornadocash/matic-tornado-subgraph", - subgraphs: { - tornado, - theGraph - }, - rpcUrls: { - oneRpc: { - name: "1RPC", - url: "https://1rpc.io/matic" - } - }, - tokens: { - matic: { - instanceAddress: { - "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD", - "1000": "0xdf231d99Ff8b6c6CBF4E9B9a945CBAcEF9339178", - "10000": "0xaf4c0B70B2Ea9FB7487C7CbB37aDa259579fe040", - "100000": "0xa5C2254e4253490C54cef0a4347fddb8f75A4998" - }, - symbol: "MATIC", - decimals: 18 - } - }, - relayerEnsSubdomain: "polygon-tornado", - pollInterval: 10, - constants: { - NOTE_ACCOUNT_BLOCK: 16257996, - ENCRYPTED_NOTES_BLOCK: 16257996 - } - }, - [10 /* OPTIMISM */]: { - rpcCallRetryAttempt: 15, - gasPrices: { - instant: 1e-3, - fast: 1e-3, - standard: 1e-3, - low: 1e-3 - }, - nativeCurrency: "eth", - currencyName: "ETH", - explorerUrl: "https://optimistic.etherscan.io", - merkleTreeHeight: 20, - emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", - networkName: "Optimism", - deployedBlock: 2243689, - multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", - routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", - echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", - offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", - ovmGasPriceOracleContract: "0x420000000000000000000000000000000000000F", - tornadoSubgraph: "tornadocash/optimism-tornado-subgraph", - subgraphs: { - tornado, - theGraph - }, - rpcUrls: { - tornadoRPC: { - name: "Tornado RPC", - url: "https://tornadocash-rpc.com/op" - }, - oneRpc: { - name: "1RPC", - url: "https://1rpc.io/op" - } - }, - tokens: { - eth: { - instanceAddress: { - "0.1": "0x84443CFd09A48AF6eF360C6976C5392aC5023a1F", - "1": "0xd47438C816c9E7f2E2888E060936a499Af9582b3", - "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", - "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD" - }, - symbol: "ETH", - decimals: 18 - } - }, - relayerEnsSubdomain: "optimism-tornado", - pollInterval: 15, - constants: { - NOTE_ACCOUNT_BLOCK: 2243694, - ENCRYPTED_NOTES_BLOCK: 2243694 - } - }, - [42161 /* ARBITRUM */]: { - rpcCallRetryAttempt: 15, - gasPrices: { - instant: 4, - fast: 3, - standard: 2.52, - low: 2.29 - }, - nativeCurrency: "eth", - currencyName: "ETH", - explorerUrl: "https://arbiscan.io", - merkleTreeHeight: 20, - emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", - networkName: "Arbitrum One", - deployedBlock: 3430648, - multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", - routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", - echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", - offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", - tornadoSubgraph: "tornadocash/arbitrum-tornado-subgraph", - subgraphs: { - tornado, - theGraph - }, - rpcUrls: { - oneRpc: { - name: "1rpc", - url: "https://1rpc.io/arb" - }, - Arbitrum: { - name: "Arbitrum RPC", - url: "https://arb1.arbitrum.io/rpc" - } - }, - tokens: { - eth: { - instanceAddress: { - "0.1": "0x84443CFd09A48AF6eF360C6976C5392aC5023a1F", - "1": "0xd47438C816c9E7f2E2888E060936a499Af9582b3", - "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", - "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD" - }, - symbol: "ETH", - decimals: 18 - } - }, - relayerEnsSubdomain: "arbitrum-tornado", - pollInterval: 15, - constants: { - NOTE_ACCOUNT_BLOCK: 3430605, - ENCRYPTED_NOTES_BLOCK: 3430605 - } - }, - [100 /* GNOSIS */]: { - rpcCallRetryAttempt: 15, - gasPrices: { - instant: 6, - fast: 5, - standard: 4, - low: 1 - }, - nativeCurrency: "xdai", - currencyName: "xDAI", - explorerUrl: "https://gnosisscan.io", - merkleTreeHeight: 20, - emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", - networkName: "Gnosis Chain", - deployedBlock: 17754561, - multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", - routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", - echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", - offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", - tornadoSubgraph: "tornadocash/xdai-tornado-subgraph", - subgraphs: { - tornado, - theGraph - }, - rpcUrls: { - tornadoRPC: { - name: "Tornado RPC", - url: "https://tornadocash-rpc.com/gnosis" - }, - blockPi: { - name: "BlockPi", - url: "https://gnosis.blockpi.network/v1/rpc/public" - } - }, - tokens: { - xdai: { - instanceAddress: { - "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD", - "1000": "0xdf231d99Ff8b6c6CBF4E9B9a945CBAcEF9339178", - "10000": "0xaf4c0B70B2Ea9FB7487C7CbB37aDa259579fe040", - "100000": "0xa5C2254e4253490C54cef0a4347fddb8f75A4998" - }, - symbol: "xDAI", - decimals: 18 - } - }, - relayerEnsSubdomain: "gnosis-tornado", - pollInterval: 15, - constants: { - NOTE_ACCOUNT_BLOCK: 17754564, - ENCRYPTED_NOTES_BLOCK: 17754564 - } - }, - [43114 /* AVALANCHE */]: { - rpcCallRetryAttempt: 15, - gasPrices: { - instant: 225, - fast: 35, - standard: 25, - low: 25 - }, - nativeCurrency: "avax", - currencyName: "AVAX", - explorerUrl: "https://snowtrace.io", - merkleTreeHeight: 20, - emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", - networkName: "Avalanche Mainnet", - deployedBlock: 4429818, - multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", - routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", - echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", - offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", - tornadoSubgraph: "tornadocash/avalanche-tornado-subgraph", - subgraphs: { - theGraph - }, - rpcUrls: { - publicRpc: { - name: "Avalanche RPC", - url: "https://api.avax.network/ext/bc/C/rpc" - }, - meowRPC: { - name: "Meow RPC", - url: "https://avax.meowrpc.com" - }, - oneRPC: { - name: "OneRPC", - url: "https://1rpc.io/avax/c" - } - }, - tokens: { - avax: { - instanceAddress: { - "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", - "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD", - "500": "0xaf8d1839c3c67cf571aa74B5c12398d4901147B3" - }, - symbol: "AVAX", - decimals: 18 - } - }, - relayerEnsSubdomain: "avalanche-tornado", - pollInterval: 10, - constants: { - NOTE_ACCOUNT_BLOCK: 4429813, - ENCRYPTED_NOTES_BLOCK: 4429813 - } - }, - [11155111 /* SEPOLIA */]: { - rpcCallRetryAttempt: 15, - gasPrices: { - instant: 2, - fast: 2, - standard: 2, - low: 2 - }, - nativeCurrency: "eth", - currencyName: "SepoliaETH", - explorerUrl: "https://sepolia.etherscan.io", - merkleTreeHeight: 20, - emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", - networkName: "Ethereum Sepolia", - deployedBlock: 5594395, - multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", - routerContract: "0x1572AFE6949fdF51Cb3E0856216670ae9Ee160Ee", - echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", - tornContract: "0x3AE6667167C0f44394106E197904519D808323cA", - governanceContract: "0xe5324cD7602eeb387418e594B87aCADee08aeCAD", - stakingRewardsContract: "0x6d0018890751Efd31feb8166711B16732E2b496b", - registryContract: "0x1428e5d2356b13778A13108b10c440C83011dfB8", - aggregatorContract: "0x4088712AC9fad39ea133cdb9130E465d235e9642", - reverseRecordsContract: "0xEc29700C0283e5Be64AcdFe8077d6cC95dE23C23", - tornadoSubgraph: "tornadocash/sepolia-tornado-subgraph", - subgraphs: { - tornado - }, - rpcUrls: { - tornadoRPC: { - name: "Tornado RPC", - url: "https://tornadocash-rpc.com/sepolia" - }, - sepolia: { - name: "Sepolia RPC", - url: "https://rpc.sepolia.org" - } - }, - tokens: { - eth: { - instanceAddress: { - "0.1": "0x8C4A04d872a6C1BE37964A21ba3a138525dFF50b", - "1": "0x8cc930096B4Df705A007c4A039BDFA1320Ed2508", - "10": "0x8D10d506D29Fc62ABb8A290B99F66dB27Fc43585", - "100": "0x44c5C92ed73dB43888210264f0C8b36Fd68D8379" - }, - symbol: "ETH", - decimals: 18 - }, - dai: { - instanceAddress: { - "100": "0x6921fd1a97441dd603a997ED6DDF388658daf754", - "1000": "0x50a637770F5d161999420F7d70d888DE47207145", - "10000": "0xecD649870407cD43923A816Cc6334a5bdf113621", - "100000": "0x73B4BD04bF83206B6e979BE2507098F92EDf4F90" - }, - tokenAddress: "0xFF34B3d4Aee8ddCd6F9AFFFB6Fe49bD371b8a357", - tokenGasLimit: 7e4, - symbol: "DAI", - decimals: 18, - gasLimit: 7e5 - } - }, - relayerEnsSubdomain: "sepolia-tornado", - pollInterval: 15, - constants: { - GOVERNANCE_BLOCK: 5594395, - NOTE_ACCOUNT_BLOCK: 5594395, - ENCRYPTED_NOTES_BLOCK: 5594395, - MINING_BLOCK_TIME: 15 - } - } -}; -const enabledChains = Object.values(NetId).filter((n) => typeof n === "number"); -exports.customConfig = {}; -function addNetwork(newConfig) { - enabledChains.push( - ...Object.keys(newConfig).map((netId) => Number(netId)).filter((netId) => !enabledChains.includes(netId)) - ); - exports.customConfig = __spreadValues$1(__spreadValues$1({}, exports.customConfig), newConfig); -} -function getNetworkConfig() { - const allConfig = __spreadValues$1(__spreadValues$1({}, defaultConfig), exports.customConfig); - return enabledChains.reduce((acc, curr) => { - acc[curr] = allConfig[curr]; - return acc; - }, {}); -} -function getConfig(netId) { - const allConfig = getNetworkConfig(); - const chainConfig = allConfig[netId]; - if (!chainConfig) { - const errMsg = `No config found for network ${netId}!`; - throw new Error(errMsg); - } - return chainConfig; -} -function getInstanceByAddress({ netId, address }) { - const { tokens } = getConfig(netId); - for (const [currency, { instanceAddress }] of Object.entries(tokens)) { - for (const [amount, instance] of Object.entries(instanceAddress)) { - if (instance === address) { - return { - amount, - currency - }; - } - } - } -} -function getSubdomains() { - const allConfig = getNetworkConfig(); - return enabledChains.map((chain) => allConfig[chain].relayerEnsSubdomain); -} - -const addressType = { type: "string", pattern: "^0x[a-fA-F0-9]{40}$" }; -const bnType = { type: "string", BN: true }; -const statusSchema = { - type: "object", - properties: { - rewardAccount: addressType, - gasPrices: { - type: "object", - properties: { - fast: { type: "number" }, - additionalProperties: { type: "number" } - }, - required: ["fast"] - }, - netId: { type: "integer" }, - tornadoServiceFee: { type: "number", maximum: 20, minimum: 0 }, - latestBlock: { type: "number" }, - version: { type: "string" }, - health: { - type: "object", - properties: { - status: { const: "true" }, - error: { type: "string" } - }, - required: ["status"] - }, - currentQueue: { type: "number" } - }, - required: ["rewardAccount", "instances", "netId", "tornadoServiceFee", "version", "health"] -}; -function getStatusSchema(netId, config) { - const { tokens, optionalTokens = [], nativeCurrency } = config; - const schema = JSON.parse(JSON.stringify(statusSchema)); - const instances = Object.keys(tokens).reduce( - (acc, token) => { - const { instanceAddress, tokenAddress, symbol, decimals, optionalInstances = [] } = tokens[token]; - const amounts = Object.keys(instanceAddress); - const instanceProperties = { - type: "object", - properties: { - instanceAddress: { - type: "object", - properties: amounts.reduce((acc2, cur) => { - acc2[cur] = addressType; - return acc2; - }, {}), - required: amounts.filter((amount) => !optionalInstances.includes(amount)) - }, - decimals: { enum: [decimals] } - }, - required: ["instanceAddress", "decimals"].concat( - tokenAddress ? ["tokenAddress"] : [], - symbol ? ["symbol"] : [] - ) - }; - if (tokenAddress) { - instanceProperties.properties.tokenAddress = addressType; - } - if (symbol) { - instanceProperties.properties.symbol = { enum: [symbol] }; - } - acc.properties[token] = instanceProperties; - if (!optionalTokens.includes(token)) { - acc.required.push(token); - } - return acc; - }, - { - type: "object", - properties: {}, - required: [] - } - ); - schema.properties.instances = instances; - if (netId === NetId.MAINNET) { - const _tokens = Object.keys(tokens).filter((t) => t !== nativeCurrency); - const ethPrices = { - type: "object", - properties: _tokens.reduce((acc, token) => { - acc[token] = bnType; - return acc; - }, {}) - // required: _tokens - }; - schema.properties.ethPrices = ethPrices; - } - return schema; -} - -const jobsSchema = { - type: "object", - properties: { - error: { type: "string" }, - id: { type: "string" }, - type: { type: "string" }, - status: { type: "string" }, - contract: { type: "string" }, - proof: { type: "string" }, - args: { - type: "array", - items: { type: "string" } - }, - txHash: { type: "string" }, - confirmations: { type: "number" }, - failedReason: { type: "string" } - }, - required: ["id", "status"] -}; - -const ajv = new Ajv({ allErrors: true }); -ajv.addKeyword({ - keyword: "BN", - // eslint-disable-next-line @typescript-eslint/no-explicit-any - validate: (schema, data) => { - try { - BigInt(data); - return true; - } catch (e) { - return false; - } - }, - errors: true -}); - -var __async$7 = (__this, __arguments, generator) => { - return new Promise((resolve, reject) => { - var fulfilled = (value) => { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - }; - var rejected = (value) => { - try { - step(generator.throw(value)); - } catch (e) { - reject(e); - } - }; - var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); - step((generator = generator.apply(__this, __arguments)).next()); - }); -}; class Pedersen { constructor() { this.pedersenPromise = this.initPedersen(); } initPedersen() { - return __async$7(this, null, function* () { + return __async$8(this, null, function* () { this.pedersenHash = yield circomlibjs.buildPedersenHash(); this.babyJub = this.pedersenHash.babyJub; }); } unpackPoint(buffer) { - return __async$7(this, null, function* () { + return __async$8(this, null, function* () { var _a, _b; yield this.pedersenPromise; return (_b = this.babyJub) == null ? void 0 : _b.unpackPoint((_a = this.pedersenHash) == null ? void 0 : _a.hash(buffer)); @@ -5742,13 +5418,13 @@ class Pedersen { } const pedersen = new Pedersen(); function buffPedersenHash(buffer) { - return __async$7(this, null, function* () { + return __async$8(this, null, function* () { const [hash] = yield pedersen.unpackPoint(buffer); return pedersen.toStringBuffer(hash); }); } -var __async$6 = (__this, __arguments, generator) => { +var __async$7 = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { @@ -5769,7 +5445,7 @@ var __async$6 = (__this, __arguments, generator) => { }); }; function createDeposit(_0) { - return __async$6(this, arguments, function* ({ nullifier, secret }) { + return __async$7(this, arguments, function* ({ nullifier, secret }) { const preimage = new Uint8Array([...leInt2Buff(nullifier), ...leInt2Buff(secret)]); const noteHex = toFixedHex(bytesToBN(preimage), 62); const commitment = BigInt(yield buffPedersenHash(preimage)); @@ -5829,7 +5505,7 @@ class Deposit { ); } static createNote(_0) { - return __async$6(this, arguments, function* ({ currency, amount, netId, nullifier, secret }) { + return __async$7(this, arguments, function* ({ currency, amount, netId, nullifier, secret }) { if (!nullifier) { nullifier = rBigInt(31); } @@ -5856,7 +5532,7 @@ class Deposit { }); } static parseNote(noteString) { - return __async$6(this, null, function* () { + return __async$7(this, null, function* () { const noteRegex = new RegExp("tornado-(?\\w+)-(?[\\d.]+)-(?\\d+)-0x(?[0-9a-fA-F]{124})", "g"); const match = noteRegex.exec(noteString); if (!match) { @@ -6115,7 +5791,7 @@ class TornadoFeeOracle { } } -var __async$5 = (__this, __arguments, generator) => { +var __async$6 = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { @@ -6140,7 +5816,7 @@ class Mimc { this.mimcPromise = this.initMimc(); } initMimc() { - return __async$5(this, null, function* () { + return __async$6(this, null, function* () { this.sponge = yield circomlibjs.buildMimcSponge(); this.hash = (left, right) => { var _a, _b; @@ -6149,7 +5825,7 @@ class Mimc { }); } getHash() { - return __async$5(this, null, function* () { + return __async$6(this, null, function* () { yield this.mimcPromise; return { sponge: this.sponge, @@ -6160,7 +5836,7 @@ class Mimc { } const mimc = new Mimc(); -var __async$4 = (__this, __arguments, generator) => { +var __async$5 = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { @@ -6203,7 +5879,7 @@ class MerkleTreeService { this.merkleWorkerPath = merkleWorkerPath; } createTree(events) { - return __async$4(this, null, function* () { + return __async$5(this, null, function* () { const { hash: hashFunction } = yield mimc.getHash(); if (this.merkleWorkerPath) { console.log("Using merkleWorker\n"); @@ -6255,7 +5931,7 @@ class MerkleTreeService { }); } createPartialTree(_0) { - return __async$4(this, arguments, function* ({ edge, elements }) { + return __async$5(this, arguments, function* ({ edge, elements }) { const { hash: hashFunction } = yield mimc.getHash(); if (this.merkleWorkerPath) { console.log("Using merkleWorker\n"); @@ -6309,7 +5985,7 @@ class MerkleTreeService { }); } verifyTree(events) { - return __async$4(this, null, function* () { + return __async$5(this, null, function* () { console.log( ` Creating deposit tree for ${this.netId} ${this.amount} ${this.currency.toUpperCase()} would take a while @@ -6329,6 +6005,50 @@ Creating deposit tree for ${this.netId} ${this.amount} ${this.currency.toUpperCa } } +var __async$4 = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +function multicall(Multicall2, calls) { + return __async$4(this, null, function* () { + const calldata = calls.map((call) => { + var _a, _b, _c; + const target = ((_a = call.contract) == null ? void 0 : _a.target) || call.address; + const callInterface = ((_b = call.contract) == null ? void 0 : _b.interface) || call.interface; + return { + target, + callData: callInterface.encodeFunctionData(call.name, call.params), + allowFailure: (_c = call.allowFailure) != null ? _c : false + }; + }); + const returnData = yield Multicall2.aggregate3.staticCall(calldata); + const res = returnData.map((call, i) => { + var _a; + const callInterface = ((_a = calls[i].contract) == null ? void 0 : _a.interface) || calls[i].interface; + const [result, data] = call; + const decodeResult = result && data && data !== "0x" ? callInterface.decodeFunctionResult(calls[i].name, data) : null; + return !decodeResult ? null : decodeResult.length === 1 ? decodeResult[0] : decodeResult; + }); + return res; + }); +} + var __async$3 = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { @@ -6424,8 +6144,7 @@ function isRelayerUpdated(relayerVersion, netId) { const { major, patch, prerelease } = parseSemanticVersion(relayerVersion); const requiredMajor = netId === NetId.MAINNET ? "4" : "5"; const isUpdatedMajor = major === requiredMajor; - if (prerelease) - return false; + if (prerelease) return false; return isUpdatedMajor && (Number(patch) >= 5 || netId !== NetId.MAINNET); } function calculateScore({ stakeBalance, tornadoServiceFee }, minFee = 0.33, maxFee = 0.53) { @@ -6826,7 +6545,6 @@ exports.GET_NOTE_ACCOUNTS = GET_NOTE_ACCOUNTS; exports.GET_REGISTERED = GET_REGISTERED; exports.GET_STATISTIC = GET_STATISTIC; exports.GET_WITHDRAWALS = GET_WITHDRAWALS; -exports.GasPriceOracle__factory = GasPriceOracle__factory; exports.Invoice = Invoice; exports.MIN_STAKE_BALANCE = MIN_STAKE_BALANCE; exports.MerkleTreeService = MerkleTreeService; @@ -6880,7 +6598,6 @@ exports.getAllWithdrawals = getAllWithdrawals; exports.getConfig = getConfig; exports.getDeposits = getDeposits; exports.getEncryptedNotes = getEncryptedNotes; -exports.getGasOraclePlugin = getGasOraclePlugin; exports.getGovernanceEvents = getGovernanceEvents; exports.getGraphEchoEvents = getGraphEchoEvents; exports.getHttpAgent = getHttpAgent; diff --git a/dist/index.mjs b/dist/index.mjs index ab3a4d1..90df6f2 100644 --- a/dist/index.mjs +++ b/dist/index.mjs @@ -1,4 +1,4 @@ -import { Interface, Contract, FetchUrlFeeDataNetworkPlugin, FetchRequest, Network, EnsPlugin, GasCostPlugin, JsonRpcProvider, Wallet, HDNodeWallet, VoidSigner, JsonRpcSigner, BrowserProvider, parseUnits, FeeData, getAddress, computeAddress, Transaction, parseEther, namehash, ZeroAddress } from 'ethers'; +import { FetchRequest, Network, EnsPlugin, GasCostPlugin, JsonRpcProvider, Wallet, HDNodeWallet, VoidSigner, JsonRpcSigner, BrowserProvider, FeeData, getAddress, Interface, Contract, computeAddress, parseUnits, Transaction, parseEther, namehash, ZeroAddress } from 'ethers'; import crossFetch from 'cross-fetch'; import { webcrypto } from 'crypto'; import BN from 'bn.js'; @@ -10,7 +10,3013 @@ import { MerkleTree, PartialMerkleTree } from '@tornado/fixed-merkle-tree'; import * as websnarkUtils from '@tornado/websnark/src/utils'; import websnarkGroth from '@tornado/websnark/src/groth16'; -const _abi$6 = [ +BigInt.prototype.toJSON = function() { + return this.toString(); +}; +const isNode = !process.browser && typeof globalThis.window === "undefined"; +const crypto = isNode ? webcrypto : globalThis.crypto; +const chunk = (arr, size) => [...Array(Math.ceil(arr.length / size))].map((_, i) => arr.slice(size * i, size + size * i)); +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} +function validateUrl(url, protocols) { + try { + const parsedUrl = new URL(url); + if (protocols && protocols.length) { + return protocols.map((p) => p.toLowerCase()).includes(parsedUrl.protocol); + } + return true; + } catch (e) { + return false; + } +} +function concatBytes(...arrays) { + const totalSize = arrays.reduce((acc, e) => acc + e.length, 0); + const merged = new Uint8Array(totalSize); + arrays.forEach((array, i, arrays2) => { + const offset = arrays2.slice(0, i).reduce((acc, e) => acc + e.length, 0); + merged.set(array, offset); + }); + return merged; +} +function bufferToBytes(b) { + return new Uint8Array(b.buffer); +} +function bytesToBase64(bytes) { + return btoa(String.fromCharCode.apply(null, Array.from(bytes))); +} +function base64ToBytes(base64) { + return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)); +} +function bytesToHex(bytes) { + return "0x" + Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""); +} +function hexToBytes(hexString) { + if (hexString.slice(0, 2) === "0x") { + hexString = hexString.replace("0x", ""); + } + if (hexString.length % 2 !== 0) { + hexString = "0" + hexString; + } + return Uint8Array.from(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); +} +function bytesToBN(bytes) { + return BigInt(bytesToHex(bytes)); +} +function bnToBytes(bigint) { + let hexString = typeof bigint === "bigint" ? bigint.toString(16) : bigint; + if (hexString.startsWith("0x")) { + hexString = hexString.replace("0x", ""); + } + if (hexString.length % 2 !== 0) { + hexString = "0" + hexString; + } + return Uint8Array.from(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); +} +function leBuff2Int(bytes) { + return new BN(bytes, 16, "le"); +} +function leInt2Buff(bigint) { + return Uint8Array.from(new BN(bigint).toArray("le", 31)); +} +function toFixedHex(numberish, length = 32) { + return "0x" + BigInt(numberish).toString(16).padStart(length * 2, "0"); +} +function toFixedLength(string, length = 32) { + string = string.replace("0x", ""); + return "0x" + string.padStart(length * 2, "0"); +} +function rBigInt(nbytes = 31) { + return bytesToBN(crypto.getRandomValues(new Uint8Array(nbytes))); +} +function bigIntReplacer(key, value) { + return typeof value === "bigint" ? value.toString() : value; +} +function substring(str, length = 10) { + if (str.length < length * 2) { + return str; + } + return `${str.substring(0, length)}...${str.substring(str.length - length)}`; +} + +var __defProp$4 = Object.defineProperty; +var __defProps$3 = Object.defineProperties; +var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols; +var __getProtoOf$1 = Object.getPrototypeOf; +var __hasOwnProp$4 = Object.prototype.hasOwnProperty; +var __propIsEnum$4 = Object.prototype.propertyIsEnumerable; +var __reflectGet$1 = Reflect.get; +var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$4 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$4.call(b, prop)) + __defNormalProp$4(a, prop, b[prop]); + if (__getOwnPropSymbols$4) + for (var prop of __getOwnPropSymbols$4(b)) { + if (__propIsEnum$4.call(b, prop)) + __defNormalProp$4(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b)); +var __superGet$1 = (cls, obj, key) => __reflectGet$1(__getProtoOf$1(cls), key, obj); +var __async$c = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +const defaultUserAgent = "Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/115.0"; +const fetch = crossFetch; +function getHttpAgent({ + fetchUrl, + proxyUrl, + torPort, + retry +}) { + const { HttpProxyAgent } = require("http-proxy-agent"); + const { HttpsProxyAgent } = require("https-proxy-agent"); + const { SocksProxyAgent } = require("socks-proxy-agent"); + if (torPort) { + return new SocksProxyAgent(`socks5h://tor${retry}@127.0.0.1:${torPort}`); + } + if (!proxyUrl) { + return; + } + const isHttps = fetchUrl.includes("https://"); + if (proxyUrl.includes("socks://") || proxyUrl.includes("socks4://") || proxyUrl.includes("socks5://")) { + return new SocksProxyAgent(proxyUrl); + } + if (proxyUrl.includes("http://") || proxyUrl.includes("https://")) { + if (isHttps) { + return new HttpsProxyAgent(proxyUrl); + } + return new HttpProxyAgent(proxyUrl); + } +} +function fetchData(_0) { + return __async$c(this, arguments, function* (url, options = {}) { + var _a, _b, _c; + const MAX_RETRY = (_a = options.maxRetry) != null ? _a : 3; + const RETRY_ON = (_b = options.retryOn) != null ? _b : 500; + const userAgent = (_c = options.userAgent) != null ? _c : defaultUserAgent; + let retry = 0; + let errorObject; + if (!options.method) { + if (!options.body) { + options.method = "GET"; + } else { + options.method = "POST"; + } + } + if (!options.headers) { + options.headers = {}; + } + if (isNode && !options.headers["User-Agent"]) { + options.headers["User-Agent"] = userAgent; + } + while (retry < MAX_RETRY + 1) { + let timeout; + if (!options.signal && options.timeout) { + const controller = new AbortController(); + options.signal = controller.signal; + timeout = setTimeout(() => { + controller.abort(); + }, options.timeout); + } + if (!options.agent && isNode && (options.proxy || options.torPort)) { + options.agent = getHttpAgent({ + fetchUrl: url, + proxyUrl: options.proxy, + torPort: options.torPort, + retry + }); + } + if (options.debug && typeof options.debug === "function") { + options.debug("request", { + url, + retry, + errorObject, + options + }); + } + try { + const resp = yield fetch(url, { + method: options.method, + headers: options.headers, + body: options.body, + redirect: options.redirect, + signal: options.signal, + agent: options.agent + }); + if (options.debug && typeof options.debug === "function") { + options.debug("response", resp); + } + if (!resp.ok) { + const errMsg = `Request to ${url} failed with error code ${resp.status}: +` + (yield resp.text()); + throw new Error(errMsg); + } + if (options.returnResponse) { + return resp; + } + const contentType = resp.headers.get("content-type"); + if (contentType == null ? void 0 : contentType.includes("application/json")) { + return yield resp.json(); + } + if (contentType == null ? void 0 : contentType.includes("text")) { + return yield resp.text(); + } + return resp; + } catch (error) { + if (timeout) { + clearTimeout(timeout); + } + errorObject = error; + retry++; + yield sleep(RETRY_ON); + } finally { + if (timeout) { + clearTimeout(timeout); + } + } + } + if (options.debug && typeof options.debug === "function") { + options.debug("error", errorObject); + } + throw errorObject; + }); +} +const fetchGetUrlFunc = (options = {}) => (req, _signal) => __async$c(void 0, null, function* () { + let signal; + if (_signal) { + const controller = new AbortController(); + signal = controller.signal; + _signal.addListener(() => { + controller.abort(); + }); + } + const init = __spreadProps$3(__spreadValues$4({}, options), { + method: req.method || "POST", + headers: req.headers, + body: req.body || void 0, + signal, + returnResponse: true + }); + const resp = yield fetchData(req.url, init); + const headers = {}; + resp.headers.forEach((value, key) => { + headers[key.toLowerCase()] = value; + }); + const respBody = yield resp.arrayBuffer(); + const body = respBody == null ? null : new Uint8Array(respBody); + return { + statusCode: resp.status, + statusMessage: resp.statusText, + headers, + body + }; +}); +function getProvider(rpcUrl, fetchOptions) { + return __async$c(this, null, function* () { + const fetchReq = new FetchRequest(rpcUrl); + fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); + const staticNetwork = yield new JsonRpcProvider(fetchReq).getNetwork(); + const provider = new JsonRpcProvider(fetchReq, staticNetwork, { + staticNetwork, + pollingInterval: (fetchOptions == null ? void 0 : fetchOptions.pollingInterval) || 1e3 + }); + return provider; + }); +} +function getProviderWithNetId(netId, rpcUrl, config, fetchOptions) { + const { networkName, reverseRecordsContract, pollInterval } = config; + const hasEns = Boolean(reverseRecordsContract); + const fetchReq = new FetchRequest(rpcUrl); + fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); + const staticNetwork = new Network(networkName, netId); + if (hasEns) { + staticNetwork.attachPlugin(new EnsPlugin(null, Number(netId))); + } + staticNetwork.attachPlugin(new GasCostPlugin()); + const provider = new JsonRpcProvider(fetchReq, staticNetwork, { + staticNetwork, + pollingInterval: (fetchOptions == null ? void 0 : fetchOptions.pollingInterval) || pollInterval * 1e3 + }); + return provider; +} +const populateTransaction = (signer, tx) => __async$c(void 0, null, function* () { + const provider = signer.provider; + if (!tx.from) { + tx.from = signer.address; + } else if (tx.from !== signer.address) { + const errMsg = `populateTransaction: signer mismatch for tx, wants ${tx.from} have ${signer.address}`; + throw new Error(errMsg); + } + const [feeData, nonce] = yield Promise.all([ + (() => __async$c(void 0, null, function* () { + if (tx.maxFeePerGas && tx.maxPriorityFeePerGas) { + return new FeeData(null, BigInt(tx.maxFeePerGas), BigInt(tx.maxPriorityFeePerGas)); + } + if (tx.gasPrice) { + return new FeeData(BigInt(tx.gasPrice), null, null); + } + const fetchedFeeData = yield provider.getFeeData(); + if (fetchedFeeData.maxFeePerGas && fetchedFeeData.maxPriorityFeePerGas) { + return new FeeData( + null, + fetchedFeeData.maxFeePerGas * (BigInt(1e4) + BigInt(signer.gasPriceBump)) / BigInt(1e4), + fetchedFeeData.maxPriorityFeePerGas + ); + } else { + return new FeeData( + fetchedFeeData.gasPrice * (BigInt(1e4) + BigInt(signer.gasPriceBump)) / BigInt(1e4), + null, + null + ); + } + }))(), + (() => __async$c(void 0, null, function* () { + if (tx.nonce) { + return tx.nonce; + } + let fetchedNonce = yield provider.getTransactionCount(signer.address, "pending"); + if (signer.bumpNonce && signer.nonce && signer.nonce >= fetchedNonce) { + console.log( + `populateTransaction: bumping nonce from ${fetchedNonce} to ${fetchedNonce + 1} for ${signer.address}` + ); + fetchedNonce++; + } + return fetchedNonce; + }))() + ]); + tx.nonce = nonce; + if (feeData.maxFeePerGas && feeData.maxPriorityFeePerGas) { + tx.maxFeePerGas = feeData.maxFeePerGas; + tx.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; + if (!tx.type) { + tx.type = 2; + } + delete tx.gasPrice; + } else if (feeData.gasPrice) { + tx.gasPrice = feeData.gasPrice; + if (!tx.type) { + tx.type = 0; + } + delete tx.maxFeePerGas; + delete tx.maxPriorityFeePerGas; + } + tx.gasLimit = tx.gasLimit || (yield (() => __async$c(void 0, null, function* () { + try { + const gasLimit = yield provider.estimateGas(tx); + return gasLimit === BigInt(21e3) ? gasLimit : gasLimit * (BigInt(1e4) + BigInt(signer.gasLimitBump)) / BigInt(1e4); + } catch (err) { + if (signer.gasFailover) { + console.log("populateTransaction: warning gas estimation failed falling back to 3M gas"); + return BigInt("3000000"); + } + throw err; + } + }))()); + return tx; +}); +class TornadoWallet extends Wallet { + constructor(key, provider, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce } = {}) { + super(key, provider); + this.gasPriceBump = gasPriceBump != null ? gasPriceBump : 0; + this.gasLimitBump = gasLimitBump != null ? gasLimitBump : 3e3; + this.gasFailover = gasFailover != null ? gasFailover : false; + this.bumpNonce = bumpNonce != null ? bumpNonce : false; + } + static fromMnemonic(mneomnic, provider, index = 0, options) { + const defaultPath = `m/44'/60'/0'/0/${index}`; + const { privateKey } = HDNodeWallet.fromPhrase(mneomnic, void 0, defaultPath); + return new TornadoWallet(privateKey, provider, options); + } + populateTransaction(tx) { + return __async$c(this, null, function* () { + const txObject = yield populateTransaction(this, tx); + this.nonce = txObject.nonce; + return __superGet$1(TornadoWallet.prototype, this, "populateTransaction").call(this, txObject); + }); + } +} +class TornadoVoidSigner extends VoidSigner { + constructor(address, provider, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce } = {}) { + super(address, provider); + this.gasPriceBump = gasPriceBump != null ? gasPriceBump : 0; + this.gasLimitBump = gasLimitBump != null ? gasLimitBump : 3e3; + this.gasFailover = gasFailover != null ? gasFailover : false; + this.bumpNonce = bumpNonce != null ? bumpNonce : false; + } + populateTransaction(tx) { + return __async$c(this, null, function* () { + const txObject = yield populateTransaction(this, tx); + this.nonce = txObject.nonce; + return __superGet$1(TornadoVoidSigner.prototype, this, "populateTransaction").call(this, txObject); + }); + } +} +class TornadoRpcSigner extends JsonRpcSigner { + constructor(provider, address, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce } = {}) { + super(provider, address); + this.gasPriceBump = gasPriceBump != null ? gasPriceBump : 0; + this.gasLimitBump = gasLimitBump != null ? gasLimitBump : 3e3; + this.gasFailover = gasFailover != null ? gasFailover : false; + this.bumpNonce = bumpNonce != null ? bumpNonce : false; + } + sendUncheckedTransaction(tx) { + return __async$c(this, null, function* () { + return __superGet$1(TornadoRpcSigner.prototype, this, "sendUncheckedTransaction").call(this, yield populateTransaction(this, tx)); + }); + } +} +class TornadoBrowserProvider extends BrowserProvider { + constructor(ethereum, network, options) { + super(ethereum, network); + this.options = options; + } + getSigner(address) { + return __async$c(this, null, function* () { + var _a, _b, _c, _d, _e, _f, _g, _h, _i; + const signerAddress = (yield __superGet$1(TornadoBrowserProvider.prototype, this, "getSigner").call(this, address)).address; + if (((_a = this.options) == null ? void 0 : _a.webChainId) && ((_b = this.options) == null ? void 0 : _b.connectWallet) && Number(yield __superGet$1(TornadoBrowserProvider.prototype, this, "send").call(this, "eth_chainId", [])) !== Number((_c = this.options) == null ? void 0 : _c.webChainId)) { + yield this.options.connectWallet(); + } + if ((_d = this.options) == null ? void 0 : _d.handleNetworkChanges) { + (_e = window == null ? void 0 : window.ethereum) == null ? void 0 : _e.on("chainChanged", this.options.handleNetworkChanges); + } + if ((_f = this.options) == null ? void 0 : _f.handleAccountChanges) { + (_g = window == null ? void 0 : window.ethereum) == null ? void 0 : _g.on("accountsChanged", this.options.handleAccountChanges); + } + if ((_h = this.options) == null ? void 0 : _h.handleAccountDisconnect) { + (_i = window == null ? void 0 : window.ethereum) == null ? void 0 : _i.on("disconnect", this.options.handleAccountDisconnect); + } + return new TornadoRpcSigner(this, signerAddress, this.options); + }); + } +} + +const GET_STATISTIC = ` + query getStatistic($currency: String!, $amount: String!, $first: Int, $orderBy: BigInt, $orderDirection: String) { + deposits(first: $first, orderBy: $orderBy, orderDirection: $orderDirection, where: { currency: $currency, amount: $amount }) { + index + timestamp + blockNumber + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const _META = ` + query getMeta { + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_REGISTERED = ` + query getRegistered($first: Int, $fromBlock: Int) { + relayers(first: $first, orderBy: blockRegistration, orderDirection: asc, where: { + blockRegistration_gte: $fromBlock + }) { + id + address + ensName + blockRegistration + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_DEPOSITS = ` + query getDeposits($currency: String!, $amount: String!, $first: Int, $fromBlock: Int) { + deposits(first: $first, orderBy: index, orderDirection: asc, where: { + amount: $amount, + currency: $currency, + blockNumber_gte: $fromBlock + }) { + id + blockNumber + commitment + index + timestamp + from + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_WITHDRAWALS = ` + query getWithdrawals($currency: String!, $amount: String!, $first: Int, $fromBlock: Int!) { + withdrawals(first: $first, orderBy: blockNumber, orderDirection: asc, where: { + currency: $currency, + amount: $amount, + blockNumber_gte: $fromBlock + }) { + id + blockNumber + nullifier + to + fee + timestamp + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_NOTE_ACCOUNTS = ` + query getNoteAccount($address: String!) { + noteAccounts(where: { address: $address }) { + id + index + address + encryptedAccount + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_ECHO_EVENTS = ` + query getNoteAccounts($first: Int, $fromBlock: Int) { + noteAccounts(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + id + blockNumber + address + encryptedAccount + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_ENCRYPTED_NOTES = ` + query getEncryptedNotes($first: Int, $fromBlock: Int) { + encryptedNotes(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + index + transactionHash + encryptedNote + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_GOVERNANCE_EVENTS = ` + query getGovernanceEvents($first: Int, $fromBlock: Int) { + proposals(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + logIndex + transactionHash + proposalId + proposer + target + startTime + endTime + description + } + votes(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + logIndex + transactionHash + proposalId + voter + support + votes + from + input + } + delegates(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + logIndex + transactionHash + account + delegateTo + } + undelegates(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + logIndex + transactionHash + account + delegateFrom + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_GOVERNANCE_APY = ` + stakeDailyBurns(first: 30, orderBy: date, orderDirection: desc) { + id + date + dailyAmountBurned + } +`; + +var __defProp$3 = Object.defineProperty; +var __defProps$2 = Object.defineProperties; +var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols; +var __hasOwnProp$3 = Object.prototype.hasOwnProperty; +var __propIsEnum$3 = Object.prototype.propertyIsEnumerable; +var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$3 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$3.call(b, prop)) + __defNormalProp$3(a, prop, b[prop]); + if (__getOwnPropSymbols$3) + for (var prop of __getOwnPropSymbols$3(b)) { + if (__propIsEnum$3.call(b, prop)) + __defNormalProp$3(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b)); +var __async$b = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +const isEmptyArray = (arr) => !Array.isArray(arr) || !arr.length; +const GRAPHQL_LIMIT = 1e3; +function queryGraph(_0) { + return __async$b(this, arguments, function* ({ + graphApi, + subgraphName, + query, + variables, + fetchDataOptions: fetchDataOptions2 + }) { + var _a; + const graphUrl = `${graphApi}/subgraphs/name/${subgraphName}`; + const { data, errors } = yield fetchData(graphUrl, __spreadProps$2(__spreadValues$3({}, fetchDataOptions2), { + method: "POST", + headers: { + "Content-Type": "application/json" + }, + body: JSON.stringify({ + query, + variables + }) + })); + if (errors) { + throw new Error(JSON.stringify(errors)); + } + if ((_a = data == null ? void 0 : data._meta) == null ? void 0 : _a.hasIndexingErrors) { + throw new Error("Subgraph has indexing errors"); + } + return data; + }); +} +function getStatistic(_0) { + return __async$b(this, arguments, function* ({ + graphApi, + subgraphName, + currency, + amount, + fetchDataOptions: fetchDataOptions2 + }) { + try { + const { + deposits, + _meta: { + block: { number: lastSyncBlock } + } + } = yield queryGraph({ + graphApi, + subgraphName, + query: GET_STATISTIC, + variables: { + currency, + first: 10, + orderBy: "index", + orderDirection: "desc", + amount + }, + fetchDataOptions: fetchDataOptions2 + }); + const events = deposits.map((e) => ({ + timestamp: Number(e.timestamp), + leafIndex: Number(e.index), + blockNumber: Number(e.blockNumber) + })).reverse(); + const [lastEvent] = events.slice(-1); + return { + events, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getStatistic query"); + console.log(err); + return { + events: [], + lastSyncBlock: null + }; + } + }); +} +function getMeta(_0) { + return __async$b(this, arguments, function* ({ graphApi, subgraphName, fetchDataOptions: fetchDataOptions2 }) { + try { + const { + _meta: { + block: { number: lastSyncBlock }, + hasIndexingErrors + } + } = yield queryGraph({ + graphApi, + subgraphName, + query: _META, + fetchDataOptions: fetchDataOptions2 + }); + return { + lastSyncBlock, + hasIndexingErrors + }; + } catch (err) { + console.log("Error from getMeta query"); + console.log(err); + return { + lastSyncBlock: null, + hasIndexingErrors: null + }; + } + }); +} +function getRegisters({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_REGISTERED, + variables: { + first: GRAPHQL_LIMIT, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllRegisters(_0) { + return __async$b(this, arguments, function* ({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + relayers: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getRegisters({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "Registers", + fromBlock: Number(firstEvent.blockRegistration), + toBlock: Number(lastEvent.blockRegistration), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockRegistration }) => blockRegistration !== lastEvent.blockRegistration); + fromBlock = Number(lastEvent.blockRegistration); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map(({ id, address, ensName, blockRegistration }) => { + const [transactionHash, logIndex] = id.split("-"); + return { + blockNumber: Number(blockRegistration), + logIndex: Number(logIndex), + transactionHash, + ensName, + relayerAddress: getAddress(address) + }; + }); + return { + events: result, + lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllRegisters query"); + console.log(err); + return { events: [], lastSyncBlock: fromBlock }; + } + }); +} +function getDeposits({ + graphApi, + subgraphName, + currency, + amount, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_DEPOSITS, + variables: { + currency, + amount, + first: GRAPHQL_LIMIT, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllDeposits(_0) { + return __async$b(this, arguments, function* ({ + graphApi, + subgraphName, + currency, + amount, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + deposits: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getDeposits({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent2] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "Deposits", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map(({ id, blockNumber, commitment, index, timestamp, from }) => { + const [transactionHash, logIndex] = id.split("-"); + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + commitment, + leafIndex: Number(index), + timestamp: Number(timestamp), + from: getAddress(from) + }; + }); + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllDeposits query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} +function getWithdrawals({ + graphApi, + subgraphName, + currency, + amount, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_WITHDRAWALS, + variables: { + currency, + amount, + first: GRAPHQL_LIMIT, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllWithdrawals(_0) { + return __async$b(this, arguments, function* ({ + graphApi, + subgraphName, + currency, + amount, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + withdrawals: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getWithdrawals({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent2] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "Withdrawals", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map(({ id, blockNumber, nullifier, to, fee, timestamp }) => { + const [transactionHash, logIndex] = id.split("-"); + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + nullifierHash: nullifier, + to: getAddress(to), + fee, + timestamp: Number(timestamp) + }; + }); + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllWithdrawals query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} +function getNoteAccounts(_0) { + return __async$b(this, arguments, function* ({ + graphApi, + subgraphName, + address, + fetchDataOptions: fetchDataOptions2 + }) { + try { + const { + noteAccounts: events, + _meta: { + block: { number: lastSyncBlock } + } + } = yield queryGraph({ + graphApi, + subgraphName, + query: GET_NOTE_ACCOUNTS, + variables: { + address: address.toLowerCase() + }, + fetchDataOptions: fetchDataOptions2 + }); + return { + events, + lastSyncBlock + }; + } catch (err) { + console.log("Error from getNoteAccounts query"); + console.log(err); + return { + events: [], + lastSyncBlock: null + }; + } + }); +} +function getGraphEchoEvents({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_ECHO_EVENTS, + variables: { + first: GRAPHQL_LIMIT, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllGraphEchoEvents(_0) { + return __async$b(this, arguments, function* ({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + noteAccounts: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getGraphEchoEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent2] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "EchoEvents", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map((e) => { + const [transactionHash, logIndex] = e.id.split("-"); + return { + blockNumber: Number(e.blockNumber), + logIndex: Number(logIndex), + transactionHash, + address: getAddress(e.address), + encryptedAccount: e.encryptedAccount + }; + }); + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllGraphEchoEvents query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} +function getEncryptedNotes({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_ENCRYPTED_NOTES, + variables: { + first: GRAPHQL_LIMIT, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllEncryptedNotes(_0) { + return __async$b(this, arguments, function* ({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + encryptedNotes: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getEncryptedNotes({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent2] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "EncryptedNotes", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map((e) => ({ + blockNumber: Number(e.blockNumber), + logIndex: Number(e.index), + transactionHash: e.transactionHash, + encryptedNote: e.encryptedNote + })); + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllEncryptedNotes query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} +function getGovernanceEvents({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_GOVERNANCE_EVENTS, + variables: { + first: GRAPHQL_LIMIT, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllGovernanceEvents(_0) { + return __async$b(this, arguments, function* ({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const result = []; + let lastSyncBlock = fromBlock; + while (true) { + const { + proposals, + votes, + delegates, + undelegates, + _meta: { + block: { number: currentBlock } + } + } = yield getGovernanceEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + const eventsLength = proposals.length + votes.length + delegates.length + undelegates.length; + if (eventsLength === 0) { + break; + } + const formattedProposals = proposals.map( + ({ blockNumber, logIndex, transactionHash, proposalId, proposer, target, startTime, endTime, description }) => { + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + event: "ProposalCreated", + id: Number(proposalId), + proposer: getAddress(proposer), + target: getAddress(target), + startTime: Number(startTime), + endTime: Number(endTime), + description + }; + } + ); + const formattedVotes = votes.map( + ({ blockNumber, logIndex, transactionHash, proposalId, voter, support, votes: votes2, from, input }) => { + if (!input || input.length > 2048) { + input = ""; + } + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + event: "Voted", + proposalId: Number(proposalId), + voter: getAddress(voter), + support, + votes: votes2, + from: getAddress(from), + input + }; + } + ); + const formattedDelegates = delegates.map( + ({ blockNumber, logIndex, transactionHash, account, delegateTo }) => { + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + event: "Delegated", + account: getAddress(account), + delegateTo: getAddress(delegateTo) + }; + } + ); + const formattedUndelegates = undelegates.map( + ({ blockNumber, logIndex, transactionHash, account, delegateFrom }) => { + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + event: "Undelegated", + account: getAddress(account), + delegateFrom: getAddress(delegateFrom) + }; + } + ); + let formattedEvents = [ + ...formattedProposals, + ...formattedVotes, + ...formattedDelegates, + ...formattedUndelegates + ].sort((a, b) => { + if (a.blockNumber === b.blockNumber) { + return a.logIndex - b.logIndex; + } + return a.blockNumber - b.blockNumber; + }); + if (eventsLength < 900) { + result.push(...formattedEvents); + break; + } + const [firstEvent] = formattedEvents; + const [lastEvent2] = formattedEvents.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "Governance Events", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: eventsLength + }); + } + formattedEvents = formattedEvents.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + result.push(...formattedEvents); + } + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllGovernance query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} + +var graph = /*#__PURE__*/Object.freeze({ + __proto__: null, + GET_DEPOSITS: GET_DEPOSITS, + GET_ECHO_EVENTS: GET_ECHO_EVENTS, + GET_ENCRYPTED_NOTES: GET_ENCRYPTED_NOTES, + GET_GOVERNANCE_APY: GET_GOVERNANCE_APY, + GET_GOVERNANCE_EVENTS: GET_GOVERNANCE_EVENTS, + GET_NOTE_ACCOUNTS: GET_NOTE_ACCOUNTS, + GET_REGISTERED: GET_REGISTERED, + GET_STATISTIC: GET_STATISTIC, + GET_WITHDRAWALS: GET_WITHDRAWALS, + _META: _META, + getAllDeposits: getAllDeposits, + getAllEncryptedNotes: getAllEncryptedNotes, + getAllGovernanceEvents: getAllGovernanceEvents, + getAllGraphEchoEvents: getAllGraphEchoEvents, + getAllRegisters: getAllRegisters, + getAllWithdrawals: getAllWithdrawals, + getDeposits: getDeposits, + getEncryptedNotes: getEncryptedNotes, + getGovernanceEvents: getGovernanceEvents, + getGraphEchoEvents: getGraphEchoEvents, + getMeta: getMeta, + getNoteAccounts: getNoteAccounts, + getRegisters: getRegisters, + getStatistic: getStatistic, + getWithdrawals: getWithdrawals, + queryGraph: queryGraph +}); + +var __async$a = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +class BatchBlockService { + constructor({ + provider, + onProgress, + concurrencySize = 10, + batchSize = 10, + shouldRetry = true, + retryMax = 5, + retryOn = 500 + }) { + this.provider = provider; + this.onProgress = onProgress; + this.concurrencySize = concurrencySize; + this.batchSize = batchSize; + this.shouldRetry = shouldRetry; + this.retryMax = retryMax; + this.retryOn = retryOn; + } + getBlock(blockTag) { + return __async$a(this, null, function* () { + const blockObject = yield this.provider.getBlock(blockTag); + if (!blockObject) { + const errMsg = `No block for ${blockTag}`; + throw new Error(errMsg); + } + return blockObject; + }); + } + createBatchRequest(batchArray) { + return batchArray.map((blocks, index) => __async$a(this, null, function* () { + yield sleep(20 * index); + return (() => __async$a(this, null, function* () { + let retries = 0; + let err; + while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { + try { + return yield Promise.all(blocks.map((b) => this.getBlock(b))); + } catch (e) { + retries++; + err = e; + yield sleep(this.retryOn); + } + } + throw err; + }))(); + })); + } + getBatchBlocks(blocks) { + return __async$a(this, null, function* () { + let blockCount = 0; + const results = []; + for (const chunks of chunk(blocks, this.concurrencySize * this.batchSize)) { + const chunksResult = (yield Promise.all(this.createBatchRequest(chunk(chunks, this.batchSize)))).flat(); + results.push(...chunksResult); + blockCount += chunks.length; + if (typeof this.onProgress === "function") { + this.onProgress({ + percentage: blockCount / blocks.length, + currentIndex: blockCount, + totalIndex: blocks.length + }); + } + } + return results; + }); + } +} +class BatchTransactionService { + constructor({ + provider, + onProgress, + concurrencySize = 10, + batchSize = 10, + shouldRetry = true, + retryMax = 5, + retryOn = 500 + }) { + this.provider = provider; + this.onProgress = onProgress; + this.concurrencySize = concurrencySize; + this.batchSize = batchSize; + this.shouldRetry = shouldRetry; + this.retryMax = retryMax; + this.retryOn = retryOn; + } + getTransaction(txHash) { + return __async$a(this, null, function* () { + const txObject = yield this.provider.getTransaction(txHash); + if (!txObject) { + const errMsg = `No transaction for ${txHash}`; + throw new Error(errMsg); + } + return txObject; + }); + } + createBatchRequest(batchArray) { + return batchArray.map((txs, index) => __async$a(this, null, function* () { + yield sleep(20 * index); + return (() => __async$a(this, null, function* () { + let retries = 0; + let err; + while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { + try { + return yield Promise.all(txs.map((tx) => this.getTransaction(tx))); + } catch (e) { + retries++; + err = e; + yield sleep(this.retryOn); + } + } + throw err; + }))(); + })); + } + getBatchTransactions(txs) { + return __async$a(this, null, function* () { + let txCount = 0; + const results = []; + for (const chunks of chunk(txs, this.concurrencySize * this.batchSize)) { + const chunksResult = (yield Promise.all(this.createBatchRequest(chunk(chunks, this.batchSize)))).flat(); + results.push(...chunksResult); + txCount += chunks.length; + if (typeof this.onProgress === "function") { + this.onProgress({ percentage: txCount / txs.length, currentIndex: txCount, totalIndex: txs.length }); + } + } + return results; + }); + } +} +class BatchEventsService { + constructor({ + provider, + contract, + onProgress, + concurrencySize = 10, + blocksPerRequest = 2e3, + shouldRetry = true, + retryMax = 5, + retryOn = 500 + }) { + this.provider = provider; + this.contract = contract; + this.onProgress = onProgress; + this.concurrencySize = concurrencySize; + this.blocksPerRequest = blocksPerRequest; + this.shouldRetry = shouldRetry; + this.retryMax = retryMax; + this.retryOn = retryOn; + } + getPastEvents(_0) { + return __async$a(this, arguments, function* ({ fromBlock, toBlock, type }) { + let err; + let retries = 0; + while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { + try { + return yield this.contract.queryFilter(type, fromBlock, toBlock); + } catch (e) { + err = e; + retries++; + if (e.message.includes("after last accepted block")) { + const acceptedBlock = parseInt(e.message.split("after last accepted block ")[1]); + toBlock = acceptedBlock; + } + yield sleep(this.retryOn); + } + } + throw err; + }); + } + createBatchRequest(batchArray) { + return batchArray.map((event, index) => __async$a(this, null, function* () { + yield sleep(20 * index); + return this.getPastEvents(event); + })); + } + getBatchEvents(_0) { + return __async$a(this, arguments, function* ({ fromBlock, toBlock, type = "*" }) { + if (!toBlock) { + toBlock = yield this.provider.getBlockNumber(); + } + const eventsToSync = []; + for (let i = fromBlock; i < toBlock; i += this.blocksPerRequest) { + const j = i + this.blocksPerRequest - 1 > toBlock ? toBlock : i + this.blocksPerRequest - 1; + eventsToSync.push({ fromBlock: i, toBlock: j, type }); + } + const events = []; + const eventChunk = chunk(eventsToSync, this.concurrencySize); + let chunkCount = 0; + for (const chunk2 of eventChunk) { + chunkCount++; + const fetchedEvents = (yield Promise.all(this.createBatchRequest(chunk2))).flat(); + events.push(...fetchedEvents); + if (typeof this.onProgress === "function") { + this.onProgress({ + percentage: chunkCount / eventChunk.length, + type, + fromBlock: chunk2[0].fromBlock, + toBlock: chunk2[chunk2.length - 1].toBlock, + count: fetchedEvents.length + }); + } + } + return events; + }); + } +} + +var __defProp$2 = Object.defineProperty; +var __defProps$1 = Object.defineProperties; +var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp$2 = Object.prototype.hasOwnProperty; +var __propIsEnum$2 = Object.prototype.propertyIsEnumerable; +var __reflectGet = Reflect.get; +var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$2 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$2.call(b, prop)) + __defNormalProp$2(a, prop, b[prop]); + if (__getOwnPropSymbols$2) + for (var prop of __getOwnPropSymbols$2(b)) { + if (__propIsEnum$2.call(b, prop)) + __defNormalProp$2(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b)); +var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj); +var __async$9 = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +const DEPOSIT = "deposit"; +const WITHDRAWAL = "withdrawal"; +class BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + contract, + type = "", + deployedBlock = 0, + fetchDataOptions: fetchDataOptions2 + }) { + this.netId = netId; + this.provider = provider; + this.graphApi = graphApi; + this.subgraphName = subgraphName; + this.fetchDataOptions = fetchDataOptions2; + this.contract = contract; + this.type = type; + this.deployedBlock = deployedBlock; + this.batchEventsService = new BatchEventsService({ + provider, + contract, + onProgress: this.updateEventProgress + }); + } + getInstanceName() { + return ""; + } + getType() { + return this.type || ""; + } + getGraphMethod() { + return ""; + } + getGraphParams() { + return { + graphApi: this.graphApi || "", + subgraphName: this.subgraphName || "", + fetchDataOptions: this.fetchDataOptions, + onProgress: this.updateGraphProgress + }; + } + /* eslint-disable @typescript-eslint/no-unused-vars */ + updateEventProgress({ percentage, type, fromBlock, toBlock, count }) { + } + updateBlockProgress({ percentage, currentIndex, totalIndex }) { + } + updateTransactionProgress({ percentage, currentIndex, totalIndex }) { + } + updateGraphProgress({ type, fromBlock, toBlock, count }) { + } + /* eslint-enable @typescript-eslint/no-unused-vars */ + formatEvents(events) { + return __async$9(this, null, function* () { + return yield new Promise((resolve) => resolve(events)); + }); + } + /** + * Get saved or cached events + */ + getEventsFromDB() { + return __async$9(this, null, function* () { + return { + events: [], + lastBlock: null + }; + }); + } + /** + * Events from remote cache (Either from local cache, CDN, or from IPFS) + */ + getEventsFromCache() { + return __async$9(this, null, function* () { + return { + events: [], + lastBlock: null, + fromCache: true + }; + }); + } + getSavedEvents() { + return __async$9(this, null, function* () { + let cachedEvents = yield this.getEventsFromDB(); + if (!cachedEvents || !cachedEvents.events.length) { + cachedEvents = yield this.getEventsFromCache(); + } + return cachedEvents; + }); + } + /** + * Get latest events + */ + getEventsFromGraph(_0) { + return __async$9(this, arguments, function* ({ + fromBlock, + methodName = "" + }) { + if (!this.graphApi || !this.subgraphName) { + return { + events: [], + lastBlock: fromBlock + }; + } + const { events, lastSyncBlock } = yield graph[methodName || this.getGraphMethod()](__spreadValues$2({ + fromBlock + }, this.getGraphParams())); + return { + events, + lastBlock: lastSyncBlock + }; + }); + } + getEventsFromRpc(_0) { + return __async$9(this, arguments, function* ({ + fromBlock, + toBlock + }) { + try { + if (!toBlock) { + toBlock = yield this.provider.getBlockNumber(); + } + if (fromBlock >= toBlock) { + return { + events: [], + lastBlock: toBlock + }; + } + this.updateEventProgress({ percentage: 0, type: this.getType() }); + const events = yield this.formatEvents( + yield this.batchEventsService.getBatchEvents({ fromBlock, toBlock, type: this.getType() }) + ); + if (!events.length) { + return { + events, + lastBlock: toBlock + }; + } + return { + events, + lastBlock: toBlock + }; + } catch (err) { + console.log(err); + return { + events: [], + lastBlock: fromBlock + }; + } + }); + } + getLatestEvents(_0) { + return __async$9(this, arguments, function* ({ fromBlock }) { + const allEvents = []; + const graphEvents = yield this.getEventsFromGraph({ fromBlock }); + const lastSyncBlock = graphEvents.lastBlock && graphEvents.lastBlock >= fromBlock ? graphEvents.lastBlock : fromBlock; + const rpcEvents = yield this.getEventsFromRpc({ fromBlock: lastSyncBlock }); + allEvents.push(...graphEvents.events); + allEvents.push(...rpcEvents.events); + const lastBlock = rpcEvents ? rpcEvents.lastBlock : allEvents[allEvents.length - 1] ? allEvents[allEvents.length - 1].blockNumber : fromBlock; + return { + events: allEvents, + lastBlock + }; + }); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + validateEvents({ events, lastBlock }) { + } + /** + * Handle saving events + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + saveEvents(_0) { + return __async$9(this, arguments, function* ({ events, lastBlock }) { + }); + } + /** + * Trigger saving and receiving latest events + */ + updateEvents() { + return __async$9(this, null, function* () { + const savedEvents = yield this.getSavedEvents(); + let fromBlock = this.deployedBlock; + if (savedEvents && savedEvents.lastBlock) { + fromBlock = savedEvents.lastBlock + 1; + } + const newEvents = yield this.getLatestEvents({ fromBlock }); + const eventSet = /* @__PURE__ */ new Set(); + let allEvents = []; + allEvents.push(...savedEvents.events); + allEvents.push(...newEvents.events); + allEvents = allEvents.sort((a, b) => { + if (a.blockNumber === b.blockNumber) { + return a.logIndex - b.logIndex; + } + return a.blockNumber - b.blockNumber; + }).filter(({ transactionHash, logIndex }) => { + const eventKey = `${transactionHash}_${logIndex}`; + const hasEvent = eventSet.has(eventKey); + eventSet.add(eventKey); + return !hasEvent; + }); + const lastBlock = newEvents ? newEvents.lastBlock : allEvents[allEvents.length - 1] ? allEvents[allEvents.length - 1].blockNumber : null; + this.validateEvents({ events: allEvents, lastBlock }); + if (savedEvents.fromCache || newEvents.events.length) { + yield this.saveEvents({ events: allEvents, lastBlock }); + } + return { + events: allEvents, + lastBlock + }; + }); + } +} +class BaseTornadoService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Tornado, + type, + amount, + currency, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: Tornado, type, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + this.amount = amount; + this.currency = currency; + this.batchTransactionService = new BatchTransactionService({ + provider, + onProgress: this.updateTransactionProgress + }); + this.batchBlockService = new BatchBlockService({ + provider, + onProgress: this.updateBlockProgress + }); + } + getInstanceName() { + return `${this.getType().toLowerCase()}s_${this.netId}_${this.currency}_${this.amount}`; + } + getGraphMethod() { + return `getAll${this.getType()}s`; + } + getGraphParams() { + return { + graphApi: this.graphApi || "", + subgraphName: this.subgraphName || "", + amount: this.amount, + currency: this.currency, + fetchDataOptions: this.fetchDataOptions, + onProgress: this.updateGraphProgress + }; + } + formatEvents(events) { + return __async$9(this, null, function* () { + const type = this.getType().toLowerCase(); + if (type === DEPOSIT) { + const formattedEvents = events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const { commitment, leafIndex, timestamp } = args; + return { + blockNumber, + logIndex, + transactionHash, + commitment, + leafIndex: Number(leafIndex), + timestamp: Number(timestamp) + }; + }); + const txs = yield this.batchTransactionService.getBatchTransactions([ + ...new Set(formattedEvents.map(({ transactionHash }) => transactionHash)) + ]); + return formattedEvents.map((event) => { + const { from } = txs.find(({ hash }) => hash === event.transactionHash); + return __spreadProps$1(__spreadValues$2({}, event), { + from + }); + }); + } else { + const formattedEvents = events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const { nullifierHash, to, fee } = args; + return { + blockNumber, + logIndex, + transactionHash, + nullifierHash: String(nullifierHash), + to: getAddress(to), + fee: String(fee) + }; + }); + const blocks = yield this.batchBlockService.getBatchBlocks([ + ...new Set(formattedEvents.map(({ blockNumber }) => blockNumber)) + ]); + return formattedEvents.map((event) => { + const { timestamp } = blocks.find(({ number }) => number === event.blockNumber); + return __spreadProps$1(__spreadValues$2({}, event), { + timestamp + }); + }); + } + }); + } + validateEvents({ events }) { + if (events.length && this.getType().toLowerCase() === DEPOSIT) { + const lastEvent = events[events.length - 1]; + if (lastEvent.leafIndex !== events.length - 1) { + const errMsg = `Deposit events invalid wants ${events.length - 1} leafIndex have ${lastEvent.leafIndex}`; + throw new Error(errMsg); + } + } + } +} +class BaseEchoService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Echoer, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: Echoer, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + } + getInstanceName() { + return `echo_${this.netId}`; + } + getType() { + return "Echo"; + } + getGraphMethod() { + return "getAllGraphEchoEvents"; + } + formatEvents(events) { + return __async$9(this, null, function* () { + return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const { who, data } = args; + if (who && data) { + const eventObjects = { + blockNumber, + logIndex, + transactionHash + }; + return __spreadProps$1(__spreadValues$2({}, eventObjects), { + address: who, + encryptedAccount: data + }); + } + }).filter((e) => e); + }); + } + getEventsFromGraph(_0) { + return __async$9(this, arguments, function* ({ fromBlock }) { + if (!this.graphApi || this.graphApi.includes("api.thegraph.com")) { + return { + events: [], + lastBlock: fromBlock + }; + } + return __superGet(BaseEchoService.prototype, this, "getEventsFromGraph").call(this, { fromBlock }); + }); + } +} +class BaseEncryptedNotesService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Router, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: Router, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + } + getInstanceName() { + return `encrypted_notes_${this.netId}`; + } + getType() { + return "EncryptedNote"; + } + getGraphMethod() { + return "getAllEncryptedNotes"; + } + formatEvents(events) { + return __async$9(this, null, function* () { + return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const { encryptedNote } = args; + if (encryptedNote) { + const eventObjects = { + blockNumber, + logIndex, + transactionHash + }; + return __spreadProps$1(__spreadValues$2({}, eventObjects), { + encryptedNote + }); + } + }).filter((e) => e); + }); + } +} +class BaseGovernanceService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Governance, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: Governance, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + this.batchTransactionService = new BatchTransactionService({ + provider, + onProgress: this.updateTransactionProgress + }); + } + getInstanceName() { + return `governance_${this.netId}`; + } + getType() { + return "*"; + } + getGraphMethod() { + return "getAllGovernanceEvents"; + } + formatEvents(events) { + return __async$9(this, null, function* () { + const proposalEvents = []; + const votedEvents = []; + const delegatedEvents = []; + const undelegatedEvents = []; + events.forEach(({ blockNumber, index: logIndex, transactionHash, args, eventName: event }) => { + const eventObjects = { + blockNumber, + logIndex, + transactionHash, + event + }; + if (event === "ProposalCreated") { + const { id, proposer, target, startTime, endTime, description } = args; + proposalEvents.push(__spreadProps$1(__spreadValues$2({}, eventObjects), { + id: Number(id), + proposer, + target, + startTime: Number(startTime), + endTime: Number(endTime), + description + })); + } + if (event === "Voted") { + const { proposalId, voter, support, votes } = args; + votedEvents.push(__spreadProps$1(__spreadValues$2({}, eventObjects), { + proposalId: Number(proposalId), + voter, + support, + votes, + from: "", + input: "" + })); + } + if (event === "Delegated") { + const { account, to: delegateTo } = args; + delegatedEvents.push(__spreadProps$1(__spreadValues$2({}, eventObjects), { + account, + delegateTo + })); + } + if (event === "Undelegated") { + const { account, from: delegateFrom } = args; + undelegatedEvents.push(__spreadProps$1(__spreadValues$2({}, eventObjects), { + account, + delegateFrom + })); + } + }); + if (votedEvents.length) { + this.updateTransactionProgress({ percentage: 0 }); + const txs = yield this.batchTransactionService.getBatchTransactions([ + ...new Set(votedEvents.map(({ transactionHash }) => transactionHash)) + ]); + votedEvents.forEach((event, index) => { + let { data: input, from } = txs.find((t) => t.hash === event.transactionHash); + if (!input || input.length > 2048) { + input = ""; + } + votedEvents[index].from = from; + votedEvents[index].input = input; + }); + } + return [...proposalEvents, ...votedEvents, ...delegatedEvents, ...undelegatedEvents]; + }); + } + getEventsFromGraph(_0) { + return __async$9(this, arguments, function* ({ fromBlock }) { + if (!this.graphApi || !this.subgraphName || this.graphApi.includes("api.thegraph.com")) { + return { + events: [], + lastBlock: fromBlock + }; + } + return __superGet(BaseGovernanceService.prototype, this, "getEventsFromGraph").call(this, { fromBlock }); + }); + } +} +class BaseRegistryService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + RelayerRegistry, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: RelayerRegistry, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + } + getInstanceName() { + return `registered_${this.netId}`; + } + // Name of type used for events + getType() { + return "RelayerRegistered"; + } + // Name of method used for graph + getGraphMethod() { + return "getAllRegisters"; + } + formatEvents(events) { + return __async$9(this, null, function* () { + return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const eventObjects = { + blockNumber, + logIndex, + transactionHash + }; + return __spreadProps$1(__spreadValues$2({}, eventObjects), { + ensName: args.ensName, + relayerAddress: args.relayerAddress + }); + }); + }); + } + fetchRelayers() { + return __async$9(this, null, function* () { + return (yield this.updateEvents()).events; + }); + } +} + +var __defProp$1 = Object.defineProperty; +var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols; +var __hasOwnProp$1 = Object.prototype.hasOwnProperty; +var __propIsEnum$1 = Object.prototype.propertyIsEnumerable; +var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$1 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$1.call(b, prop)) + __defNormalProp$1(a, prop, b[prop]); + if (__getOwnPropSymbols$1) + for (var prop of __getOwnPropSymbols$1(b)) { + if (__propIsEnum$1.call(b, prop)) + __defNormalProp$1(a, prop, b[prop]); + } + return a; +}; +var NetId = /* @__PURE__ */ ((NetId2) => { + NetId2[NetId2["MAINNET"] = 1] = "MAINNET"; + NetId2[NetId2["BSC"] = 56] = "BSC"; + NetId2[NetId2["POLYGON"] = 137] = "POLYGON"; + NetId2[NetId2["OPTIMISM"] = 10] = "OPTIMISM"; + NetId2[NetId2["ARBITRUM"] = 42161] = "ARBITRUM"; + NetId2[NetId2["GNOSIS"] = 100] = "GNOSIS"; + NetId2[NetId2["AVALANCHE"] = 43114] = "AVALANCHE"; + NetId2[NetId2["SEPOLIA"] = 11155111] = "SEPOLIA"; + return NetId2; +})(NetId || {}); +const theGraph = { + name: "Hosted Graph", + url: "https://api.thegraph.com" +}; +const tornado = { + name: "Tornado Subgraphs", + url: "https://tornadocash-rpc.com" +}; +const defaultConfig = { + [1 /* MAINNET */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 80, + fast: 50, + standard: 25, + low: 8 + }, + nativeCurrency: "eth", + currencyName: "ETH", + explorerUrl: "https://etherscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Ethereum Mainnet", + deployedBlock: 9116966, + rpcUrls: { + tornadoRPC: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/mainnet" + }, + mevblockerRPC: { + name: "MevblockerRPC", + url: "https://rpc.mevblocker.io" + }, + oneRPC: { + name: "1RPC", + url: "https://1rpc.io/eth" + } + }, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0xd90e2f925DA726b50C4Ed8D0Fb90Ad053324F31b", + echoContract: "0x9B27DD5Bb15d42DC224FCD0B7caEbBe16161Df42", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornContract: "0x77777FeDdddFfC19Ff86DB637967013e6C6A116C", + governanceContract: "0x5efda50f22d34F262c29268506C5Fa42cB56A1Ce", + stakingRewardsContract: "0x5B3f656C80E8ddb9ec01Dd9018815576E9238c29", + registryContract: "0x58E8dCC13BE9780fC42E8723D8EaD4CF46943dF2", + aggregatorContract: "0xE8F47A78A6D52D317D0D2FFFac56739fE14D1b49", + reverseRecordsContract: "0x3671aE578E63FdF66ad4F3E12CC0c0d71Ac7510C", + tornadoSubgraph: "tornadocash/mainnet-tornado-subgraph", + registrySubgraph: "tornadocash/tornado-relayer-registry", + governanceSubgraph: "tornadocash/tornado-governance", + subgraphs: { + tornado, + theGraph + }, + tokens: { + eth: { + instanceAddress: { + "0.1": "0x12D66f87A04A9E220743712cE6d9bB1B5616B8Fc", + "1": "0x47CE0C6eD5B0Ce3d3A51fdb1C52DC66a7c3c2936", + "10": "0x910Cbd523D972eb0a6f4cAe4618aD62622b39DbF", + "100": "0xA160cdAB225685dA1d56aa342Ad8841c3b53f291" + }, + symbol: "ETH", + decimals: 18 + }, + dai: { + instanceAddress: { + "100": "0xD4B88Df4D29F5CedD6857912842cff3b20C8Cfa3", + "1000": "0xFD8610d20aA15b7B2E3Be39B396a1bC3516c7144", + "10000": "0x07687e702b410Fa43f4cB4Af7FA097918ffD2730", + "100000": "0x23773E65ed146A459791799d01336DB287f25334" + }, + tokenAddress: "0x6B175474E89094C44Da98b954EedeAC495271d0F", + tokenGasLimit: 7e4, + symbol: "DAI", + decimals: 18, + gasLimit: 7e5 + }, + cdai: { + instanceAddress: { + "5000": "0x22aaA7720ddd5388A3c0A3333430953C68f1849b", + "50000": "0x03893a7c7463AE47D46bc7f091665f1893656003", + "500000": "0x2717c5e28cf931547B621a5dddb772Ab6A35B701", + "5000000": "0xD21be7248e0197Ee08E0c20D4a96DEBdaC3D20Af" + }, + tokenAddress: "0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643", + tokenGasLimit: 2e5, + symbol: "cDAI", + decimals: 8, + gasLimit: 7e5 + }, + usdc: { + instanceAddress: { + "100": "0xd96f2B1c14Db8458374d9Aca76E26c3D18364307", + "1000": "0x4736dCf1b7A3d580672CcE6E7c65cd5cc9cFBa9D" + }, + tokenAddress: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", + tokenGasLimit: 7e4, + symbol: "USDC", + decimals: 6, + gasLimit: 7e5 + }, + usdt: { + instanceAddress: { + "100": "0x169AD27A470D064DEDE56a2D3ff727986b15D52B", + "1000": "0x0836222F2B2B24A3F36f98668Ed8F0B38D1a872f" + }, + tokenAddress: "0xdAC17F958D2ee523a2206206994597C13D831ec7", + tokenGasLimit: 7e4, + symbol: "USDT", + decimals: 6, + gasLimit: 7e5 + }, + wbtc: { + instanceAddress: { + "0.1": "0x178169B423a011fff22B9e3F3abeA13414dDD0F1", + "1": "0x610B717796ad172B316836AC95a2ffad065CeaB4", + "10": "0xbB93e510BbCD0B7beb5A853875f9eC60275CF498" + }, + tokenAddress: "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599", + tokenGasLimit: 7e4, + symbol: "WBTC", + decimals: 8, + gasLimit: 7e5 + } + }, + relayerEnsSubdomain: "mainnet-tornado", + pollInterval: 15, + constants: { + GOVERNANCE_BLOCK: 11474695, + NOTE_ACCOUNT_BLOCK: 11842486, + ENCRYPTED_NOTES_BLOCK: 12143762, + REGISTRY_BLOCK: 14173129, + MINING_BLOCK_TIME: 15 + } + }, + [56 /* BSC */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 5, + fast: 5, + standard: 5, + low: 5 + }, + nativeCurrency: "bnb", + currencyName: "BNB", + explorerUrl: "https://bscscan.com", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Binance Smart Chain", + deployedBlock: 8158799, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornadoSubgraph: "tornadocash/bsc-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + tornadoRPC: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/bsc" + }, + oneRPC: { + name: "1RPC", + url: "https://1rpc.io/bnb" + } + }, + tokens: { + bnb: { + instanceAddress: { + "0.1": "0x84443CFd09A48AF6eF360C6976C5392aC5023a1F", + "1": "0xd47438C816c9E7f2E2888E060936a499Af9582b3", + "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD" + }, + symbol: "BNB", + decimals: 18 + } + }, + relayerEnsSubdomain: "bsc-tornado", + pollInterval: 10, + constants: { + NOTE_ACCOUNT_BLOCK: 8159269, + ENCRYPTED_NOTES_BLOCK: 8159269 + } + }, + [137 /* POLYGON */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 100, + fast: 75, + standard: 50, + low: 30 + }, + nativeCurrency: "matic", + currencyName: "MATIC", + explorerUrl: "https://polygonscan.com", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Polygon (Matic) Network", + deployedBlock: 16257962, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornadoSubgraph: "tornadocash/matic-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + oneRpc: { + name: "1RPC", + url: "https://1rpc.io/matic" + } + }, + tokens: { + matic: { + instanceAddress: { + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD", + "1000": "0xdf231d99Ff8b6c6CBF4E9B9a945CBAcEF9339178", + "10000": "0xaf4c0B70B2Ea9FB7487C7CbB37aDa259579fe040", + "100000": "0xa5C2254e4253490C54cef0a4347fddb8f75A4998" + }, + symbol: "MATIC", + decimals: 18 + } + }, + relayerEnsSubdomain: "polygon-tornado", + pollInterval: 10, + constants: { + NOTE_ACCOUNT_BLOCK: 16257996, + ENCRYPTED_NOTES_BLOCK: 16257996 + } + }, + [10 /* OPTIMISM */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 1e-3, + fast: 1e-3, + standard: 1e-3, + low: 1e-3 + }, + nativeCurrency: "eth", + currencyName: "ETH", + explorerUrl: "https://optimistic.etherscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Optimism", + deployedBlock: 2243689, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + ovmGasPriceOracleContract: "0x420000000000000000000000000000000000000F", + tornadoSubgraph: "tornadocash/optimism-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + tornadoRPC: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/op" + }, + oneRpc: { + name: "1RPC", + url: "https://1rpc.io/op" + } + }, + tokens: { + eth: { + instanceAddress: { + "0.1": "0x84443CFd09A48AF6eF360C6976C5392aC5023a1F", + "1": "0xd47438C816c9E7f2E2888E060936a499Af9582b3", + "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD" + }, + symbol: "ETH", + decimals: 18 + } + }, + relayerEnsSubdomain: "optimism-tornado", + pollInterval: 15, + constants: { + NOTE_ACCOUNT_BLOCK: 2243694, + ENCRYPTED_NOTES_BLOCK: 2243694 + } + }, + [42161 /* ARBITRUM */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 4, + fast: 3, + standard: 2.52, + low: 2.29 + }, + nativeCurrency: "eth", + currencyName: "ETH", + explorerUrl: "https://arbiscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Arbitrum One", + deployedBlock: 3430648, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornadoSubgraph: "tornadocash/arbitrum-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + oneRpc: { + name: "1rpc", + url: "https://1rpc.io/arb" + }, + Arbitrum: { + name: "Arbitrum RPC", + url: "https://arb1.arbitrum.io/rpc" + } + }, + tokens: { + eth: { + instanceAddress: { + "0.1": "0x84443CFd09A48AF6eF360C6976C5392aC5023a1F", + "1": "0xd47438C816c9E7f2E2888E060936a499Af9582b3", + "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD" + }, + symbol: "ETH", + decimals: 18 + } + }, + relayerEnsSubdomain: "arbitrum-tornado", + pollInterval: 15, + constants: { + NOTE_ACCOUNT_BLOCK: 3430605, + ENCRYPTED_NOTES_BLOCK: 3430605 + } + }, + [100 /* GNOSIS */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 6, + fast: 5, + standard: 4, + low: 1 + }, + nativeCurrency: "xdai", + currencyName: "xDAI", + explorerUrl: "https://gnosisscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Gnosis Chain", + deployedBlock: 17754561, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornadoSubgraph: "tornadocash/xdai-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + tornadoRPC: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/gnosis" + }, + blockPi: { + name: "BlockPi", + url: "https://gnosis.blockpi.network/v1/rpc/public" + } + }, + tokens: { + xdai: { + instanceAddress: { + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD", + "1000": "0xdf231d99Ff8b6c6CBF4E9B9a945CBAcEF9339178", + "10000": "0xaf4c0B70B2Ea9FB7487C7CbB37aDa259579fe040", + "100000": "0xa5C2254e4253490C54cef0a4347fddb8f75A4998" + }, + symbol: "xDAI", + decimals: 18 + } + }, + relayerEnsSubdomain: "gnosis-tornado", + pollInterval: 15, + constants: { + NOTE_ACCOUNT_BLOCK: 17754564, + ENCRYPTED_NOTES_BLOCK: 17754564 + } + }, + [43114 /* AVALANCHE */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 225, + fast: 35, + standard: 25, + low: 25 + }, + nativeCurrency: "avax", + currencyName: "AVAX", + explorerUrl: "https://snowtrace.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Avalanche Mainnet", + deployedBlock: 4429818, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornadoSubgraph: "tornadocash/avalanche-tornado-subgraph", + subgraphs: { + theGraph + }, + rpcUrls: { + publicRpc: { + name: "Avalanche RPC", + url: "https://api.avax.network/ext/bc/C/rpc" + }, + meowRPC: { + name: "Meow RPC", + url: "https://avax.meowrpc.com" + }, + oneRPC: { + name: "OneRPC", + url: "https://1rpc.io/avax/c" + } + }, + tokens: { + avax: { + instanceAddress: { + "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD", + "500": "0xaf8d1839c3c67cf571aa74B5c12398d4901147B3" + }, + symbol: "AVAX", + decimals: 18 + } + }, + relayerEnsSubdomain: "avalanche-tornado", + pollInterval: 10, + constants: { + NOTE_ACCOUNT_BLOCK: 4429813, + ENCRYPTED_NOTES_BLOCK: 4429813 + } + }, + [11155111 /* SEPOLIA */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 2, + fast: 2, + standard: 2, + low: 2 + }, + nativeCurrency: "eth", + currencyName: "SepoliaETH", + explorerUrl: "https://sepolia.etherscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Ethereum Sepolia", + deployedBlock: 5594395, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x1572AFE6949fdF51Cb3E0856216670ae9Ee160Ee", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + tornContract: "0x3AE6667167C0f44394106E197904519D808323cA", + governanceContract: "0xe5324cD7602eeb387418e594B87aCADee08aeCAD", + stakingRewardsContract: "0x6d0018890751Efd31feb8166711B16732E2b496b", + registryContract: "0x1428e5d2356b13778A13108b10c440C83011dfB8", + aggregatorContract: "0x4088712AC9fad39ea133cdb9130E465d235e9642", + reverseRecordsContract: "0xEc29700C0283e5Be64AcdFe8077d6cC95dE23C23", + tornadoSubgraph: "tornadocash/sepolia-tornado-subgraph", + subgraphs: { + tornado + }, + rpcUrls: { + tornadoRPC: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/sepolia" + }, + sepolia: { + name: "Sepolia RPC", + url: "https://rpc.sepolia.org" + } + }, + tokens: { + eth: { + instanceAddress: { + "0.1": "0x8C4A04d872a6C1BE37964A21ba3a138525dFF50b", + "1": "0x8cc930096B4Df705A007c4A039BDFA1320Ed2508", + "10": "0x8D10d506D29Fc62ABb8A290B99F66dB27Fc43585", + "100": "0x44c5C92ed73dB43888210264f0C8b36Fd68D8379" + }, + symbol: "ETH", + decimals: 18 + }, + dai: { + instanceAddress: { + "100": "0x6921fd1a97441dd603a997ED6DDF388658daf754", + "1000": "0x50a637770F5d161999420F7d70d888DE47207145", + "10000": "0xecD649870407cD43923A816Cc6334a5bdf113621", + "100000": "0x73B4BD04bF83206B6e979BE2507098F92EDf4F90" + }, + tokenAddress: "0xFF34B3d4Aee8ddCd6F9AFFFB6Fe49bD371b8a357", + tokenGasLimit: 7e4, + symbol: "DAI", + decimals: 18, + gasLimit: 7e5 + } + }, + relayerEnsSubdomain: "sepolia-tornado", + pollInterval: 15, + constants: { + GOVERNANCE_BLOCK: 5594395, + NOTE_ACCOUNT_BLOCK: 5594395, + ENCRYPTED_NOTES_BLOCK: 5594395, + MINING_BLOCK_TIME: 15 + } + } +}; +const enabledChains = Object.values(NetId).filter((n) => typeof n === "number"); +let customConfig = {}; +function addNetwork(newConfig) { + enabledChains.push( + ...Object.keys(newConfig).map((netId) => Number(netId)).filter((netId) => !enabledChains.includes(netId)) + ); + customConfig = __spreadValues$1(__spreadValues$1({}, customConfig), newConfig); +} +function getNetworkConfig() { + const allConfig = __spreadValues$1(__spreadValues$1({}, defaultConfig), customConfig); + return enabledChains.reduce((acc, curr) => { + acc[curr] = allConfig[curr]; + return acc; + }, {}); +} +function getConfig(netId) { + const allConfig = getNetworkConfig(); + const chainConfig = allConfig[netId]; + if (!chainConfig) { + const errMsg = `No config found for network ${netId}!`; + throw new Error(errMsg); + } + return chainConfig; +} +function getInstanceByAddress({ netId, address }) { + const { tokens } = getConfig(netId); + for (const [currency, { instanceAddress }] of Object.entries(tokens)) { + for (const [amount, instance] of Object.entries(instanceAddress)) { + if (instance === address) { + return { + amount, + currency + }; + } + } + } +} +function getSubdomains() { + const allConfig = getNetworkConfig(); + return enabledChains.map((chain) => allConfig[chain].relayerEnsSubdomain); +} + +const addressType = { type: "string", pattern: "^0x[a-fA-F0-9]{40}$" }; +const bnType = { type: "string", BN: true }; +const statusSchema = { + type: "object", + properties: { + rewardAccount: addressType, + gasPrices: { + type: "object", + properties: { + fast: { type: "number" }, + additionalProperties: { type: "number" } + }, + required: ["fast"] + }, + netId: { type: "integer" }, + tornadoServiceFee: { type: "number", maximum: 20, minimum: 0 }, + latestBlock: { type: "number" }, + version: { type: "string" }, + health: { + type: "object", + properties: { + status: { const: "true" }, + error: { type: "string" } + }, + required: ["status"] + }, + currentQueue: { type: "number" } + }, + required: ["rewardAccount", "instances", "netId", "tornadoServiceFee", "version", "health"] +}; +function getStatusSchema(netId, config) { + const { tokens, optionalTokens = [], nativeCurrency } = config; + const schema = JSON.parse(JSON.stringify(statusSchema)); + const instances = Object.keys(tokens).reduce( + (acc, token) => { + const { instanceAddress, tokenAddress, symbol, decimals, optionalInstances = [] } = tokens[token]; + const amounts = Object.keys(instanceAddress); + const instanceProperties = { + type: "object", + properties: { + instanceAddress: { + type: "object", + properties: amounts.reduce((acc2, cur) => { + acc2[cur] = addressType; + return acc2; + }, {}), + required: amounts.filter((amount) => !optionalInstances.includes(amount)) + }, + decimals: { enum: [decimals] } + }, + required: ["instanceAddress", "decimals"].concat( + tokenAddress ? ["tokenAddress"] : [], + symbol ? ["symbol"] : [] + ) + }; + if (tokenAddress) { + instanceProperties.properties.tokenAddress = addressType; + } + if (symbol) { + instanceProperties.properties.symbol = { enum: [symbol] }; + } + acc.properties[token] = instanceProperties; + if (!optionalTokens.includes(token)) { + acc.required.push(token); + } + return acc; + }, + { + type: "object", + properties: {}, + required: [] + } + ); + schema.properties.instances = instances; + if (netId === NetId.MAINNET) { + const _tokens = Object.keys(tokens).filter((t) => t !== nativeCurrency); + const ethPrices = { + type: "object", + properties: _tokens.reduce((acc, token) => { + acc[token] = bnType; + return acc; + }, {}) + // required: _tokens + }; + schema.properties.ethPrices = ethPrices; + } + return schema; +} + +const jobsSchema = { + type: "object", + properties: { + error: { type: "string" }, + id: { type: "string" }, + type: { type: "string" }, + status: { type: "string" }, + contract: { type: "string" }, + proof: { type: "string" }, + args: { + type: "array", + items: { type: "string" } + }, + txHash: { type: "string" }, + confirmations: { type: "number" }, + failedReason: { type: "string" } + }, + required: ["id", "status"] +}; + +const ajv = new Ajv({ allErrors: true }); +ajv.addKeyword({ + keyword: "BN", + // eslint-disable-next-line @typescript-eslint/no-explicit-any + validate: (schema, data) => { + try { + BigInt(data); + return true; + } catch (e) { + return false; + } + }, + errors: true +}); + +const _abi$5 = [ { constant: true, inputs: [ @@ -693,15 +3699,15 @@ const _abi$6 = [ ]; class ENS__factory { static createInterface() { - return new Interface(_abi$6); + return new Interface(_abi$5); } static connect(address, runner) { - return new Contract(address, _abi$6, runner); + return new Contract(address, _abi$5, runner); } } -ENS__factory.abi = _abi$6; +ENS__factory.abi = _abi$5; -const _abi$5 = [ +const _abi$4 = [ { constant: true, inputs: [], @@ -1003,205 +4009,6 @@ const _abi$5 = [ } ]; class ERC20__factory { - static createInterface() { - return new Interface(_abi$5); - } - static connect(address, runner) { - return new Contract(address, _abi$5, runner); - } -} -ERC20__factory.abi = _abi$5; - -const _abi$4 = [ - { - inputs: [], - stateMutability: "nonpayable", - type: "constructor" - }, - { - inputs: [], - name: "GAS_UNIT", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [ - { - internalType: "uint32", - name: "_derivationThresold", - type: "uint32" - } - ], - name: "changeDerivationThresold", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [ - { - internalType: "uint32", - name: "_gasUnit", - type: "uint32" - } - ], - name: "changeGasUnit", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [ - { - internalType: "uint32", - name: "_heartbeat", - type: "uint32" - } - ], - name: "changeHeartbeat", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [ - { - internalType: "address", - name: "_owner", - type: "address" - } - ], - name: "changeOwnership", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [], - name: "derivationThresold", - outputs: [ - { - internalType: "uint32", - name: "", - type: "uint32" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [], - name: "gasPrice", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [], - name: "heartbeat", - outputs: [ - { - internalType: "uint32", - name: "", - type: "uint32" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [], - name: "maxFeePerGas", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [], - name: "maxPriorityFeePerGas", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [], - name: "owner", - outputs: [ - { - internalType: "address", - name: "", - type: "address" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [], - name: "pastGasPrice", - outputs: [ - { - internalType: "uint32", - name: "", - type: "uint32" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [ - { - internalType: "uint32", - name: "_gasPrice", - type: "uint32" - } - ], - name: "setGasPrice", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [], - name: "timestamp", - outputs: [ - { - internalType: "uint32", - name: "", - type: "uint32" - } - ], - stateMutability: "view", - type: "function" - } -]; -class GasPriceOracle__factory { static createInterface() { return new Interface(_abi$4); } @@ -1209,7 +4016,7 @@ class GasPriceOracle__factory { return new Contract(address, _abi$4, runner); } } -GasPriceOracle__factory.abi = _abi$4; +ERC20__factory.abi = _abi$4; const _abi$3 = [ { @@ -2540,1854 +5347,12 @@ var index = /*#__PURE__*/Object.freeze({ __proto__: null, ENS__factory: ENS__factory, ERC20__factory: ERC20__factory, - GasPriceOracle__factory: GasPriceOracle__factory, Multicall__factory: Multicall__factory, OffchainOracle__factory: OffchainOracle__factory, OvmGasPriceOracle__factory: OvmGasPriceOracle__factory, ReverseRecords__factory: ReverseRecords__factory }); -BigInt.prototype.toJSON = function() { - return this.toString(); -}; -const isNode = !process.browser && typeof globalThis.window === "undefined"; -const crypto = isNode ? webcrypto : globalThis.crypto; -const chunk = (arr, size) => [...Array(Math.ceil(arr.length / size))].map((_, i) => arr.slice(size * i, size + size * i)); -function sleep(ms) { - return new Promise((resolve) => setTimeout(resolve, ms)); -} -function validateUrl(url, protocols) { - try { - const parsedUrl = new URL(url); - if (protocols && protocols.length) { - return protocols.map((p) => p.toLowerCase()).includes(parsedUrl.protocol); - } - return true; - } catch (e) { - return false; - } -} -function concatBytes(...arrays) { - const totalSize = arrays.reduce((acc, e) => acc + e.length, 0); - const merged = new Uint8Array(totalSize); - arrays.forEach((array, i, arrays2) => { - const offset = arrays2.slice(0, i).reduce((acc, e) => acc + e.length, 0); - merged.set(array, offset); - }); - return merged; -} -function bufferToBytes(b) { - return new Uint8Array(b.buffer); -} -function bytesToBase64(bytes) { - return btoa(String.fromCharCode.apply(null, Array.from(bytes))); -} -function base64ToBytes(base64) { - return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)); -} -function bytesToHex(bytes) { - return "0x" + Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""); -} -function hexToBytes(hexString) { - if (hexString.slice(0, 2) === "0x") { - hexString = hexString.replace("0x", ""); - } - if (hexString.length % 2 !== 0) { - hexString = "0" + hexString; - } - return Uint8Array.from(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); -} -function bytesToBN(bytes) { - return BigInt(bytesToHex(bytes)); -} -function bnToBytes(bigint) { - let hexString = typeof bigint === "bigint" ? bigint.toString(16) : bigint; - if (hexString.startsWith("0x")) { - hexString = hexString.replace("0x", ""); - } - if (hexString.length % 2 !== 0) { - hexString = "0" + hexString; - } - return Uint8Array.from(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); -} -function leBuff2Int(bytes) { - return new BN(bytes, 16, "le"); -} -function leInt2Buff(bigint) { - return Uint8Array.from(new BN(bigint).toArray("le", 31)); -} -function toFixedHex(numberish, length = 32) { - return "0x" + BigInt(numberish).toString(16).padStart(length * 2, "0"); -} -function toFixedLength(string, length = 32) { - string = string.replace("0x", ""); - return "0x" + string.padStart(length * 2, "0"); -} -function rBigInt(nbytes = 31) { - return bytesToBN(crypto.getRandomValues(new Uint8Array(nbytes))); -} -function bigIntReplacer(key, value) { - return typeof value === "bigint" ? value.toString() : value; -} -function substring(str, length = 10) { - if (str.length < length * 2) { - return str; - } - return `${str.substring(0, length)}...${str.substring(str.length - length)}`; -} - -var __async$c = (__this, __arguments, generator) => { - return new Promise((resolve, reject) => { - var fulfilled = (value) => { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - }; - var rejected = (value) => { - try { - step(generator.throw(value)); - } catch (e) { - reject(e); - } - }; - var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); - step((generator = generator.apply(__this, __arguments)).next()); - }); -}; -function multicall(Multicall2, calls) { - return __async$c(this, null, function* () { - const calldata = calls.map((call) => { - var _a, _b, _c; - const target = ((_a = call.contract) == null ? void 0 : _a.target) || call.address; - const callInterface = ((_b = call.contract) == null ? void 0 : _b.interface) || call.interface; - return { - target, - callData: callInterface.encodeFunctionData(call.name, call.params), - allowFailure: (_c = call.allowFailure) != null ? _c : false - }; - }); - const returnData = yield Multicall2.aggregate3.staticCall(calldata); - const res = returnData.map((call, i) => { - var _a; - const callInterface = ((_a = calls[i].contract) == null ? void 0 : _a.interface) || calls[i].interface; - const [result, data] = call; - const decodeResult = result && data && data !== "0x" ? callInterface.decodeFunctionResult(calls[i].name, data) : null; - return !decodeResult ? null : decodeResult.length === 1 ? decodeResult[0] : decodeResult; - }); - return res; - }); -} - -var __defProp$4 = Object.defineProperty; -var __defProps$3 = Object.defineProperties; -var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors; -var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols; -var __getProtoOf$1 = Object.getPrototypeOf; -var __hasOwnProp$4 = Object.prototype.hasOwnProperty; -var __propIsEnum$4 = Object.prototype.propertyIsEnumerable; -var __reflectGet$1 = Reflect.get; -var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __spreadValues$4 = (a, b) => { - for (var prop in b || (b = {})) - if (__hasOwnProp$4.call(b, prop)) - __defNormalProp$4(a, prop, b[prop]); - if (__getOwnPropSymbols$4) - for (var prop of __getOwnPropSymbols$4(b)) { - if (__propIsEnum$4.call(b, prop)) - __defNormalProp$4(a, prop, b[prop]); - } - return a; -}; -var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b)); -var __superGet$1 = (cls, obj, key) => __reflectGet$1(__getProtoOf$1(cls), key, obj); -var __async$b = (__this, __arguments, generator) => { - return new Promise((resolve, reject) => { - var fulfilled = (value) => { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - }; - var rejected = (value) => { - try { - step(generator.throw(value)); - } catch (e) { - reject(e); - } - }; - var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); - step((generator = generator.apply(__this, __arguments)).next()); - }); -}; -const defaultUserAgent = "Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/115.0"; -const fetch = crossFetch; -function getHttpAgent({ - fetchUrl, - proxyUrl, - torPort, - retry -}) { - const { HttpProxyAgent } = require("http-proxy-agent"); - const { HttpsProxyAgent } = require("https-proxy-agent"); - const { SocksProxyAgent } = require("socks-proxy-agent"); - if (torPort) { - return new SocksProxyAgent(`socks5h://tor${retry}@127.0.0.1:${torPort}`); - } - if (!proxyUrl) { - return; - } - const isHttps = fetchUrl.includes("https://"); - if (proxyUrl.includes("socks://") || proxyUrl.includes("socks4://") || proxyUrl.includes("socks5://")) { - return new SocksProxyAgent(proxyUrl); - } - if (proxyUrl.includes("http://") || proxyUrl.includes("https://")) { - if (isHttps) { - return new HttpsProxyAgent(proxyUrl); - } - return new HttpProxyAgent(proxyUrl); - } -} -function fetchData(_0) { - return __async$b(this, arguments, function* (url, options = {}) { - var _a, _b, _c; - const MAX_RETRY = (_a = options.maxRetry) != null ? _a : 3; - const RETRY_ON = (_b = options.retryOn) != null ? _b : 500; - const userAgent = (_c = options.userAgent) != null ? _c : defaultUserAgent; - let retry = 0; - let errorObject; - if (!options.method) { - if (!options.body) { - options.method = "GET"; - } else { - options.method = "POST"; - } - } - if (!options.headers) { - options.headers = {}; - } - if (isNode && !options.headers["User-Agent"]) { - options.headers["User-Agent"] = userAgent; - } - while (retry < MAX_RETRY + 1) { - let timeout; - if (!options.signal && options.timeout) { - const controller = new AbortController(); - options.signal = controller.signal; - timeout = setTimeout(() => { - controller.abort(); - }, options.timeout); - } - if (!options.agent && isNode && (options.proxy || options.torPort)) { - options.agent = getHttpAgent({ - fetchUrl: url, - proxyUrl: options.proxy, - torPort: options.torPort, - retry - }); - } - if (options.debug && typeof options.debug === "function") { - options.debug("request", { - url, - retry, - errorObject, - options - }); - } - try { - const resp = yield fetch(url, { - method: options.method, - headers: options.headers, - body: options.body, - redirect: options.redirect, - signal: options.signal, - agent: options.agent - }); - if (options.debug && typeof options.debug === "function") { - options.debug("response", resp); - } - if (!resp.ok) { - const errMsg = `Request to ${url} failed with error code ${resp.status}: -` + (yield resp.text()); - throw new Error(errMsg); - } - if (options.returnResponse) { - return resp; - } - const contentType = resp.headers.get("content-type"); - if (contentType == null ? void 0 : contentType.includes("application/json")) { - return yield resp.json(); - } - if (contentType == null ? void 0 : contentType.includes("text")) { - return yield resp.text(); - } - return resp; - } catch (error) { - if (timeout) { - clearTimeout(timeout); - } - errorObject = error; - retry++; - yield sleep(RETRY_ON); - } finally { - if (timeout) { - clearTimeout(timeout); - } - } - } - if (options.debug && typeof options.debug === "function") { - options.debug("error", errorObject); - } - throw errorObject; - }); -} -const fetchGetUrlFunc = (options = {}) => (req, _signal) => __async$b(void 0, null, function* () { - let signal; - if (_signal) { - const controller = new AbortController(); - signal = controller.signal; - _signal.addListener(() => { - controller.abort(); - }); - } - const init = __spreadProps$3(__spreadValues$4({}, options), { - method: req.method || "POST", - headers: req.headers, - body: req.body || void 0, - signal, - returnResponse: true - }); - const resp = yield fetchData(req.url, init); - const headers = {}; - resp.headers.forEach((value, key) => { - headers[key.toLowerCase()] = value; - }); - const respBody = yield resp.arrayBuffer(); - const body = respBody == null ? null : new Uint8Array(respBody); - return { - statusCode: resp.status, - statusMessage: resp.statusText, - headers, - body - }; -}); -const oracleMapper = /* @__PURE__ */ new Map(); -const multicallMapper = /* @__PURE__ */ new Map(); -function getGasOraclePlugin(networkKey, fetchOptions) { - const gasStationApi = (fetchOptions == null ? void 0 : fetchOptions.gasStationApi) || "https://gasstation.polygon.technology/v2"; - return new FetchUrlFeeDataNetworkPlugin(gasStationApi, (fetchFeeData, provider, request) => __async$b(this, null, function* () { - if (!oracleMapper.has(networkKey)) { - oracleMapper.set(networkKey, GasPriceOracle__factory.connect(fetchOptions == null ? void 0 : fetchOptions.gasPriceOracle, provider)); - } - if (!multicallMapper.has(networkKey)) { - multicallMapper.set( - networkKey, - Multicall__factory.connect("0xcA11bde05977b3631167028862bE2a173976CA11", provider) - ); - } - const Oracle = oracleMapper.get(networkKey); - const Multicall2 = multicallMapper.get(networkKey); - const [timestamp, heartbeat, feePerGas, priorityFeePerGas] = yield multicall(Multicall2, [ - { - contract: Oracle, - name: "timestamp" - }, - { - contract: Oracle, - name: "heartbeat" - }, - { - contract: Oracle, - name: "maxFeePerGas" - }, - { - contract: Oracle, - name: "maxPriorityFeePerGas" - } - ]); - const isOutdated = Number(timestamp) <= Date.now() / 1e3 - Number(heartbeat); - if (!isOutdated) { - const maxPriorityFeePerGas = priorityFeePerGas * BigInt(13) / BigInt(10); - const maxFeePerGas = feePerGas * BigInt(2) + maxPriorityFeePerGas; - return { - gasPrice: maxFeePerGas, - maxFeePerGas, - maxPriorityFeePerGas - }; - } - const fetchReq = new FetchRequest(gasStationApi); - fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); - if (isNode) { - fetchReq.setHeader("User-Agent", "ethers"); - } - const [ - { - bodyJson: { fast } - }, - { gasPrice } - ] = yield Promise.all([fetchReq.send(), fetchFeeData()]); - return { - gasPrice, - maxFeePerGas: parseUnits(`${fast.maxFee}`, 9), - maxPriorityFeePerGas: parseUnits(`${fast.maxPriorityFee}`, 9) - }; - })); -} -function getProvider(rpcUrl, fetchOptions) { - return __async$b(this, null, function* () { - const fetchReq = new FetchRequest(rpcUrl); - fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); - const _staticNetwork = yield new JsonRpcProvider(fetchReq).getNetwork(); - const ensPlugin = _staticNetwork.getPlugin("org.ethers.plugins.network.Ens"); - const gasCostPlugin = _staticNetwork.getPlugin("org.ethers.plugins.network.GasCost"); - const gasStationPlugin = _staticNetwork.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin"); - const staticNetwork = new Network(_staticNetwork.name, _staticNetwork.chainId); - if (ensPlugin) { - staticNetwork.attachPlugin(ensPlugin); - } - if (gasCostPlugin) { - staticNetwork.attachPlugin(gasCostPlugin); - } - if (fetchOptions == null ? void 0 : fetchOptions.gasPriceOracle) { - staticNetwork.attachPlugin(getGasOraclePlugin(`${_staticNetwork.chainId}_${rpcUrl}`, fetchOptions)); - } else if (gasStationPlugin) { - staticNetwork.attachPlugin(gasStationPlugin); - } - const provider = new JsonRpcProvider(fetchReq, staticNetwork, { - staticNetwork - }); - provider.pollingInterval = (fetchOptions == null ? void 0 : fetchOptions.pollingInterval) || 1e3; - return provider; - }); -} -function getProviderWithNetId(netId, rpcUrl, config, fetchOptions) { - const { networkName, reverseRecordsContract, gasPriceOracleContract, gasStationApi, pollInterval } = config; - const hasEns = Boolean(reverseRecordsContract); - const fetchReq = new FetchRequest(rpcUrl); - fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); - const staticNetwork = new Network(networkName, netId); - if (hasEns) { - staticNetwork.attachPlugin(new EnsPlugin(null, Number(netId))); - } - staticNetwork.attachPlugin(new GasCostPlugin()); - if (gasPriceOracleContract) { - staticNetwork.attachPlugin( - getGasOraclePlugin(`${netId}_${rpcUrl}`, { - gasPriceOracle: gasPriceOracleContract, - gasStationApi - }) - ); - } - const provider = new JsonRpcProvider(fetchReq, staticNetwork, { - staticNetwork - }); - provider.pollingInterval = (fetchOptions == null ? void 0 : fetchOptions.pollingInterval) || pollInterval * 1e3; - return provider; -} -const populateTransaction = (signer, tx) => __async$b(void 0, null, function* () { - const provider = signer.provider; - if (!tx.from) { - tx.from = signer.address; - } else if (tx.from !== signer.address) { - const errMsg = `populateTransaction: signer mismatch for tx, wants ${tx.from} have ${signer.address}`; - throw new Error(errMsg); - } - const [feeData, nonce] = yield Promise.all([ - (() => __async$b(void 0, null, function* () { - if (tx.maxFeePerGas && tx.maxPriorityFeePerGas) { - return new FeeData(null, BigInt(tx.maxFeePerGas), BigInt(tx.maxPriorityFeePerGas)); - } - if (tx.gasPrice) { - return new FeeData(BigInt(tx.gasPrice), null, null); - } - const fetchedFeeData = yield provider.getFeeData(); - if (fetchedFeeData.maxFeePerGas && fetchedFeeData.maxPriorityFeePerGas) { - return new FeeData( - null, - fetchedFeeData.maxFeePerGas * (BigInt(1e4) + BigInt(signer.gasPriceBump)) / BigInt(1e4), - fetchedFeeData.maxPriorityFeePerGas - ); - } else { - return new FeeData( - fetchedFeeData.gasPrice * (BigInt(1e4) + BigInt(signer.gasPriceBump)) / BigInt(1e4), - null, - null - ); - } - }))(), - (() => __async$b(void 0, null, function* () { - if (tx.nonce) { - return tx.nonce; - } - let fetchedNonce = yield provider.getTransactionCount(signer.address, "pending"); - if (signer.bumpNonce && signer.nonce && signer.nonce >= fetchedNonce) { - console.log( - `populateTransaction: bumping nonce from ${fetchedNonce} to ${fetchedNonce + 1} for ${signer.address}` - ); - fetchedNonce++; - } - return fetchedNonce; - }))() - ]); - tx.nonce = nonce; - if (feeData.maxFeePerGas && feeData.maxPriorityFeePerGas) { - tx.maxFeePerGas = feeData.maxFeePerGas; - tx.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; - if (!tx.type) { - tx.type = 2; - } - delete tx.gasPrice; - } else if (feeData.gasPrice) { - tx.gasPrice = feeData.gasPrice; - if (!tx.type) { - tx.type = 0; - } - delete tx.maxFeePerGas; - delete tx.maxPriorityFeePerGas; - } - tx.gasLimit = tx.gasLimit || (yield (() => __async$b(void 0, null, function* () { - try { - const gasLimit = yield provider.estimateGas(tx); - return gasLimit === BigInt(21e3) ? gasLimit : gasLimit * (BigInt(1e4) + BigInt(signer.gasLimitBump)) / BigInt(1e4); - } catch (err) { - if (signer.gasFailover) { - console.log("populateTransaction: warning gas estimation failed falling back to 3M gas"); - return BigInt("3000000"); - } - throw err; - } - }))()); - return tx; -}); -class TornadoWallet extends Wallet { - constructor(key, provider, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce } = {}) { - super(key, provider); - this.gasPriceBump = gasPriceBump != null ? gasPriceBump : 0; - this.gasLimitBump = gasLimitBump != null ? gasLimitBump : 3e3; - this.gasFailover = gasFailover != null ? gasFailover : false; - this.bumpNonce = bumpNonce != null ? bumpNonce : false; - } - static fromMnemonic(mneomnic, provider, index = 0, options) { - const defaultPath = `m/44'/60'/0'/0/${index}`; - const { privateKey } = HDNodeWallet.fromPhrase(mneomnic, void 0, defaultPath); - return new TornadoWallet(privateKey, provider, options); - } - populateTransaction(tx) { - return __async$b(this, null, function* () { - const txObject = yield populateTransaction(this, tx); - this.nonce = txObject.nonce; - return __superGet$1(TornadoWallet.prototype, this, "populateTransaction").call(this, txObject); - }); - } -} -class TornadoVoidSigner extends VoidSigner { - constructor(address, provider, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce } = {}) { - super(address, provider); - this.gasPriceBump = gasPriceBump != null ? gasPriceBump : 0; - this.gasLimitBump = gasLimitBump != null ? gasLimitBump : 3e3; - this.gasFailover = gasFailover != null ? gasFailover : false; - this.bumpNonce = bumpNonce != null ? bumpNonce : false; - } - populateTransaction(tx) { - return __async$b(this, null, function* () { - const txObject = yield populateTransaction(this, tx); - this.nonce = txObject.nonce; - return __superGet$1(TornadoVoidSigner.prototype, this, "populateTransaction").call(this, txObject); - }); - } -} -class TornadoRpcSigner extends JsonRpcSigner { - constructor(provider, address, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce } = {}) { - super(provider, address); - this.gasPriceBump = gasPriceBump != null ? gasPriceBump : 0; - this.gasLimitBump = gasLimitBump != null ? gasLimitBump : 3e3; - this.gasFailover = gasFailover != null ? gasFailover : false; - this.bumpNonce = bumpNonce != null ? bumpNonce : false; - } - sendUncheckedTransaction(tx) { - return __async$b(this, null, function* () { - return __superGet$1(TornadoRpcSigner.prototype, this, "sendUncheckedTransaction").call(this, yield populateTransaction(this, tx)); - }); - } -} -class TornadoBrowserProvider extends BrowserProvider { - constructor(ethereum, network, options) { - super(ethereum, network); - this.options = options; - } - getSigner(address) { - return __async$b(this, null, function* () { - var _a, _b, _c, _d, _e, _f, _g, _h, _i; - const signerAddress = (yield __superGet$1(TornadoBrowserProvider.prototype, this, "getSigner").call(this, address)).address; - if (((_a = this.options) == null ? void 0 : _a.webChainId) && ((_b = this.options) == null ? void 0 : _b.connectWallet) && Number(yield __superGet$1(TornadoBrowserProvider.prototype, this, "send").call(this, "eth_chainId", [])) !== Number((_c = this.options) == null ? void 0 : _c.webChainId)) { - yield this.options.connectWallet(); - } - if ((_d = this.options) == null ? void 0 : _d.handleNetworkChanges) { - (_e = window == null ? void 0 : window.ethereum) == null ? void 0 : _e.on("chainChanged", this.options.handleNetworkChanges); - } - if ((_f = this.options) == null ? void 0 : _f.handleAccountChanges) { - (_g = window == null ? void 0 : window.ethereum) == null ? void 0 : _g.on("accountsChanged", this.options.handleAccountChanges); - } - if ((_h = this.options) == null ? void 0 : _h.handleAccountDisconnect) { - (_i = window == null ? void 0 : window.ethereum) == null ? void 0 : _i.on("disconnect", this.options.handleAccountDisconnect); - } - return new TornadoRpcSigner(this, signerAddress, this.options); - }); - } -} - -const GET_STATISTIC = ` - query getStatistic($currency: String!, $amount: String!, $first: Int, $orderBy: BigInt, $orderDirection: String) { - deposits(first: $first, orderBy: $orderBy, orderDirection: $orderDirection, where: { currency: $currency, amount: $amount }) { - index - timestamp - blockNumber - } - _meta { - block { - number - } - hasIndexingErrors - } - } -`; -const _META = ` - query getMeta { - _meta { - block { - number - } - hasIndexingErrors - } - } -`; -const GET_REGISTERED = ` - query getRegistered($first: Int, $fromBlock: Int) { - relayers(first: $first, orderBy: blockRegistration, orderDirection: asc, where: { - blockRegistration_gte: $fromBlock - }) { - id - address - ensName - blockRegistration - } - _meta { - block { - number - } - hasIndexingErrors - } - } -`; -const GET_DEPOSITS = ` - query getDeposits($currency: String!, $amount: String!, $first: Int, $fromBlock: Int) { - deposits(first: $first, orderBy: index, orderDirection: asc, where: { - amount: $amount, - currency: $currency, - blockNumber_gte: $fromBlock - }) { - id - blockNumber - commitment - index - timestamp - from - } - _meta { - block { - number - } - hasIndexingErrors - } - } -`; -const GET_WITHDRAWALS = ` - query getWithdrawals($currency: String!, $amount: String!, $first: Int, $fromBlock: Int!) { - withdrawals(first: $first, orderBy: blockNumber, orderDirection: asc, where: { - currency: $currency, - amount: $amount, - blockNumber_gte: $fromBlock - }) { - id - blockNumber - nullifier - to - fee - timestamp - } - _meta { - block { - number - } - hasIndexingErrors - } - } -`; -const GET_NOTE_ACCOUNTS = ` - query getNoteAccount($address: String!) { - noteAccounts(where: { address: $address }) { - id - index - address - encryptedAccount - } - _meta { - block { - number - } - hasIndexingErrors - } - } -`; -const GET_ECHO_EVENTS = ` - query getNoteAccounts($first: Int, $fromBlock: Int) { - noteAccounts(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { - id - blockNumber - address - encryptedAccount - } - _meta { - block { - number - } - hasIndexingErrors - } - } -`; -const GET_ENCRYPTED_NOTES = ` - query getEncryptedNotes($first: Int, $fromBlock: Int) { - encryptedNotes(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { - blockNumber - index - transactionHash - encryptedNote - } - _meta { - block { - number - } - hasIndexingErrors - } - } -`; -const GET_GOVERNANCE_EVENTS = ` - query getGovernanceEvents($first: Int, $fromBlock: Int) { - proposals(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { - blockNumber - logIndex - transactionHash - proposalId - proposer - target - startTime - endTime - description - } - votes(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { - blockNumber - logIndex - transactionHash - proposalId - voter - support - votes - from - input - } - delegates(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { - blockNumber - logIndex - transactionHash - account - delegateTo - } - undelegates(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { - blockNumber - logIndex - transactionHash - account - delegateFrom - } - _meta { - block { - number - } - hasIndexingErrors - } - } -`; -const GET_GOVERNANCE_APY = ` - stakeDailyBurns(first: 30, orderBy: date, orderDirection: desc) { - id - date - dailyAmountBurned - } -`; - -var __defProp$3 = Object.defineProperty; -var __defProps$2 = Object.defineProperties; -var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors; -var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols; -var __hasOwnProp$3 = Object.prototype.hasOwnProperty; -var __propIsEnum$3 = Object.prototype.propertyIsEnumerable; -var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __spreadValues$3 = (a, b) => { - for (var prop in b || (b = {})) - if (__hasOwnProp$3.call(b, prop)) - __defNormalProp$3(a, prop, b[prop]); - if (__getOwnPropSymbols$3) - for (var prop of __getOwnPropSymbols$3(b)) { - if (__propIsEnum$3.call(b, prop)) - __defNormalProp$3(a, prop, b[prop]); - } - return a; -}; -var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b)); -var __async$a = (__this, __arguments, generator) => { - return new Promise((resolve, reject) => { - var fulfilled = (value) => { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - }; - var rejected = (value) => { - try { - step(generator.throw(value)); - } catch (e) { - reject(e); - } - }; - var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); - step((generator = generator.apply(__this, __arguments)).next()); - }); -}; -const isEmptyArray = (arr) => !Array.isArray(arr) || !arr.length; -const GRAPHQL_LIMIT = 1e3; -function queryGraph(_0) { - return __async$a(this, arguments, function* ({ - graphApi, - subgraphName, - query, - variables, - fetchDataOptions: fetchDataOptions2 - }) { - var _a; - const graphUrl = `${graphApi}/subgraphs/name/${subgraphName}`; - const { data, errors } = yield fetchData(graphUrl, __spreadProps$2(__spreadValues$3({}, fetchDataOptions2), { - method: "POST", - headers: { - "Content-Type": "application/json" - }, - body: JSON.stringify({ - query, - variables - }) - })); - if (errors) { - throw new Error(JSON.stringify(errors)); - } - if ((_a = data == null ? void 0 : data._meta) == null ? void 0 : _a.hasIndexingErrors) { - throw new Error("Subgraph has indexing errors"); - } - return data; - }); -} -function getStatistic(_0) { - return __async$a(this, arguments, function* ({ - graphApi, - subgraphName, - currency, - amount, - fetchDataOptions: fetchDataOptions2 - }) { - try { - const { - deposits, - _meta: { - block: { number: lastSyncBlock } - } - } = yield queryGraph({ - graphApi, - subgraphName, - query: GET_STATISTIC, - variables: { - currency, - first: 10, - orderBy: "index", - orderDirection: "desc", - amount - }, - fetchDataOptions: fetchDataOptions2 - }); - const events = deposits.map((e) => ({ - timestamp: Number(e.timestamp), - leafIndex: Number(e.index), - blockNumber: Number(e.blockNumber) - })).reverse(); - const [lastEvent] = events.slice(-1); - return { - events, - lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock - }; - } catch (err) { - console.log("Error from getStatistic query"); - console.log(err); - return { - events: [], - lastSyncBlock: null - }; - } - }); -} -function getMeta(_0) { - return __async$a(this, arguments, function* ({ graphApi, subgraphName, fetchDataOptions: fetchDataOptions2 }) { - try { - const { - _meta: { - block: { number: lastSyncBlock }, - hasIndexingErrors - } - } = yield queryGraph({ - graphApi, - subgraphName, - query: _META, - fetchDataOptions: fetchDataOptions2 - }); - return { - lastSyncBlock, - hasIndexingErrors - }; - } catch (err) { - console.log("Error from getMeta query"); - console.log(err); - return { - lastSyncBlock: null, - hasIndexingErrors: null - }; - } - }); -} -function getRegisters({ - graphApi, - subgraphName, - fromBlock, - fetchDataOptions: fetchDataOptions2 -}) { - return queryGraph({ - graphApi, - subgraphName, - query: GET_REGISTERED, - variables: { - first: GRAPHQL_LIMIT, - fromBlock - }, - fetchDataOptions: fetchDataOptions2 - }); -} -function getAllRegisters(_0) { - return __async$a(this, arguments, function* ({ - graphApi, - subgraphName, - fromBlock, - fetchDataOptions: fetchDataOptions2, - onProgress - }) { - try { - const events = []; - let lastSyncBlock = fromBlock; - while (true) { - let { - relayers: result2, - _meta: { - // eslint-disable-next-line prefer-const - block: { number: currentBlock } - } - } = yield getRegisters({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); - lastSyncBlock = currentBlock; - if (isEmptyArray(result2)) { - break; - } - const [firstEvent] = result2; - const [lastEvent] = result2.slice(-1); - if (typeof onProgress === "function") { - onProgress({ - type: "Registers", - fromBlock: Number(firstEvent.blockRegistration), - toBlock: Number(lastEvent.blockRegistration), - count: result2.length - }); - } - if (result2.length < 900) { - events.push(...result2); - break; - } - result2 = result2.filter(({ blockRegistration }) => blockRegistration !== lastEvent.blockRegistration); - fromBlock = Number(lastEvent.blockRegistration); - events.push(...result2); - } - if (!events.length) { - return { - events: [], - lastSyncBlock - }; - } - const result = events.map(({ id, address, ensName, blockRegistration }) => { - const [transactionHash, logIndex] = id.split("-"); - return { - blockNumber: Number(blockRegistration), - logIndex: Number(logIndex), - transactionHash, - ensName, - relayerAddress: getAddress(address) - }; - }); - return { - events: result, - lastSyncBlock - }; - } catch (err) { - console.log("Error from getAllRegisters query"); - console.log(err); - return { events: [], lastSyncBlock: fromBlock }; - } - }); -} -function getDeposits({ - graphApi, - subgraphName, - currency, - amount, - fromBlock, - fetchDataOptions: fetchDataOptions2 -}) { - return queryGraph({ - graphApi, - subgraphName, - query: GET_DEPOSITS, - variables: { - currency, - amount, - first: GRAPHQL_LIMIT, - fromBlock - }, - fetchDataOptions: fetchDataOptions2 - }); -} -function getAllDeposits(_0) { - return __async$a(this, arguments, function* ({ - graphApi, - subgraphName, - currency, - amount, - fromBlock, - fetchDataOptions: fetchDataOptions2, - onProgress - }) { - try { - const events = []; - let lastSyncBlock = fromBlock; - while (true) { - let { - deposits: result2, - _meta: { - // eslint-disable-next-line prefer-const - block: { number: currentBlock } - } - } = yield getDeposits({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions: fetchDataOptions2 }); - lastSyncBlock = currentBlock; - if (isEmptyArray(result2)) { - break; - } - const [firstEvent] = result2; - const [lastEvent2] = result2.slice(-1); - if (typeof onProgress === "function") { - onProgress({ - type: "Deposits", - fromBlock: Number(firstEvent.blockNumber), - toBlock: Number(lastEvent2.blockNumber), - count: result2.length - }); - } - if (result2.length < 900) { - events.push(...result2); - break; - } - result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); - fromBlock = Number(lastEvent2.blockNumber); - events.push(...result2); - } - if (!events.length) { - return { - events: [], - lastSyncBlock - }; - } - const result = events.map(({ id, blockNumber, commitment, index, timestamp, from }) => { - const [transactionHash, logIndex] = id.split("-"); - return { - blockNumber: Number(blockNumber), - logIndex: Number(logIndex), - transactionHash, - commitment, - leafIndex: Number(index), - timestamp: Number(timestamp), - from: getAddress(from) - }; - }); - const [lastEvent] = result.slice(-1); - return { - events: result, - lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock - }; - } catch (err) { - console.log("Error from getAllDeposits query"); - console.log(err); - return { - events: [], - lastSyncBlock: fromBlock - }; - } - }); -} -function getWithdrawals({ - graphApi, - subgraphName, - currency, - amount, - fromBlock, - fetchDataOptions: fetchDataOptions2 -}) { - return queryGraph({ - graphApi, - subgraphName, - query: GET_WITHDRAWALS, - variables: { - currency, - amount, - first: GRAPHQL_LIMIT, - fromBlock - }, - fetchDataOptions: fetchDataOptions2 - }); -} -function getAllWithdrawals(_0) { - return __async$a(this, arguments, function* ({ - graphApi, - subgraphName, - currency, - amount, - fromBlock, - fetchDataOptions: fetchDataOptions2, - onProgress - }) { - try { - const events = []; - let lastSyncBlock = fromBlock; - while (true) { - let { - withdrawals: result2, - _meta: { - // eslint-disable-next-line prefer-const - block: { number: currentBlock } - } - } = yield getWithdrawals({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions: fetchDataOptions2 }); - lastSyncBlock = currentBlock; - if (isEmptyArray(result2)) { - break; - } - const [firstEvent] = result2; - const [lastEvent2] = result2.slice(-1); - if (typeof onProgress === "function") { - onProgress({ - type: "Withdrawals", - fromBlock: Number(firstEvent.blockNumber), - toBlock: Number(lastEvent2.blockNumber), - count: result2.length - }); - } - if (result2.length < 900) { - events.push(...result2); - break; - } - result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); - fromBlock = Number(lastEvent2.blockNumber); - events.push(...result2); - } - if (!events.length) { - return { - events: [], - lastSyncBlock - }; - } - const result = events.map(({ id, blockNumber, nullifier, to, fee, timestamp }) => { - const [transactionHash, logIndex] = id.split("-"); - return { - blockNumber: Number(blockNumber), - logIndex: Number(logIndex), - transactionHash, - nullifierHash: nullifier, - to: getAddress(to), - fee, - timestamp: Number(timestamp) - }; - }); - const [lastEvent] = result.slice(-1); - return { - events: result, - lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock - }; - } catch (err) { - console.log("Error from getAllWithdrawals query"); - console.log(err); - return { - events: [], - lastSyncBlock: fromBlock - }; - } - }); -} -function getNoteAccounts(_0) { - return __async$a(this, arguments, function* ({ - graphApi, - subgraphName, - address, - fetchDataOptions: fetchDataOptions2 - }) { - try { - const { - noteAccounts: events, - _meta: { - block: { number: lastSyncBlock } - } - } = yield queryGraph({ - graphApi, - subgraphName, - query: GET_NOTE_ACCOUNTS, - variables: { - address: address.toLowerCase() - }, - fetchDataOptions: fetchDataOptions2 - }); - return { - events, - lastSyncBlock - }; - } catch (err) { - console.log("Error from getNoteAccounts query"); - console.log(err); - return { - events: [], - lastSyncBlock: null - }; - } - }); -} -function getGraphEchoEvents({ - graphApi, - subgraphName, - fromBlock, - fetchDataOptions: fetchDataOptions2 -}) { - return queryGraph({ - graphApi, - subgraphName, - query: GET_ECHO_EVENTS, - variables: { - first: GRAPHQL_LIMIT, - fromBlock - }, - fetchDataOptions: fetchDataOptions2 - }); -} -function getAllGraphEchoEvents(_0) { - return __async$a(this, arguments, function* ({ - graphApi, - subgraphName, - fromBlock, - fetchDataOptions: fetchDataOptions2, - onProgress - }) { - try { - const events = []; - let lastSyncBlock = fromBlock; - while (true) { - let { - noteAccounts: result2, - _meta: { - // eslint-disable-next-line prefer-const - block: { number: currentBlock } - } - } = yield getGraphEchoEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); - lastSyncBlock = currentBlock; - if (isEmptyArray(result2)) { - break; - } - const [firstEvent] = result2; - const [lastEvent2] = result2.slice(-1); - if (typeof onProgress === "function") { - onProgress({ - type: "EchoEvents", - fromBlock: Number(firstEvent.blockNumber), - toBlock: Number(lastEvent2.blockNumber), - count: result2.length - }); - } - if (result2.length < 900) { - events.push(...result2); - break; - } - result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); - fromBlock = Number(lastEvent2.blockNumber); - events.push(...result2); - } - if (!events.length) { - return { - events: [], - lastSyncBlock - }; - } - const result = events.map((e) => { - const [transactionHash, logIndex] = e.id.split("-"); - return { - blockNumber: Number(e.blockNumber), - logIndex: Number(logIndex), - transactionHash, - address: getAddress(e.address), - encryptedAccount: e.encryptedAccount - }; - }); - const [lastEvent] = result.slice(-1); - return { - events: result, - lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock - }; - } catch (err) { - console.log("Error from getAllGraphEchoEvents query"); - console.log(err); - return { - events: [], - lastSyncBlock: fromBlock - }; - } - }); -} -function getEncryptedNotes({ - graphApi, - subgraphName, - fromBlock, - fetchDataOptions: fetchDataOptions2 -}) { - return queryGraph({ - graphApi, - subgraphName, - query: GET_ENCRYPTED_NOTES, - variables: { - first: GRAPHQL_LIMIT, - fromBlock - }, - fetchDataOptions: fetchDataOptions2 - }); -} -function getAllEncryptedNotes(_0) { - return __async$a(this, arguments, function* ({ - graphApi, - subgraphName, - fromBlock, - fetchDataOptions: fetchDataOptions2, - onProgress - }) { - try { - const events = []; - let lastSyncBlock = fromBlock; - while (true) { - let { - encryptedNotes: result2, - _meta: { - // eslint-disable-next-line prefer-const - block: { number: currentBlock } - } - } = yield getEncryptedNotes({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); - lastSyncBlock = currentBlock; - if (isEmptyArray(result2)) { - break; - } - const [firstEvent] = result2; - const [lastEvent2] = result2.slice(-1); - if (typeof onProgress === "function") { - onProgress({ - type: "EncryptedNotes", - fromBlock: Number(firstEvent.blockNumber), - toBlock: Number(lastEvent2.blockNumber), - count: result2.length - }); - } - if (result2.length < 900) { - events.push(...result2); - break; - } - result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); - fromBlock = Number(lastEvent2.blockNumber); - events.push(...result2); - } - if (!events.length) { - return { - events: [], - lastSyncBlock - }; - } - const result = events.map((e) => ({ - blockNumber: Number(e.blockNumber), - logIndex: Number(e.index), - transactionHash: e.transactionHash, - encryptedNote: e.encryptedNote - })); - const [lastEvent] = result.slice(-1); - return { - events: result, - lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock - }; - } catch (err) { - console.log("Error from getAllEncryptedNotes query"); - console.log(err); - return { - events: [], - lastSyncBlock: fromBlock - }; - } - }); -} -function getGovernanceEvents({ - graphApi, - subgraphName, - fromBlock, - fetchDataOptions: fetchDataOptions2 -}) { - return queryGraph({ - graphApi, - subgraphName, - query: GET_GOVERNANCE_EVENTS, - variables: { - first: GRAPHQL_LIMIT, - fromBlock - }, - fetchDataOptions: fetchDataOptions2 - }); -} -function getAllGovernanceEvents(_0) { - return __async$a(this, arguments, function* ({ - graphApi, - subgraphName, - fromBlock, - fetchDataOptions: fetchDataOptions2, - onProgress - }) { - try { - const result = []; - let lastSyncBlock = fromBlock; - while (true) { - const { - proposals, - votes, - delegates, - undelegates, - _meta: { - block: { number: currentBlock } - } - } = yield getGovernanceEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); - lastSyncBlock = currentBlock; - const eventsLength = proposals.length + votes.length + delegates.length + undelegates.length; - if (eventsLength === 0) { - break; - } - const formattedProposals = proposals.map( - ({ blockNumber, logIndex, transactionHash, proposalId, proposer, target, startTime, endTime, description }) => { - return { - blockNumber: Number(blockNumber), - logIndex: Number(logIndex), - transactionHash, - event: "ProposalCreated", - id: Number(proposalId), - proposer: getAddress(proposer), - target: getAddress(target), - startTime: Number(startTime), - endTime: Number(endTime), - description - }; - } - ); - const formattedVotes = votes.map( - ({ blockNumber, logIndex, transactionHash, proposalId, voter, support, votes: votes2, from, input }) => { - if (!input || input.length > 2048) { - input = ""; - } - return { - blockNumber: Number(blockNumber), - logIndex: Number(logIndex), - transactionHash, - event: "Voted", - proposalId: Number(proposalId), - voter: getAddress(voter), - support, - votes: votes2, - from: getAddress(from), - input - }; - } - ); - const formattedDelegates = delegates.map( - ({ blockNumber, logIndex, transactionHash, account, delegateTo }) => { - return { - blockNumber: Number(blockNumber), - logIndex: Number(logIndex), - transactionHash, - event: "Delegated", - account: getAddress(account), - delegateTo: getAddress(delegateTo) - }; - } - ); - const formattedUndelegates = undelegates.map( - ({ blockNumber, logIndex, transactionHash, account, delegateFrom }) => { - return { - blockNumber: Number(blockNumber), - logIndex: Number(logIndex), - transactionHash, - event: "Undelegated", - account: getAddress(account), - delegateFrom: getAddress(delegateFrom) - }; - } - ); - let formattedEvents = [ - ...formattedProposals, - ...formattedVotes, - ...formattedDelegates, - ...formattedUndelegates - ].sort((a, b) => { - if (a.blockNumber === b.blockNumber) { - return a.logIndex - b.logIndex; - } - return a.blockNumber - b.blockNumber; - }); - if (eventsLength < 900) { - result.push(...formattedEvents); - break; - } - const [firstEvent] = formattedEvents; - const [lastEvent2] = formattedEvents.slice(-1); - if (typeof onProgress === "function") { - onProgress({ - type: "Governance Events", - fromBlock: Number(firstEvent.blockNumber), - toBlock: Number(lastEvent2.blockNumber), - count: eventsLength - }); - } - formattedEvents = formattedEvents.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); - fromBlock = Number(lastEvent2.blockNumber); - result.push(...formattedEvents); - } - const [lastEvent] = result.slice(-1); - return { - events: result, - lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock - }; - } catch (err) { - console.log("Error from getAllGovernance query"); - console.log(err); - return { - events: [], - lastSyncBlock: fromBlock - }; - } - }); -} - -var graph = /*#__PURE__*/Object.freeze({ - __proto__: null, - GET_DEPOSITS: GET_DEPOSITS, - GET_ECHO_EVENTS: GET_ECHO_EVENTS, - GET_ENCRYPTED_NOTES: GET_ENCRYPTED_NOTES, - GET_GOVERNANCE_APY: GET_GOVERNANCE_APY, - GET_GOVERNANCE_EVENTS: GET_GOVERNANCE_EVENTS, - GET_NOTE_ACCOUNTS: GET_NOTE_ACCOUNTS, - GET_REGISTERED: GET_REGISTERED, - GET_STATISTIC: GET_STATISTIC, - GET_WITHDRAWALS: GET_WITHDRAWALS, - _META: _META, - getAllDeposits: getAllDeposits, - getAllEncryptedNotes: getAllEncryptedNotes, - getAllGovernanceEvents: getAllGovernanceEvents, - getAllGraphEchoEvents: getAllGraphEchoEvents, - getAllRegisters: getAllRegisters, - getAllWithdrawals: getAllWithdrawals, - getDeposits: getDeposits, - getEncryptedNotes: getEncryptedNotes, - getGovernanceEvents: getGovernanceEvents, - getGraphEchoEvents: getGraphEchoEvents, - getMeta: getMeta, - getNoteAccounts: getNoteAccounts, - getRegisters: getRegisters, - getStatistic: getStatistic, - getWithdrawals: getWithdrawals, - queryGraph: queryGraph -}); - -var __async$9 = (__this, __arguments, generator) => { - return new Promise((resolve, reject) => { - var fulfilled = (value) => { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - }; - var rejected = (value) => { - try { - step(generator.throw(value)); - } catch (e) { - reject(e); - } - }; - var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); - step((generator = generator.apply(__this, __arguments)).next()); - }); -}; -class BatchBlockService { - constructor({ - provider, - onProgress, - concurrencySize = 10, - batchSize = 10, - shouldRetry = true, - retryMax = 5, - retryOn = 500 - }) { - this.provider = provider; - this.onProgress = onProgress; - this.concurrencySize = concurrencySize; - this.batchSize = batchSize; - this.shouldRetry = shouldRetry; - this.retryMax = retryMax; - this.retryOn = retryOn; - } - getBlock(blockTag) { - return __async$9(this, null, function* () { - const blockObject = yield this.provider.getBlock(blockTag); - if (!blockObject) { - const errMsg = `No block for ${blockTag}`; - throw new Error(errMsg); - } - return blockObject; - }); - } - createBatchRequest(batchArray) { - return batchArray.map((blocks, index) => __async$9(this, null, function* () { - yield sleep(20 * index); - return (() => __async$9(this, null, function* () { - let retries = 0; - let err; - while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { - try { - return yield Promise.all(blocks.map((b) => this.getBlock(b))); - } catch (e) { - retries++; - err = e; - yield sleep(this.retryOn); - } - } - throw err; - }))(); - })); - } - getBatchBlocks(blocks) { - return __async$9(this, null, function* () { - let blockCount = 0; - const results = []; - for (const chunks of chunk(blocks, this.concurrencySize * this.batchSize)) { - const chunksResult = (yield Promise.all(this.createBatchRequest(chunk(chunks, this.batchSize)))).flat(); - results.push(...chunksResult); - blockCount += chunks.length; - if (typeof this.onProgress === "function") { - this.onProgress({ - percentage: blockCount / blocks.length, - currentIndex: blockCount, - totalIndex: blocks.length - }); - } - } - return results; - }); - } -} -class BatchTransactionService { - constructor({ - provider, - onProgress, - concurrencySize = 10, - batchSize = 10, - shouldRetry = true, - retryMax = 5, - retryOn = 500 - }) { - this.provider = provider; - this.onProgress = onProgress; - this.concurrencySize = concurrencySize; - this.batchSize = batchSize; - this.shouldRetry = shouldRetry; - this.retryMax = retryMax; - this.retryOn = retryOn; - } - getTransaction(txHash) { - return __async$9(this, null, function* () { - const txObject = yield this.provider.getTransaction(txHash); - if (!txObject) { - const errMsg = `No transaction for ${txHash}`; - throw new Error(errMsg); - } - return txObject; - }); - } - createBatchRequest(batchArray) { - return batchArray.map((txs, index) => __async$9(this, null, function* () { - yield sleep(20 * index); - return (() => __async$9(this, null, function* () { - let retries = 0; - let err; - while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { - try { - return yield Promise.all(txs.map((tx) => this.getTransaction(tx))); - } catch (e) { - retries++; - err = e; - yield sleep(this.retryOn); - } - } - throw err; - }))(); - })); - } - getBatchTransactions(txs) { - return __async$9(this, null, function* () { - let txCount = 0; - const results = []; - for (const chunks of chunk(txs, this.concurrencySize * this.batchSize)) { - const chunksResult = (yield Promise.all(this.createBatchRequest(chunk(chunks, this.batchSize)))).flat(); - results.push(...chunksResult); - txCount += chunks.length; - if (typeof this.onProgress === "function") { - this.onProgress({ percentage: txCount / txs.length, currentIndex: txCount, totalIndex: txs.length }); - } - } - return results; - }); - } -} -class BatchEventsService { - constructor({ - provider, - contract, - onProgress, - concurrencySize = 10, - blocksPerRequest = 2e3, - shouldRetry = true, - retryMax = 5, - retryOn = 500 - }) { - this.provider = provider; - this.contract = contract; - this.onProgress = onProgress; - this.concurrencySize = concurrencySize; - this.blocksPerRequest = blocksPerRequest; - this.shouldRetry = shouldRetry; - this.retryMax = retryMax; - this.retryOn = retryOn; - } - getPastEvents(_0) { - return __async$9(this, arguments, function* ({ fromBlock, toBlock, type }) { - let err; - let retries = 0; - while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { - try { - return yield this.contract.queryFilter(type, fromBlock, toBlock); - } catch (e) { - err = e; - retries++; - if (e.message.includes("after last accepted block")) { - const acceptedBlock = parseInt(e.message.split("after last accepted block ")[1]); - toBlock = acceptedBlock; - } - yield sleep(this.retryOn); - } - } - throw err; - }); - } - createBatchRequest(batchArray) { - return batchArray.map((event, index) => __async$9(this, null, function* () { - yield sleep(20 * index); - return this.getPastEvents(event); - })); - } - getBatchEvents(_0) { - return __async$9(this, arguments, function* ({ fromBlock, toBlock, type = "*" }) { - if (!toBlock) { - toBlock = yield this.provider.getBlockNumber(); - } - const eventsToSync = []; - for (let i = fromBlock; i < toBlock; i += this.blocksPerRequest) { - const j = i + this.blocksPerRequest - 1 > toBlock ? toBlock : i + this.blocksPerRequest - 1; - eventsToSync.push({ fromBlock: i, toBlock: j, type }); - } - const events = []; - const eventChunk = chunk(eventsToSync, this.concurrencySize); - let chunkCount = 0; - for (const chunk2 of eventChunk) { - chunkCount++; - const fetchedEvents = (yield Promise.all(this.createBatchRequest(chunk2))).flat(); - events.push(...fetchedEvents); - if (typeof this.onProgress === "function") { - this.onProgress({ - percentage: chunkCount / eventChunk.length, - type, - fromBlock: chunk2[0].fromBlock, - toBlock: chunk2[chunk2.length - 1].toBlock, - count: fetchedEvents.length - }); - } - } - return events; - }); - } -} - -var __defProp$2 = Object.defineProperty; -var __defProps$1 = Object.defineProperties; -var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors; -var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp$2 = Object.prototype.hasOwnProperty; -var __propIsEnum$2 = Object.prototype.propertyIsEnumerable; -var __reflectGet = Reflect.get; -var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __spreadValues$2 = (a, b) => { - for (var prop in b || (b = {})) - if (__hasOwnProp$2.call(b, prop)) - __defNormalProp$2(a, prop, b[prop]); - if (__getOwnPropSymbols$2) - for (var prop of __getOwnPropSymbols$2(b)) { - if (__propIsEnum$2.call(b, prop)) - __defNormalProp$2(a, prop, b[prop]); - } - return a; -}; -var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b)); -var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj); var __async$8 = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { @@ -4408,1307 +5373,18 @@ var __async$8 = (__this, __arguments, generator) => { step((generator = generator.apply(__this, __arguments)).next()); }); }; -const DEPOSIT = "deposit"; -const WITHDRAWAL = "withdrawal"; -class BaseEventsService { - constructor({ - netId, - provider, - graphApi, - subgraphName, - contract, - type = "", - deployedBlock = 0, - fetchDataOptions: fetchDataOptions2 - }) { - this.netId = netId; - this.provider = provider; - this.graphApi = graphApi; - this.subgraphName = subgraphName; - this.fetchDataOptions = fetchDataOptions2; - this.contract = contract; - this.type = type; - this.deployedBlock = deployedBlock; - this.batchEventsService = new BatchEventsService({ - provider, - contract, - onProgress: this.updateEventProgress - }); - } - getInstanceName() { - return ""; - } - getType() { - return this.type || ""; - } - getGraphMethod() { - return ""; - } - getGraphParams() { - return { - graphApi: this.graphApi || "", - subgraphName: this.subgraphName || "", - fetchDataOptions: this.fetchDataOptions, - onProgress: this.updateGraphProgress - }; - } - /* eslint-disable @typescript-eslint/no-unused-vars */ - updateEventProgress({ percentage, type, fromBlock, toBlock, count }) { - } - updateBlockProgress({ percentage, currentIndex, totalIndex }) { - } - updateTransactionProgress({ percentage, currentIndex, totalIndex }) { - } - updateGraphProgress({ type, fromBlock, toBlock, count }) { - } - /* eslint-enable @typescript-eslint/no-unused-vars */ - formatEvents(events) { - return __async$8(this, null, function* () { - return yield new Promise((resolve) => resolve(events)); - }); - } - /** - * Get saved or cached events - */ - getEventsFromDB() { - return __async$8(this, null, function* () { - return { - events: [], - lastBlock: null - }; - }); - } - getEventsFromCache() { - return __async$8(this, null, function* () { - return { - events: [], - lastBlock: null - }; - }); - } - getSavedEvents() { - return __async$8(this, null, function* () { - let cachedEvents = yield this.getEventsFromDB(); - if (!cachedEvents || !cachedEvents.events.length) { - cachedEvents = yield this.getEventsFromCache(); - } - return cachedEvents; - }); - } - /** - * Get latest events - */ - getEventsFromGraph(_0) { - return __async$8(this, arguments, function* ({ - fromBlock, - methodName = "" - }) { - if (!this.graphApi || !this.subgraphName) { - return { - events: [], - lastBlock: fromBlock - }; - } - const { events, lastSyncBlock } = yield graph[methodName || this.getGraphMethod()](__spreadValues$2({ - fromBlock - }, this.getGraphParams())); - return { - events, - lastBlock: lastSyncBlock - }; - }); - } - getEventsFromRpc(_0) { - return __async$8(this, arguments, function* ({ - fromBlock, - toBlock - }) { - try { - if (!toBlock) { - toBlock = yield this.provider.getBlockNumber(); - } - if (fromBlock >= toBlock) { - return { - events: [], - lastBlock: toBlock - }; - } - this.updateEventProgress({ percentage: 0, type: this.getType() }); - const events = yield this.formatEvents( - yield this.batchEventsService.getBatchEvents({ fromBlock, toBlock, type: this.getType() }) - ); - if (!events.length) { - return { - events, - lastBlock: toBlock - }; - } - return { - events, - lastBlock: toBlock - }; - } catch (err) { - console.log(err); - return { - events: [], - lastBlock: fromBlock - }; - } - }); - } - getLatestEvents(_0) { - return __async$8(this, arguments, function* ({ fromBlock }) { - const allEvents = []; - const graphEvents = yield this.getEventsFromGraph({ fromBlock }); - const lastSyncBlock = graphEvents.lastBlock && graphEvents.lastBlock >= fromBlock ? graphEvents.lastBlock : fromBlock; - const rpcEvents = yield this.getEventsFromRpc({ fromBlock: lastSyncBlock }); - allEvents.push(...graphEvents.events); - allEvents.push(...rpcEvents.events); - const lastBlock = rpcEvents ? rpcEvents.lastBlock : allEvents[allEvents.length - 1] ? allEvents[allEvents.length - 1].blockNumber : fromBlock; - return { - events: allEvents, - lastBlock - }; - }); - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - validateEvents({ events, lastBlock }) { - } - /** - * Handle saving events - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - saveEvents(_0) { - return __async$8(this, arguments, function* ({ events, lastBlock }) { - }); - } - /** - * Trigger saving and receiving latest events - */ - updateEvents() { - return __async$8(this, null, function* () { - const savedEvents = yield this.getSavedEvents(); - let fromBlock = this.deployedBlock; - if (savedEvents && savedEvents.lastBlock) { - fromBlock = savedEvents.lastBlock + 1; - } - const newEvents = yield this.getLatestEvents({ fromBlock }); - const eventSet = /* @__PURE__ */ new Set(); - let allEvents = []; - allEvents.push(...savedEvents.events); - allEvents.push(...newEvents.events); - allEvents = allEvents.sort((a, b) => { - if (a.blockNumber === b.blockNumber) { - return a.logIndex - b.logIndex; - } - return a.blockNumber - b.blockNumber; - }).filter(({ transactionHash, logIndex }) => { - const eventKey = `${transactionHash}_${logIndex}`; - const hasEvent = eventSet.has(eventKey); - eventSet.add(eventKey); - return !hasEvent; - }); - const lastBlock = newEvents ? newEvents.lastBlock : allEvents[allEvents.length - 1] ? allEvents[allEvents.length - 1].blockNumber : null; - this.validateEvents({ events: allEvents, lastBlock }); - this.saveEventsPromise = this.saveEvents({ events: allEvents, lastBlock }); - return { - events: allEvents, - lastBlock - }; - }); - } -} -class BaseTornadoService extends BaseEventsService { - constructor({ - netId, - provider, - graphApi, - subgraphName, - Tornado, - type, - amount, - currency, - deployedBlock, - fetchDataOptions: fetchDataOptions2 - }) { - super({ netId, provider, graphApi, subgraphName, contract: Tornado, type, deployedBlock, fetchDataOptions: fetchDataOptions2 }); - this.amount = amount; - this.currency = currency; - this.batchTransactionService = new BatchTransactionService({ - provider, - onProgress: this.updateTransactionProgress - }); - this.batchBlockService = new BatchBlockService({ - provider, - onProgress: this.updateBlockProgress - }); - } - getInstanceName() { - return `${this.getType().toLowerCase()}s_${this.netId}_${this.currency}_${this.amount}`; - } - getGraphMethod() { - return `getAll${this.getType()}s`; - } - getGraphParams() { - return { - graphApi: this.graphApi || "", - subgraphName: this.subgraphName || "", - amount: this.amount, - currency: this.currency, - fetchDataOptions: this.fetchDataOptions, - onProgress: this.updateGraphProgress - }; - } - formatEvents(events) { - return __async$8(this, null, function* () { - const type = this.getType().toLowerCase(); - if (type === DEPOSIT) { - const formattedEvents = events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { - const { commitment, leafIndex, timestamp } = args; - return { - blockNumber, - logIndex, - transactionHash, - commitment, - leafIndex: Number(leafIndex), - timestamp: Number(timestamp) - }; - }); - const txs = yield this.batchTransactionService.getBatchTransactions([ - ...new Set(formattedEvents.map(({ transactionHash }) => transactionHash)) - ]); - return formattedEvents.map((event) => { - const { from } = txs.find(({ hash }) => hash === event.transactionHash); - return __spreadProps$1(__spreadValues$2({}, event), { - from - }); - }); - } else { - const formattedEvents = events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { - const { nullifierHash, to, fee } = args; - return { - blockNumber, - logIndex, - transactionHash, - nullifierHash: String(nullifierHash), - to: getAddress(to), - fee: String(fee) - }; - }); - const blocks = yield this.batchBlockService.getBatchBlocks([ - ...new Set(formattedEvents.map(({ blockNumber }) => blockNumber)) - ]); - return formattedEvents.map((event) => { - const { timestamp } = blocks.find(({ number }) => number === event.blockNumber); - return __spreadProps$1(__spreadValues$2({}, event), { - timestamp - }); - }); - } - }); - } - validateEvents({ events }) { - if (events.length && this.getType().toLowerCase() === DEPOSIT) { - const lastEvent = events[events.length - 1]; - if (lastEvent.leafIndex !== events.length - 1) { - const errMsg = `Deposit events invalid wants ${events.length - 1} leafIndex have ${lastEvent.leafIndex}`; - throw new Error(errMsg); - } - } - } -} -class BaseEchoService extends BaseEventsService { - constructor({ - netId, - provider, - graphApi, - subgraphName, - Echoer, - deployedBlock, - fetchDataOptions: fetchDataOptions2 - }) { - super({ netId, provider, graphApi, subgraphName, contract: Echoer, deployedBlock, fetchDataOptions: fetchDataOptions2 }); - } - getInstanceName() { - return `echo_${this.netId}`; - } - getType() { - return "Echo"; - } - getGraphMethod() { - return "getAllGraphEchoEvents"; - } - formatEvents(events) { - return __async$8(this, null, function* () { - return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { - const { who, data } = args; - if (who && data) { - const eventObjects = { - blockNumber, - logIndex, - transactionHash - }; - return __spreadProps$1(__spreadValues$2({}, eventObjects), { - address: who, - encryptedAccount: data - }); - } - }).filter((e) => e); - }); - } - getEventsFromGraph(_0) { - return __async$8(this, arguments, function* ({ fromBlock }) { - if (!this.graphApi || this.graphApi.includes("api.thegraph.com")) { - return { - events: [], - lastBlock: fromBlock - }; - } - return __superGet(BaseEchoService.prototype, this, "getEventsFromGraph").call(this, { fromBlock }); - }); - } -} -class BaseEncryptedNotesService extends BaseEventsService { - constructor({ - netId, - provider, - graphApi, - subgraphName, - Router, - deployedBlock, - fetchDataOptions: fetchDataOptions2 - }) { - super({ netId, provider, graphApi, subgraphName, contract: Router, deployedBlock, fetchDataOptions: fetchDataOptions2 }); - } - getInstanceName() { - return `encrypted_notes_${this.netId}`; - } - getType() { - return "EncryptedNote"; - } - getGraphMethod() { - return "getAllEncryptedNotes"; - } - formatEvents(events) { - return __async$8(this, null, function* () { - return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { - const { encryptedNote } = args; - if (encryptedNote) { - const eventObjects = { - blockNumber, - logIndex, - transactionHash - }; - return __spreadProps$1(__spreadValues$2({}, eventObjects), { - encryptedNote - }); - } - }).filter((e) => e); - }); - } -} -class BaseGovernanceService extends BaseEventsService { - constructor({ - netId, - provider, - graphApi, - subgraphName, - Governance, - deployedBlock, - fetchDataOptions: fetchDataOptions2 - }) { - super({ netId, provider, graphApi, subgraphName, contract: Governance, deployedBlock, fetchDataOptions: fetchDataOptions2 }); - this.batchTransactionService = new BatchTransactionService({ - provider, - onProgress: this.updateTransactionProgress - }); - } - getInstanceName() { - return `governance_${this.netId}`; - } - getType() { - return "*"; - } - getGraphMethod() { - return "getAllGovernanceEvents"; - } - formatEvents(events) { - return __async$8(this, null, function* () { - const proposalEvents = []; - const votedEvents = []; - const delegatedEvents = []; - const undelegatedEvents = []; - events.forEach(({ blockNumber, index: logIndex, transactionHash, args, eventName: event }) => { - const eventObjects = { - blockNumber, - logIndex, - transactionHash, - event - }; - if (event === "ProposalCreated") { - const { id, proposer, target, startTime, endTime, description } = args; - proposalEvents.push(__spreadProps$1(__spreadValues$2({}, eventObjects), { - id: Number(id), - proposer, - target, - startTime: Number(startTime), - endTime: Number(endTime), - description - })); - } - if (event === "Voted") { - const { proposalId, voter, support, votes } = args; - votedEvents.push(__spreadProps$1(__spreadValues$2({}, eventObjects), { - proposalId: Number(proposalId), - voter, - support, - votes, - from: "", - input: "" - })); - } - if (event === "Delegated") { - const { account, to: delegateTo } = args; - delegatedEvents.push(__spreadProps$1(__spreadValues$2({}, eventObjects), { - account, - delegateTo - })); - } - if (event === "Undelegated") { - const { account, from: delegateFrom } = args; - undelegatedEvents.push(__spreadProps$1(__spreadValues$2({}, eventObjects), { - account, - delegateFrom - })); - } - }); - if (votedEvents.length) { - this.updateTransactionProgress({ percentage: 0 }); - const txs = yield this.batchTransactionService.getBatchTransactions([ - ...new Set(votedEvents.map(({ transactionHash }) => transactionHash)) - ]); - votedEvents.forEach((event, index) => { - let { data: input, from } = txs.find((t) => t.hash === event.transactionHash); - if (!input || input.length > 2048) { - input = ""; - } - votedEvents[index].from = from; - votedEvents[index].input = input; - }); - } - return [...proposalEvents, ...votedEvents, ...delegatedEvents, ...undelegatedEvents]; - }); - } - getEventsFromGraph(_0) { - return __async$8(this, arguments, function* ({ fromBlock }) { - if (!this.graphApi || !this.subgraphName || this.graphApi.includes("api.thegraph.com")) { - return { - events: [], - lastBlock: fromBlock - }; - } - return __superGet(BaseGovernanceService.prototype, this, "getEventsFromGraph").call(this, { fromBlock }); - }); - } -} -class BaseRegistryService extends BaseEventsService { - constructor({ - netId, - provider, - graphApi, - subgraphName, - RelayerRegistry, - deployedBlock, - fetchDataOptions: fetchDataOptions2 - }) { - super({ netId, provider, graphApi, subgraphName, contract: RelayerRegistry, deployedBlock, fetchDataOptions: fetchDataOptions2 }); - } - getInstanceName() { - return `registered_${this.netId}`; - } - // Name of type used for events - getType() { - return "RelayerRegistered"; - } - // Name of method used for graph - getGraphMethod() { - return "getAllRegisters"; - } - formatEvents(events) { - return __async$8(this, null, function* () { - return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { - const eventObjects = { - blockNumber, - logIndex, - transactionHash - }; - return __spreadProps$1(__spreadValues$2({}, eventObjects), { - ensName: args.ensName, - relayerAddress: args.relayerAddress - }); - }); - }); - } - fetchRelayers() { - return __async$8(this, null, function* () { - return (yield this.updateEvents()).events; - }); - } -} - -var __defProp$1 = Object.defineProperty; -var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols; -var __hasOwnProp$1 = Object.prototype.hasOwnProperty; -var __propIsEnum$1 = Object.prototype.propertyIsEnumerable; -var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __spreadValues$1 = (a, b) => { - for (var prop in b || (b = {})) - if (__hasOwnProp$1.call(b, prop)) - __defNormalProp$1(a, prop, b[prop]); - if (__getOwnPropSymbols$1) - for (var prop of __getOwnPropSymbols$1(b)) { - if (__propIsEnum$1.call(b, prop)) - __defNormalProp$1(a, prop, b[prop]); - } - return a; -}; -var NetId = /* @__PURE__ */ ((NetId2) => { - NetId2[NetId2["MAINNET"] = 1] = "MAINNET"; - NetId2[NetId2["BSC"] = 56] = "BSC"; - NetId2[NetId2["POLYGON"] = 137] = "POLYGON"; - NetId2[NetId2["OPTIMISM"] = 10] = "OPTIMISM"; - NetId2[NetId2["ARBITRUM"] = 42161] = "ARBITRUM"; - NetId2[NetId2["GNOSIS"] = 100] = "GNOSIS"; - NetId2[NetId2["AVALANCHE"] = 43114] = "AVALANCHE"; - NetId2[NetId2["SEPOLIA"] = 11155111] = "SEPOLIA"; - return NetId2; -})(NetId || {}); -const theGraph = { - name: "Hosted Graph", - url: "https://api.thegraph.com" -}; -const tornado = { - name: "Tornado Subgraphs", - url: "https://tornadocash-rpc.com" -}; -const defaultConfig = { - [1 /* MAINNET */]: { - rpcCallRetryAttempt: 15, - gasPrices: { - instant: 80, - fast: 50, - standard: 25, - low: 8 - }, - nativeCurrency: "eth", - currencyName: "ETH", - explorerUrl: "https://etherscan.io", - merkleTreeHeight: 20, - emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", - networkName: "Ethereum Mainnet", - deployedBlock: 9116966, - rpcUrls: { - tornadoRPC: { - name: "Tornado RPC", - url: "https://tornadocash-rpc.com/mainnet" - }, - mevblockerRPC: { - name: "MevblockerRPC", - url: "https://rpc.mevblocker.io" - }, - oneRPC: { - name: "1RPC", - url: "https://1rpc.io/eth" - } - }, - multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", - routerContract: "0xd90e2f925DA726b50C4Ed8D0Fb90Ad053324F31b", - echoContract: "0x9B27DD5Bb15d42DC224FCD0B7caEbBe16161Df42", - offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", - tornContract: "0x77777FeDdddFfC19Ff86DB637967013e6C6A116C", - governanceContract: "0x5efda50f22d34F262c29268506C5Fa42cB56A1Ce", - stakingRewardsContract: "0x5B3f656C80E8ddb9ec01Dd9018815576E9238c29", - registryContract: "0x58E8dCC13BE9780fC42E8723D8EaD4CF46943dF2", - aggregatorContract: "0xE8F47A78A6D52D317D0D2FFFac56739fE14D1b49", - reverseRecordsContract: "0x3671aE578E63FdF66ad4F3E12CC0c0d71Ac7510C", - tornadoSubgraph: "tornadocash/mainnet-tornado-subgraph", - registrySubgraph: "tornadocash/tornado-relayer-registry", - governanceSubgraph: "tornadocash/tornado-governance", - subgraphs: { - tornado, - theGraph - }, - tokens: { - eth: { - instanceAddress: { - "0.1": "0x12D66f87A04A9E220743712cE6d9bB1B5616B8Fc", - "1": "0x47CE0C6eD5B0Ce3d3A51fdb1C52DC66a7c3c2936", - "10": "0x910Cbd523D972eb0a6f4cAe4618aD62622b39DbF", - "100": "0xA160cdAB225685dA1d56aa342Ad8841c3b53f291" - }, - symbol: "ETH", - decimals: 18 - }, - dai: { - instanceAddress: { - "100": "0xD4B88Df4D29F5CedD6857912842cff3b20C8Cfa3", - "1000": "0xFD8610d20aA15b7B2E3Be39B396a1bC3516c7144", - "10000": "0x07687e702b410Fa43f4cB4Af7FA097918ffD2730", - "100000": "0x23773E65ed146A459791799d01336DB287f25334" - }, - tokenAddress: "0x6B175474E89094C44Da98b954EedeAC495271d0F", - tokenGasLimit: 7e4, - symbol: "DAI", - decimals: 18, - gasLimit: 7e5 - }, - cdai: { - instanceAddress: { - "5000": "0x22aaA7720ddd5388A3c0A3333430953C68f1849b", - "50000": "0x03893a7c7463AE47D46bc7f091665f1893656003", - "500000": "0x2717c5e28cf931547B621a5dddb772Ab6A35B701", - "5000000": "0xD21be7248e0197Ee08E0c20D4a96DEBdaC3D20Af" - }, - tokenAddress: "0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643", - tokenGasLimit: 2e5, - symbol: "cDAI", - decimals: 8, - gasLimit: 7e5 - }, - usdc: { - instanceAddress: { - "100": "0xd96f2B1c14Db8458374d9Aca76E26c3D18364307", - "1000": "0x4736dCf1b7A3d580672CcE6E7c65cd5cc9cFBa9D" - }, - tokenAddress: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", - tokenGasLimit: 7e4, - symbol: "USDC", - decimals: 6, - gasLimit: 7e5 - }, - usdt: { - instanceAddress: { - "100": "0x169AD27A470D064DEDE56a2D3ff727986b15D52B", - "1000": "0x0836222F2B2B24A3F36f98668Ed8F0B38D1a872f" - }, - tokenAddress: "0xdAC17F958D2ee523a2206206994597C13D831ec7", - tokenGasLimit: 7e4, - symbol: "USDT", - decimals: 6, - gasLimit: 7e5 - }, - wbtc: { - instanceAddress: { - "0.1": "0x178169B423a011fff22B9e3F3abeA13414dDD0F1", - "1": "0x610B717796ad172B316836AC95a2ffad065CeaB4", - "10": "0xbB93e510BbCD0B7beb5A853875f9eC60275CF498" - }, - tokenAddress: "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599", - tokenGasLimit: 7e4, - symbol: "WBTC", - decimals: 8, - gasLimit: 7e5 - } - }, - relayerEnsSubdomain: "mainnet-tornado", - pollInterval: 15, - constants: { - GOVERNANCE_BLOCK: 11474695, - NOTE_ACCOUNT_BLOCK: 11842486, - ENCRYPTED_NOTES_BLOCK: 12143762, - REGISTRY_BLOCK: 14173129, - MINING_BLOCK_TIME: 15 - } - }, - [56 /* BSC */]: { - rpcCallRetryAttempt: 15, - gasPrices: { - instant: 5, - fast: 5, - standard: 5, - low: 5 - }, - nativeCurrency: "bnb", - currencyName: "BNB", - explorerUrl: "https://bscscan.com", - merkleTreeHeight: 20, - emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", - networkName: "Binance Smart Chain", - deployedBlock: 8158799, - multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", - routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", - echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", - offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", - tornadoSubgraph: "tornadocash/bsc-tornado-subgraph", - subgraphs: { - tornado, - theGraph - }, - rpcUrls: { - tornadoRPC: { - name: "Tornado RPC", - url: "https://tornadocash-rpc.com/bsc" - }, - oneRPC: { - name: "1RPC", - url: "https://1rpc.io/bnb" - } - }, - tokens: { - bnb: { - instanceAddress: { - "0.1": "0x84443CFd09A48AF6eF360C6976C5392aC5023a1F", - "1": "0xd47438C816c9E7f2E2888E060936a499Af9582b3", - "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", - "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD" - }, - symbol: "BNB", - decimals: 18 - } - }, - relayerEnsSubdomain: "bsc-tornado", - pollInterval: 10, - constants: { - NOTE_ACCOUNT_BLOCK: 8159269, - ENCRYPTED_NOTES_BLOCK: 8159269 - } - }, - [137 /* POLYGON */]: { - rpcCallRetryAttempt: 15, - gasPrices: { - instant: 100, - fast: 75, - standard: 50, - low: 30 - }, - nativeCurrency: "matic", - currencyName: "MATIC", - explorerUrl: "https://polygonscan.com", - merkleTreeHeight: 20, - emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", - networkName: "Polygon (Matic) Network", - deployedBlock: 16257962, - multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", - routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", - echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", - offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", - gasPriceOracleContract: "0xF81A8D8D3581985D3969fe53bFA67074aDFa8F3C", - tornadoSubgraph: "tornadocash/matic-tornado-subgraph", - subgraphs: { - tornado, - theGraph - }, - rpcUrls: { - oneRpc: { - name: "1RPC", - url: "https://1rpc.io/matic" - } - }, - tokens: { - matic: { - instanceAddress: { - "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD", - "1000": "0xdf231d99Ff8b6c6CBF4E9B9a945CBAcEF9339178", - "10000": "0xaf4c0B70B2Ea9FB7487C7CbB37aDa259579fe040", - "100000": "0xa5C2254e4253490C54cef0a4347fddb8f75A4998" - }, - symbol: "MATIC", - decimals: 18 - } - }, - relayerEnsSubdomain: "polygon-tornado", - pollInterval: 10, - constants: { - NOTE_ACCOUNT_BLOCK: 16257996, - ENCRYPTED_NOTES_BLOCK: 16257996 - } - }, - [10 /* OPTIMISM */]: { - rpcCallRetryAttempt: 15, - gasPrices: { - instant: 1e-3, - fast: 1e-3, - standard: 1e-3, - low: 1e-3 - }, - nativeCurrency: "eth", - currencyName: "ETH", - explorerUrl: "https://optimistic.etherscan.io", - merkleTreeHeight: 20, - emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", - networkName: "Optimism", - deployedBlock: 2243689, - multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", - routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", - echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", - offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", - ovmGasPriceOracleContract: "0x420000000000000000000000000000000000000F", - tornadoSubgraph: "tornadocash/optimism-tornado-subgraph", - subgraphs: { - tornado, - theGraph - }, - rpcUrls: { - tornadoRPC: { - name: "Tornado RPC", - url: "https://tornadocash-rpc.com/op" - }, - oneRpc: { - name: "1RPC", - url: "https://1rpc.io/op" - } - }, - tokens: { - eth: { - instanceAddress: { - "0.1": "0x84443CFd09A48AF6eF360C6976C5392aC5023a1F", - "1": "0xd47438C816c9E7f2E2888E060936a499Af9582b3", - "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", - "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD" - }, - symbol: "ETH", - decimals: 18 - } - }, - relayerEnsSubdomain: "optimism-tornado", - pollInterval: 15, - constants: { - NOTE_ACCOUNT_BLOCK: 2243694, - ENCRYPTED_NOTES_BLOCK: 2243694 - } - }, - [42161 /* ARBITRUM */]: { - rpcCallRetryAttempt: 15, - gasPrices: { - instant: 4, - fast: 3, - standard: 2.52, - low: 2.29 - }, - nativeCurrency: "eth", - currencyName: "ETH", - explorerUrl: "https://arbiscan.io", - merkleTreeHeight: 20, - emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", - networkName: "Arbitrum One", - deployedBlock: 3430648, - multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", - routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", - echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", - offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", - tornadoSubgraph: "tornadocash/arbitrum-tornado-subgraph", - subgraphs: { - tornado, - theGraph - }, - rpcUrls: { - oneRpc: { - name: "1rpc", - url: "https://1rpc.io/arb" - }, - Arbitrum: { - name: "Arbitrum RPC", - url: "https://arb1.arbitrum.io/rpc" - } - }, - tokens: { - eth: { - instanceAddress: { - "0.1": "0x84443CFd09A48AF6eF360C6976C5392aC5023a1F", - "1": "0xd47438C816c9E7f2E2888E060936a499Af9582b3", - "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", - "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD" - }, - symbol: "ETH", - decimals: 18 - } - }, - relayerEnsSubdomain: "arbitrum-tornado", - pollInterval: 15, - constants: { - NOTE_ACCOUNT_BLOCK: 3430605, - ENCRYPTED_NOTES_BLOCK: 3430605 - } - }, - [100 /* GNOSIS */]: { - rpcCallRetryAttempt: 15, - gasPrices: { - instant: 6, - fast: 5, - standard: 4, - low: 1 - }, - nativeCurrency: "xdai", - currencyName: "xDAI", - explorerUrl: "https://gnosisscan.io", - merkleTreeHeight: 20, - emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", - networkName: "Gnosis Chain", - deployedBlock: 17754561, - multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", - routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", - echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", - offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", - tornadoSubgraph: "tornadocash/xdai-tornado-subgraph", - subgraphs: { - tornado, - theGraph - }, - rpcUrls: { - tornadoRPC: { - name: "Tornado RPC", - url: "https://tornadocash-rpc.com/gnosis" - }, - blockPi: { - name: "BlockPi", - url: "https://gnosis.blockpi.network/v1/rpc/public" - } - }, - tokens: { - xdai: { - instanceAddress: { - "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD", - "1000": "0xdf231d99Ff8b6c6CBF4E9B9a945CBAcEF9339178", - "10000": "0xaf4c0B70B2Ea9FB7487C7CbB37aDa259579fe040", - "100000": "0xa5C2254e4253490C54cef0a4347fddb8f75A4998" - }, - symbol: "xDAI", - decimals: 18 - } - }, - relayerEnsSubdomain: "gnosis-tornado", - pollInterval: 15, - constants: { - NOTE_ACCOUNT_BLOCK: 17754564, - ENCRYPTED_NOTES_BLOCK: 17754564 - } - }, - [43114 /* AVALANCHE */]: { - rpcCallRetryAttempt: 15, - gasPrices: { - instant: 225, - fast: 35, - standard: 25, - low: 25 - }, - nativeCurrency: "avax", - currencyName: "AVAX", - explorerUrl: "https://snowtrace.io", - merkleTreeHeight: 20, - emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", - networkName: "Avalanche Mainnet", - deployedBlock: 4429818, - multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", - routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", - echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", - offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", - tornadoSubgraph: "tornadocash/avalanche-tornado-subgraph", - subgraphs: { - theGraph - }, - rpcUrls: { - publicRpc: { - name: "Avalanche RPC", - url: "https://api.avax.network/ext/bc/C/rpc" - }, - meowRPC: { - name: "Meow RPC", - url: "https://avax.meowrpc.com" - }, - oneRPC: { - name: "OneRPC", - url: "https://1rpc.io/avax/c" - } - }, - tokens: { - avax: { - instanceAddress: { - "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", - "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD", - "500": "0xaf8d1839c3c67cf571aa74B5c12398d4901147B3" - }, - symbol: "AVAX", - decimals: 18 - } - }, - relayerEnsSubdomain: "avalanche-tornado", - pollInterval: 10, - constants: { - NOTE_ACCOUNT_BLOCK: 4429813, - ENCRYPTED_NOTES_BLOCK: 4429813 - } - }, - [11155111 /* SEPOLIA */]: { - rpcCallRetryAttempt: 15, - gasPrices: { - instant: 2, - fast: 2, - standard: 2, - low: 2 - }, - nativeCurrency: "eth", - currencyName: "SepoliaETH", - explorerUrl: "https://sepolia.etherscan.io", - merkleTreeHeight: 20, - emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", - networkName: "Ethereum Sepolia", - deployedBlock: 5594395, - multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", - routerContract: "0x1572AFE6949fdF51Cb3E0856216670ae9Ee160Ee", - echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", - tornContract: "0x3AE6667167C0f44394106E197904519D808323cA", - governanceContract: "0xe5324cD7602eeb387418e594B87aCADee08aeCAD", - stakingRewardsContract: "0x6d0018890751Efd31feb8166711B16732E2b496b", - registryContract: "0x1428e5d2356b13778A13108b10c440C83011dfB8", - aggregatorContract: "0x4088712AC9fad39ea133cdb9130E465d235e9642", - reverseRecordsContract: "0xEc29700C0283e5Be64AcdFe8077d6cC95dE23C23", - tornadoSubgraph: "tornadocash/sepolia-tornado-subgraph", - subgraphs: { - tornado - }, - rpcUrls: { - tornadoRPC: { - name: "Tornado RPC", - url: "https://tornadocash-rpc.com/sepolia" - }, - sepolia: { - name: "Sepolia RPC", - url: "https://rpc.sepolia.org" - } - }, - tokens: { - eth: { - instanceAddress: { - "0.1": "0x8C4A04d872a6C1BE37964A21ba3a138525dFF50b", - "1": "0x8cc930096B4Df705A007c4A039BDFA1320Ed2508", - "10": "0x8D10d506D29Fc62ABb8A290B99F66dB27Fc43585", - "100": "0x44c5C92ed73dB43888210264f0C8b36Fd68D8379" - }, - symbol: "ETH", - decimals: 18 - }, - dai: { - instanceAddress: { - "100": "0x6921fd1a97441dd603a997ED6DDF388658daf754", - "1000": "0x50a637770F5d161999420F7d70d888DE47207145", - "10000": "0xecD649870407cD43923A816Cc6334a5bdf113621", - "100000": "0x73B4BD04bF83206B6e979BE2507098F92EDf4F90" - }, - tokenAddress: "0xFF34B3d4Aee8ddCd6F9AFFFB6Fe49bD371b8a357", - tokenGasLimit: 7e4, - symbol: "DAI", - decimals: 18, - gasLimit: 7e5 - } - }, - relayerEnsSubdomain: "sepolia-tornado", - pollInterval: 15, - constants: { - GOVERNANCE_BLOCK: 5594395, - NOTE_ACCOUNT_BLOCK: 5594395, - ENCRYPTED_NOTES_BLOCK: 5594395, - MINING_BLOCK_TIME: 15 - } - } -}; -const enabledChains = Object.values(NetId).filter((n) => typeof n === "number"); -let customConfig = {}; -function addNetwork(newConfig) { - enabledChains.push( - ...Object.keys(newConfig).map((netId) => Number(netId)).filter((netId) => !enabledChains.includes(netId)) - ); - customConfig = __spreadValues$1(__spreadValues$1({}, customConfig), newConfig); -} -function getNetworkConfig() { - const allConfig = __spreadValues$1(__spreadValues$1({}, defaultConfig), customConfig); - return enabledChains.reduce((acc, curr) => { - acc[curr] = allConfig[curr]; - return acc; - }, {}); -} -function getConfig(netId) { - const allConfig = getNetworkConfig(); - const chainConfig = allConfig[netId]; - if (!chainConfig) { - const errMsg = `No config found for network ${netId}!`; - throw new Error(errMsg); - } - return chainConfig; -} -function getInstanceByAddress({ netId, address }) { - const { tokens } = getConfig(netId); - for (const [currency, { instanceAddress }] of Object.entries(tokens)) { - for (const [amount, instance] of Object.entries(instanceAddress)) { - if (instance === address) { - return { - amount, - currency - }; - } - } - } -} -function getSubdomains() { - const allConfig = getNetworkConfig(); - return enabledChains.map((chain) => allConfig[chain].relayerEnsSubdomain); -} - -const addressType = { type: "string", pattern: "^0x[a-fA-F0-9]{40}$" }; -const bnType = { type: "string", BN: true }; -const statusSchema = { - type: "object", - properties: { - rewardAccount: addressType, - gasPrices: { - type: "object", - properties: { - fast: { type: "number" }, - additionalProperties: { type: "number" } - }, - required: ["fast"] - }, - netId: { type: "integer" }, - tornadoServiceFee: { type: "number", maximum: 20, minimum: 0 }, - latestBlock: { type: "number" }, - version: { type: "string" }, - health: { - type: "object", - properties: { - status: { const: "true" }, - error: { type: "string" } - }, - required: ["status"] - }, - currentQueue: { type: "number" } - }, - required: ["rewardAccount", "instances", "netId", "tornadoServiceFee", "version", "health"] -}; -function getStatusSchema(netId, config) { - const { tokens, optionalTokens = [], nativeCurrency } = config; - const schema = JSON.parse(JSON.stringify(statusSchema)); - const instances = Object.keys(tokens).reduce( - (acc, token) => { - const { instanceAddress, tokenAddress, symbol, decimals, optionalInstances = [] } = tokens[token]; - const amounts = Object.keys(instanceAddress); - const instanceProperties = { - type: "object", - properties: { - instanceAddress: { - type: "object", - properties: amounts.reduce((acc2, cur) => { - acc2[cur] = addressType; - return acc2; - }, {}), - required: amounts.filter((amount) => !optionalInstances.includes(amount)) - }, - decimals: { enum: [decimals] } - }, - required: ["instanceAddress", "decimals"].concat( - tokenAddress ? ["tokenAddress"] : [], - symbol ? ["symbol"] : [] - ) - }; - if (tokenAddress) { - instanceProperties.properties.tokenAddress = addressType; - } - if (symbol) { - instanceProperties.properties.symbol = { enum: [symbol] }; - } - acc.properties[token] = instanceProperties; - if (!optionalTokens.includes(token)) { - acc.required.push(token); - } - return acc; - }, - { - type: "object", - properties: {}, - required: [] - } - ); - schema.properties.instances = instances; - if (netId === NetId.MAINNET) { - const _tokens = Object.keys(tokens).filter((t) => t !== nativeCurrency); - const ethPrices = { - type: "object", - properties: _tokens.reduce((acc, token) => { - acc[token] = bnType; - return acc; - }, {}) - // required: _tokens - }; - schema.properties.ethPrices = ethPrices; - } - return schema; -} - -const jobsSchema = { - type: "object", - properties: { - error: { type: "string" }, - id: { type: "string" }, - type: { type: "string" }, - status: { type: "string" }, - contract: { type: "string" }, - proof: { type: "string" }, - args: { - type: "array", - items: { type: "string" } - }, - txHash: { type: "string" }, - confirmations: { type: "number" }, - failedReason: { type: "string" } - }, - required: ["id", "status"] -}; - -const ajv = new Ajv({ allErrors: true }); -ajv.addKeyword({ - keyword: "BN", - // eslint-disable-next-line @typescript-eslint/no-explicit-any - validate: (schema, data) => { - try { - BigInt(data); - return true; - } catch (e) { - return false; - } - }, - errors: true -}); - -var __async$7 = (__this, __arguments, generator) => { - return new Promise((resolve, reject) => { - var fulfilled = (value) => { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - }; - var rejected = (value) => { - try { - step(generator.throw(value)); - } catch (e) { - reject(e); - } - }; - var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); - step((generator = generator.apply(__this, __arguments)).next()); - }); -}; class Pedersen { constructor() { this.pedersenPromise = this.initPedersen(); } initPedersen() { - return __async$7(this, null, function* () { + return __async$8(this, null, function* () { this.pedersenHash = yield buildPedersenHash(); this.babyJub = this.pedersenHash.babyJub; }); } unpackPoint(buffer) { - return __async$7(this, null, function* () { + return __async$8(this, null, function* () { var _a, _b; yield this.pedersenPromise; return (_b = this.babyJub) == null ? void 0 : _b.unpackPoint((_a = this.pedersenHash) == null ? void 0 : _a.hash(buffer)); @@ -5721,13 +5397,13 @@ class Pedersen { } const pedersen = new Pedersen(); function buffPedersenHash(buffer) { - return __async$7(this, null, function* () { + return __async$8(this, null, function* () { const [hash] = yield pedersen.unpackPoint(buffer); return pedersen.toStringBuffer(hash); }); } -var __async$6 = (__this, __arguments, generator) => { +var __async$7 = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { @@ -5748,7 +5424,7 @@ var __async$6 = (__this, __arguments, generator) => { }); }; function createDeposit(_0) { - return __async$6(this, arguments, function* ({ nullifier, secret }) { + return __async$7(this, arguments, function* ({ nullifier, secret }) { const preimage = new Uint8Array([...leInt2Buff(nullifier), ...leInt2Buff(secret)]); const noteHex = toFixedHex(bytesToBN(preimage), 62); const commitment = BigInt(yield buffPedersenHash(preimage)); @@ -5808,7 +5484,7 @@ class Deposit { ); } static createNote(_0) { - return __async$6(this, arguments, function* ({ currency, amount, netId, nullifier, secret }) { + return __async$7(this, arguments, function* ({ currency, amount, netId, nullifier, secret }) { if (!nullifier) { nullifier = rBigInt(31); } @@ -5835,7 +5511,7 @@ class Deposit { }); } static parseNote(noteString) { - return __async$6(this, null, function* () { + return __async$7(this, null, function* () { const noteRegex = new RegExp("tornado-(?\\w+)-(?[\\d.]+)-(?\\d+)-0x(?[0-9a-fA-F]{124})", "g"); const match = noteRegex.exec(noteString); if (!match) { @@ -6094,7 +5770,7 @@ class TornadoFeeOracle { } } -var __async$5 = (__this, __arguments, generator) => { +var __async$6 = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { @@ -6119,7 +5795,7 @@ class Mimc { this.mimcPromise = this.initMimc(); } initMimc() { - return __async$5(this, null, function* () { + return __async$6(this, null, function* () { this.sponge = yield buildMimcSponge(); this.hash = (left, right) => { var _a, _b; @@ -6128,7 +5804,7 @@ class Mimc { }); } getHash() { - return __async$5(this, null, function* () { + return __async$6(this, null, function* () { yield this.mimcPromise; return { sponge: this.sponge, @@ -6139,7 +5815,7 @@ class Mimc { } const mimc = new Mimc(); -var __async$4 = (__this, __arguments, generator) => { +var __async$5 = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { @@ -6182,7 +5858,7 @@ class MerkleTreeService { this.merkleWorkerPath = merkleWorkerPath; } createTree(events) { - return __async$4(this, null, function* () { + return __async$5(this, null, function* () { const { hash: hashFunction } = yield mimc.getHash(); if (this.merkleWorkerPath) { console.log("Using merkleWorker\n"); @@ -6234,7 +5910,7 @@ class MerkleTreeService { }); } createPartialTree(_0) { - return __async$4(this, arguments, function* ({ edge, elements }) { + return __async$5(this, arguments, function* ({ edge, elements }) { const { hash: hashFunction } = yield mimc.getHash(); if (this.merkleWorkerPath) { console.log("Using merkleWorker\n"); @@ -6288,7 +5964,7 @@ class MerkleTreeService { }); } verifyTree(events) { - return __async$4(this, null, function* () { + return __async$5(this, null, function* () { console.log( ` Creating deposit tree for ${this.netId} ${this.amount} ${this.currency.toUpperCase()} would take a while @@ -6308,6 +5984,50 @@ Creating deposit tree for ${this.netId} ${this.amount} ${this.currency.toUpperCa } } +var __async$4 = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +function multicall(Multicall2, calls) { + return __async$4(this, null, function* () { + const calldata = calls.map((call) => { + var _a, _b, _c; + const target = ((_a = call.contract) == null ? void 0 : _a.target) || call.address; + const callInterface = ((_b = call.contract) == null ? void 0 : _b.interface) || call.interface; + return { + target, + callData: callInterface.encodeFunctionData(call.name, call.params), + allowFailure: (_c = call.allowFailure) != null ? _c : false + }; + }); + const returnData = yield Multicall2.aggregate3.staticCall(calldata); + const res = returnData.map((call, i) => { + var _a; + const callInterface = ((_a = calls[i].contract) == null ? void 0 : _a.interface) || calls[i].interface; + const [result, data] = call; + const decodeResult = result && data && data !== "0x" ? callInterface.decodeFunctionResult(calls[i].name, data) : null; + return !decodeResult ? null : decodeResult.length === 1 ? decodeResult[0] : decodeResult; + }); + return res; + }); +} + var __async$3 = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { @@ -6403,8 +6123,7 @@ function isRelayerUpdated(relayerVersion, netId) { const { major, patch, prerelease } = parseSemanticVersion(relayerVersion); const requiredMajor = netId === NetId.MAINNET ? "4" : "5"; const isUpdatedMajor = major === requiredMajor; - if (prerelease) - return false; + if (prerelease) return false; return isUpdatedMajor && (Number(patch) >= 5 || netId !== NetId.MAINNET); } function calculateScore({ stakeBalance, tornadoServiceFee }, minFee = 0.33, maxFee = 0.53) { @@ -6783,4 +6502,4 @@ function calculateSnarkProof(input, circuit, provingKey) { }); } -export { BaseEchoService, BaseEncryptedNotesService, BaseEventsService, BaseGovernanceService, BaseRegistryService, BaseTornadoService, BatchBlockService, BatchEventsService, BatchTransactionService, DEPOSIT, Deposit, ENS__factory, ERC20__factory, GET_DEPOSITS, GET_ECHO_EVENTS, GET_ENCRYPTED_NOTES, GET_GOVERNANCE_APY, GET_GOVERNANCE_EVENTS, GET_NOTE_ACCOUNTS, GET_REGISTERED, GET_STATISTIC, GET_WITHDRAWALS, GasPriceOracle__factory, Invoice, MIN_STAKE_BALANCE, MerkleTreeService, Mimc, Multicall__factory, NetId, NoteAccount, OffchainOracle__factory, OvmGasPriceOracle__factory, Pedersen, RelayerClient, ReverseRecords__factory, TokenPriceOracle, TornadoBrowserProvider, TornadoFeeOracle, TornadoRpcSigner, TornadoVoidSigner, TornadoWallet, WITHDRAWAL, _META, addNetwork, ajv, base64ToBytes, bigIntReplacer, bnToBytes, buffPedersenHash, bufferToBytes, bytesToBN, bytesToBase64, bytesToHex, calculateScore, calculateSnarkProof, chunk, concatBytes, convertETHToTokenAmount, createDeposit, crypto, customConfig, defaultConfig, defaultUserAgent, enabledChains, index as factories, fetch, fetchData, fetchGetUrlFunc, getAllDeposits, getAllEncryptedNotes, getAllGovernanceEvents, getAllGraphEchoEvents, getAllRegisters, getAllWithdrawals, getConfig, getDeposits, getEncryptedNotes, getGasOraclePlugin, getGovernanceEvents, getGraphEchoEvents, getHttpAgent, getInstanceByAddress, getMeta, getNetworkConfig, getNoteAccounts, getProvider, getProviderWithNetId, getRegisters, getStatistic, getStatusSchema, getSubdomains, getSupportedInstances, getTokenBalances, getWeightRandom, getWithdrawals, hexToBytes, initGroth16, isNode, isRelayerUpdated, jobsSchema, leBuff2Int, leInt2Buff, mimc, multicall, packEncryptedMessage, parseSemanticVersion, pedersen, pickWeightedRandomRelayer, populateTransaction, queryGraph, rBigInt, sleep, substring, toFixedHex, toFixedLength, unpackEncryptedMessage, validateUrl }; +export { BaseEchoService, BaseEncryptedNotesService, BaseEventsService, BaseGovernanceService, BaseRegistryService, BaseTornadoService, BatchBlockService, BatchEventsService, BatchTransactionService, DEPOSIT, Deposit, ENS__factory, ERC20__factory, GET_DEPOSITS, GET_ECHO_EVENTS, GET_ENCRYPTED_NOTES, GET_GOVERNANCE_APY, GET_GOVERNANCE_EVENTS, GET_NOTE_ACCOUNTS, GET_REGISTERED, GET_STATISTIC, GET_WITHDRAWALS, Invoice, MIN_STAKE_BALANCE, MerkleTreeService, Mimc, Multicall__factory, NetId, NoteAccount, OffchainOracle__factory, OvmGasPriceOracle__factory, Pedersen, RelayerClient, ReverseRecords__factory, TokenPriceOracle, TornadoBrowserProvider, TornadoFeeOracle, TornadoRpcSigner, TornadoVoidSigner, TornadoWallet, WITHDRAWAL, _META, addNetwork, ajv, base64ToBytes, bigIntReplacer, bnToBytes, buffPedersenHash, bufferToBytes, bytesToBN, bytesToBase64, bytesToHex, calculateScore, calculateSnarkProof, chunk, concatBytes, convertETHToTokenAmount, createDeposit, crypto, customConfig, defaultConfig, defaultUserAgent, enabledChains, index as factories, fetch, fetchData, fetchGetUrlFunc, getAllDeposits, getAllEncryptedNotes, getAllGovernanceEvents, getAllGraphEchoEvents, getAllRegisters, getAllWithdrawals, getConfig, getDeposits, getEncryptedNotes, getGovernanceEvents, getGraphEchoEvents, getHttpAgent, getInstanceByAddress, getMeta, getNetworkConfig, getNoteAccounts, getProvider, getProviderWithNetId, getRegisters, getStatistic, getStatusSchema, getSubdomains, getSupportedInstances, getTokenBalances, getWeightRandom, getWithdrawals, hexToBytes, initGroth16, isNode, isRelayerUpdated, jobsSchema, leBuff2Int, leInt2Buff, mimc, multicall, packEncryptedMessage, parseSemanticVersion, pedersen, pickWeightedRandomRelayer, populateTransaction, queryGraph, rBigInt, sleep, substring, toFixedHex, toFixedLength, unpackEncryptedMessage, validateUrl }; diff --git a/dist/index.umd.js b/dist/index.umd.js index b31ac2d..8ddd531 100644 --- a/dist/index.umd.js +++ b/dist/index.umd.js @@ -1759,10 +1759,9 @@ exports.isHexString = isHexString; /***/ }), /***/ 31708: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ ((__unused_webpack_module, exports) => { "use strict"; -/* provided dependency */ var console = __webpack_require__(96763); Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Lock = void 0; @@ -2195,7 +2194,7 @@ exports.Withdrawal = Withdrawal; /* eslint-disable jsdoc/check-indentation, jsdoc/match-description */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.decodeSingle = exports.decode = exports.encodePacked = exports.encodeSingle = exports.encode = void 0; -const utils_1 = __webpack_require__(22049); +const utils_1 = __webpack_require__(52367); const errors_1 = __webpack_require__(5961); const packer_1 = __webpack_require__(37700); /** @@ -2431,7 +2430,7 @@ exports.decodeSingle = decodeSingle; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ParserError = exports.getErrorStack = exports.getErrorMessage = void 0; -const utils_1 = __webpack_require__(22049); +const utils_1 = __webpack_require__(52367); /** * Attempt to get an error message from a value. * @@ -2528,7 +2527,7 @@ __exportStar(__webpack_require__(11126), exports); Object.defineProperty(exports, "__esModule", ({ value: true })); exports.iterate = void 0; -const utils_1 = __webpack_require__(22049); +const utils_1 = __webpack_require__(52367); /** * Iterate over a buffer with the specified size. This will yield a part of the * buffer starting at an increment of the specified size, until the end of the @@ -2568,7 +2567,7 @@ exports.iterate = iterate; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.unpack = exports.pack = exports.isDynamicParser = exports.getParser = void 0; -const utils_1 = __webpack_require__(22049); +const utils_1 = __webpack_require__(52367); const errors_1 = __webpack_require__(5961); const iterator_1 = __webpack_require__(57924); const parsers_1 = __webpack_require__(46207); @@ -2719,7 +2718,7 @@ exports.unpack = unpack; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.address = exports.getAddress = void 0; -const utils_1 = __webpack_require__(22049); +const utils_1 = __webpack_require__(52367); const errors_1 = __webpack_require__(5961); const utils_2 = __webpack_require__(26365); /** @@ -2803,7 +2802,7 @@ exports.address = { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.array = exports.getTupleType = exports.getArrayType = exports.isArrayType = void 0; -const utils_1 = __webpack_require__(22049); +const utils_1 = __webpack_require__(52367); const errors_1 = __webpack_require__(5961); const packer_1 = __webpack_require__(37700); const utils_2 = __webpack_require__(26365); @@ -2982,8 +2981,8 @@ exports.array = { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.bool = exports.getBooleanValue = void 0; -const utils_1 = __webpack_require__(22049); -const superstruct_1 = __webpack_require__(2150); +const superstruct_1 = __webpack_require__(35620); +const utils_1 = __webpack_require__(52367); const errors_1 = __webpack_require__(5961); const number_1 = __webpack_require__(6150); const BooleanCoercer = (0, superstruct_1.coerce)((0, superstruct_1.boolean)(), (0, superstruct_1.union)([(0, superstruct_1.literal)('true'), (0, superstruct_1.literal)('false')]), (value) => value === 'true'); @@ -3082,7 +3081,7 @@ exports.bool = { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.bytes = void 0; -const utils_1 = __webpack_require__(22049); +const utils_1 = __webpack_require__(52367); const utils_2 = __webpack_require__(26365); exports.bytes = { isDynamic: true, @@ -3157,7 +3156,7 @@ exports.bytes = { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fixedBytes = exports.getByteLength = void 0; -const utils_1 = __webpack_require__(22049); +const utils_1 = __webpack_require__(52367); const errors_1 = __webpack_require__(5961); const utils_2 = __webpack_require__(26365); const BYTES_REGEX = /^bytes([0-9]{1,2})$/u; @@ -3242,8 +3241,8 @@ exports.fixedBytes = { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fn = exports.getFunction = void 0; -const utils_1 = __webpack_require__(22049); -const superstruct_1 = __webpack_require__(2150); +const superstruct_1 = __webpack_require__(35620); +const utils_1 = __webpack_require__(52367); const errors_1 = __webpack_require__(5961); const fixed_bytes_1 = __webpack_require__(83415); /** @@ -3380,7 +3379,7 @@ __exportStar(__webpack_require__(30717), exports); Object.defineProperty(exports, "__esModule", ({ value: true })); exports.number = exports.getBigInt = exports.assertNumberLength = exports.getLength = exports.isSigned = void 0; -const utils_1 = __webpack_require__(22049); +const utils_1 = __webpack_require__(52367); const errors_1 = __webpack_require__(5961); const utils_2 = __webpack_require__(26365); const NUMBER_REGEX = /^u?int(?[0-9]*)?$/u; @@ -3552,7 +3551,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true })); exports.string = void 0; -const utils_1 = __webpack_require__(22049); +const utils_1 = __webpack_require__(52367); const bytes_1 = __webpack_require__(99356); exports.string = { isDynamic: true, @@ -3620,7 +3619,7 @@ exports.string = { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.tuple = exports.getTupleElements = void 0; -const utils_1 = __webpack_require__(22049); +const utils_1 = __webpack_require__(52367); const errors_1 = __webpack_require__(5961); const packer_1 = __webpack_require__(37700); const TUPLE_REGEX = /^\((.+)\)$/u; @@ -3782,7 +3781,7 @@ __exportStar(__webpack_require__(15744), exports); Object.defineProperty(exports, "__esModule", ({ value: true })); exports.padEnd = exports.padStart = exports.set = void 0; -const utils_1 = __webpack_require__(22049); +const utils_1 = __webpack_require__(52367); const BUFFER_WIDTH = 32; /** * Set `buffer` in `target` at the specified position. @@ -3886,8 +3885,8 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getEncryptionPublicKey = exports.decryptSafely = exports.decrypt = exports.encryptSafely = exports.encrypt = void 0; +const base_1 = __webpack_require__(63203); const nacl = __importStar(__webpack_require__(88947)); -const naclUtil = __importStar(__webpack_require__(76386)); const utils_1 = __webpack_require__(54907); /** * Encrypt a message. @@ -3918,21 +3917,21 @@ function encrypt({ publicKey, data, version, }) { // assemble encryption parameters - from string to UInt8 let pubKeyUInt8Array; try { - pubKeyUInt8Array = naclUtil.decodeBase64(publicKey); + pubKeyUInt8Array = base_1.base64.decode(publicKey); } catch (err) { throw new Error('Bad public key'); } - const msgParamsUInt8Array = naclUtil.decodeUTF8(data); + const msgParamsUInt8Array = base_1.utf8.decode(data); const nonce = nacl.randomBytes(nacl.box.nonceLength); // encrypt const encryptedMessage = nacl.box(msgParamsUInt8Array, nonce, pubKeyUInt8Array, ephemeralKeyPair.secretKey); // handle encrypted data const output = { version: 'x25519-xsalsa20-poly1305', - nonce: naclUtil.encodeBase64(nonce), - ephemPublicKey: naclUtil.encodeBase64(ephemeralKeyPair.publicKey), - ciphertext: naclUtil.encodeBase64(encryptedMessage), + nonce: base_1.base64.encode(nonce), + ephemPublicKey: base_1.base64.encode(ephemeralKeyPair.publicKey), + ciphertext: base_1.base64.encode(encryptedMessage), }; // return encrypted msg data return output; @@ -4006,13 +4005,12 @@ function decrypt({ encryptedData, privateKey, }) { } switch (encryptedData.version) { case 'x25519-xsalsa20-poly1305': { - // string to buffer to UInt8Array - const receiverPrivateKeyUint8Array = naclDecodeHex(privateKey); + const receiverPrivateKeyUint8Array = Buffer.from(privateKey, 'hex'); const receiverEncryptionPrivateKey = nacl.box.keyPair.fromSecretKey(receiverPrivateKeyUint8Array).secretKey; // assemble decryption parameters - const nonce = naclUtil.decodeBase64(encryptedData.nonce); - const ciphertext = naclUtil.decodeBase64(encryptedData.ciphertext); - const ephemPublicKey = naclUtil.decodeBase64(encryptedData.ephemPublicKey); + const nonce = base_1.base64.decode(encryptedData.nonce); + const ciphertext = base_1.base64.decode(encryptedData.ciphertext); + const ephemPublicKey = base_1.base64.decode(encryptedData.ephemPublicKey); // decrypt const decryptedMessage = nacl.box.open(ciphertext, nonce, ephemPublicKey, receiverEncryptionPrivateKey); // return decrypted msg data @@ -4020,7 +4018,7 @@ function decrypt({ encryptedData, privateKey, }) { if (!decryptedMessage) { throw new Error(); } - const output = naclUtil.encodeUTF8(decryptedMessage); + const output = base_1.utf8.encode(decryptedMessage); // TODO: This is probably extraneous but was kept to minimize changes during refactor if (!output) { throw new Error(); @@ -4065,21 +4063,11 @@ exports.decryptSafely = decryptSafely; * @returns The encryption public key. */ function getEncryptionPublicKey(privateKey) { - const privateKeyUint8Array = naclDecodeHex(privateKey); + const privateKeyUint8Array = Buffer.from(privateKey, 'hex'); const encryptionPublicKey = nacl.box.keyPair.fromSecretKey(privateKeyUint8Array).publicKey; - return naclUtil.encodeBase64(encryptionPublicKey); + return base_1.base64.encode(encryptionPublicKey); } exports.getEncryptionPublicKey = getEncryptionPublicKey; -/** - * Convert a hex string to the UInt8Array format used by nacl. - * - * @param msgHex - The string to convert. - * @returns The converted string. - */ -function naclDecodeHex(msgHex) { - const msgBase64 = Buffer.from(msgHex, 'hex').toString('base64'); - return naclUtil.decodeBase64(msgBase64); -} //# sourceMappingURL=encryption.js.map /***/ }), @@ -4217,7 +4205,7 @@ const util_1 = __webpack_require__(68683); const abi_utils_1 = __webpack_require__(93256); const parsers_1 = __webpack_require__(46207); const utils_1 = __webpack_require__(26365); -const utils_2 = __webpack_require__(22049); +const utils_2 = __webpack_require__(52367); const keccak_1 = __webpack_require__(32019); const utils_3 = __webpack_require__(54907); /** @@ -4850,7 +4838,7 @@ exports.recoverTypedSignature = recoverTypedSignature; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.normalize = exports.recoverPublicKey = exports.concatSig = exports.legacyToBuffer = exports.isNullish = exports.padWithZeroes = void 0; const util_1 = __webpack_require__(68683); -const utils_1 = __webpack_require__(22049); +const utils_1 = __webpack_require__(52367); /** * Pads the front of the given hex string with zeroes until it reaches the * target length. If the input string is already longer than or equal to the @@ -4956,1761 +4944,50 @@ exports.normalize = normalize; /***/ }), -/***/ 61275: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({value: true})); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }// src/logging.ts -var _debug = __webpack_require__(17833); var _debug2 = _interopRequireDefault(_debug); -var globalLogger = _debug2.default.call(void 0, "metamask"); -function createProjectLogger(projectName) { - return globalLogger.extend(projectName); -} -function createModuleLogger(projectLogger, moduleName) { - return projectLogger.extend(moduleName); -} - - - - -exports.createProjectLogger = createProjectLogger; exports.createModuleLogger = createModuleLogger; -//# sourceMappingURL=chunk-2LBGT4GH.js.map - -/***/ }), - -/***/ 85244: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({value: true}));var __accessCheck = (obj, member, msg) => { - if (!member.has(obj)) - throw TypeError("Cannot " + msg); -}; -var __privateGet = (obj, member, getter) => { - __accessCheck(obj, member, "read from private field"); - return getter ? getter.call(obj) : member.get(obj); -}; -var __privateAdd = (obj, member, value) => { - if (member.has(obj)) - throw TypeError("Cannot add the same private member more than once"); - member instanceof WeakSet ? member.add(obj) : member.set(obj, value); -}; -var __privateSet = (obj, member, value, setter) => { - __accessCheck(obj, member, "write to private field"); - setter ? setter.call(obj, value) : member.set(obj, value); - return value; -}; - - - - - -exports.__privateGet = __privateGet; exports.__privateAdd = __privateAdd; exports.__privateSet = __privateSet; -//# sourceMappingURL=chunk-3W5G4CYI.js.map - -/***/ }), - -/***/ 73631: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({value: true})); - -var _chunk6ZDHSOUVjs = __webpack_require__(40932); - -// src/versions.ts - - - - - - -var _semver = __webpack_require__(99589); -var _superstruct = __webpack_require__(2150); -var VersionStruct = _superstruct.refine.call(void 0, - _superstruct.string.call(void 0, ), - "Version", - (value) => { - if (_semver.valid.call(void 0, value) === null) { - return `Expected SemVer version, got "${value}"`; - } - return true; - } -); -var VersionRangeStruct = _superstruct.refine.call(void 0, - _superstruct.string.call(void 0, ), - "Version range", - (value) => { - if (_semver.validRange.call(void 0, value) === null) { - return `Expected SemVer range, got "${value}"`; - } - return true; - } -); -function isValidSemVerVersion(version) { - return _superstruct.is.call(void 0, version, VersionStruct); -} -function isValidSemVerRange(versionRange) { - return _superstruct.is.call(void 0, versionRange, VersionRangeStruct); -} -function assertIsSemVerVersion(version) { - _chunk6ZDHSOUVjs.assertStruct.call(void 0, version, VersionStruct); -} -function assertIsSemVerRange(range) { - _chunk6ZDHSOUVjs.assertStruct.call(void 0, range, VersionRangeStruct); -} -function gtVersion(version1, version2) { - return _semver.gt.call(void 0, version1, version2); -} -function gtRange(version, range) { - return _semver.gtr.call(void 0, version, range); -} -function satisfiesVersionRange(version, versionRange) { - return _semver.satisfies.call(void 0, version, versionRange, { - includePrerelease: true - }); -} - - - - - - - - - - - -exports.VersionStruct = VersionStruct; exports.VersionRangeStruct = VersionRangeStruct; exports.isValidSemVerVersion = isValidSemVerVersion; exports.isValidSemVerRange = isValidSemVerRange; exports.assertIsSemVerVersion = assertIsSemVerVersion; exports.assertIsSemVerRange = assertIsSemVerRange; exports.gtVersion = gtVersion; exports.gtRange = gtRange; exports.satisfiesVersionRange = satisfiesVersionRange; -//# sourceMappingURL=chunk-4D6XQBHA.js.map - -/***/ }), - -/***/ 69116: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({value: true}));// src/time.ts -var Duration = /* @__PURE__ */ ((Duration2) => { - Duration2[Duration2["Millisecond"] = 1] = "Millisecond"; - Duration2[Duration2["Second"] = 1e3] = "Second"; - Duration2[Duration2["Minute"] = 6e4] = "Minute"; - Duration2[Duration2["Hour"] = 36e5] = "Hour"; - Duration2[Duration2["Day"] = 864e5] = "Day"; - Duration2[Duration2["Week"] = 6048e5] = "Week"; - Duration2[Duration2["Year"] = 31536e6] = "Year"; - return Duration2; -})(Duration || {}); -var isNonNegativeInteger = (number) => Number.isInteger(number) && number >= 0; -var assertIsNonNegativeInteger = (number, name) => { - if (!isNonNegativeInteger(number)) { - throw new Error( - `"${name}" must be a non-negative integer. Received: "${number}".` - ); - } -}; -function inMilliseconds(count, duration) { - assertIsNonNegativeInteger(count, "count"); - return count * duration; -} -function timeSince(timestamp) { - assertIsNonNegativeInteger(timestamp, "timestamp"); - return Date.now() - timestamp; -} - - - - - -exports.Duration = Duration; exports.inMilliseconds = inMilliseconds; exports.timeSince = timeSince; -//# sourceMappingURL=chunk-4RMX5YWE.js.map - -/***/ }), - -/***/ 87982: -/***/ (() => { - -"use strict"; -//# sourceMappingURL=chunk-5AVWINSB.js.map - -/***/ }), - -/***/ 21848: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({value: true})); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } - -var _chunk6ZDHSOUVjs = __webpack_require__(40932); - -// src/base64.ts -var _superstruct = __webpack_require__(2150); -var base64 = (struct, options = {}) => { - const paddingRequired = _nullishCoalesce(options.paddingRequired, () => ( false)); - const characterSet = _nullishCoalesce(options.characterSet, () => ( "base64")); - let letters; - if (characterSet === "base64") { - letters = String.raw`[A-Za-z0-9+\/]`; - } else { - _chunk6ZDHSOUVjs.assert.call(void 0, characterSet === "base64url"); - letters = String.raw`[-_A-Za-z0-9]`; - } - let re; - if (paddingRequired) { - re = new RegExp( - `^(?:${letters}{4})*(?:${letters}{3}=|${letters}{2}==)?$`, - "u" - ); - } else { - re = new RegExp( - `^(?:${letters}{4})*(?:${letters}{2,3}|${letters}{3}=|${letters}{2}==)?$`, - "u" - ); - } - return _superstruct.pattern.call(void 0, struct, re); -}; - - - -exports.base64 = base64; -//# sourceMappingURL=chunk-6NZW4WK4.js.map - -/***/ }), - -/***/ 40932: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({value: true})); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } - -var _chunkIZC266HSjs = __webpack_require__(1486); - -// src/assert.ts -var _superstruct = __webpack_require__(2150); -function isConstructable(fn) { - return Boolean(typeof _optionalChain([fn, 'optionalAccess', _ => _.prototype, 'optionalAccess', _2 => _2.constructor, 'optionalAccess', _3 => _3.name]) === "string"); -} -function getErrorMessageWithoutTrailingPeriod(error) { - return _chunkIZC266HSjs.getErrorMessage.call(void 0, error).replace(/\.$/u, ""); -} -function getError(ErrorWrapper, message) { - if (isConstructable(ErrorWrapper)) { - return new ErrorWrapper({ - message - }); - } - return ErrorWrapper({ - message - }); -} -var AssertionError = class extends Error { - constructor(options) { - super(options.message); - this.code = "ERR_ASSERTION"; - } -}; -function assert(value, message = "Assertion failed.", ErrorWrapper = AssertionError) { - if (!value) { - if (message instanceof Error) { - throw message; - } - throw getError(ErrorWrapper, message); - } -} -function assertStruct(value, struct, errorPrefix = "Assertion failed", ErrorWrapper = AssertionError) { - try { - _superstruct.assert.call(void 0, value, struct); - } catch (error) { - throw getError( - ErrorWrapper, - `${errorPrefix}: ${getErrorMessageWithoutTrailingPeriod(error)}.` - ); - } -} -function assertExhaustive(_object) { - throw new Error( - "Invalid branch reached. Should be detected during compilation." - ); -} - - - - - - -exports.AssertionError = AssertionError; exports.assert = assert; exports.assertStruct = assertStruct; exports.assertExhaustive = assertExhaustive; -//# sourceMappingURL=chunk-6ZDHSOUV.js.map - -/***/ }), - -/***/ 39705: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({value: true}));// src/promise.ts -function createDeferredPromise({ - suppressUnhandledRejection = false -} = {}) { - let resolve; - let reject; - const promise = new Promise( - (innerResolve, innerReject) => { - resolve = innerResolve; - reject = innerReject; - } - ); - if (suppressUnhandledRejection) { - promise.catch((_error) => { - }); - } - return { promise, resolve, reject }; -} - - - -exports.createDeferredPromise = createDeferredPromise; -//# sourceMappingURL=chunk-C6HGFEYL.js.map - -/***/ }), - -/***/ 1203: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({value: true})); - - - -var _chunkQEPVHEP7js = __webpack_require__(75363); - - -var _chunk6ZDHSOUVjs = __webpack_require__(40932); - -// src/coercers.ts - - - - - - - - - -var _superstruct = __webpack_require__(2150); -var NumberLikeStruct = _superstruct.union.call(void 0, [_superstruct.number.call(void 0, ), _superstruct.bigint.call(void 0, ), _superstruct.string.call(void 0, ), _chunkQEPVHEP7js.StrictHexStruct]); -var NumberCoercer = _superstruct.coerce.call(void 0, _superstruct.number.call(void 0, ), NumberLikeStruct, Number); -var BigIntCoercer = _superstruct.coerce.call(void 0, _superstruct.bigint.call(void 0, ), NumberLikeStruct, BigInt); -var BytesLikeStruct = _superstruct.union.call(void 0, [_chunkQEPVHEP7js.StrictHexStruct, _superstruct.instance.call(void 0, Uint8Array)]); -var BytesCoercer = _superstruct.coerce.call(void 0, - _superstruct.instance.call(void 0, Uint8Array), - _superstruct.union.call(void 0, [_chunkQEPVHEP7js.StrictHexStruct]), - _chunkQEPVHEP7js.hexToBytes -); -var HexCoercer = _superstruct.coerce.call(void 0, _chunkQEPVHEP7js.StrictHexStruct, _superstruct.instance.call(void 0, Uint8Array), _chunkQEPVHEP7js.bytesToHex); -function createNumber(value) { - try { - const result = _superstruct.create.call(void 0, value, NumberCoercer); - _chunk6ZDHSOUVjs.assert.call(void 0, - Number.isFinite(result), - `Expected a number-like value, got "${value}".` - ); - return result; - } catch (error) { - if (error instanceof _superstruct.StructError) { - throw new Error(`Expected a number-like value, got "${value}".`); - } - throw error; - } -} -function createBigInt(value) { - try { - return _superstruct.create.call(void 0, value, BigIntCoercer); - } catch (error) { - if (error instanceof _superstruct.StructError) { - throw new Error( - `Expected a number-like value, got "${String(error.value)}".` - ); - } - throw error; - } -} -function createBytes(value) { - if (typeof value === "string" && value.toLowerCase() === "0x") { - return new Uint8Array(); - } - try { - return _superstruct.create.call(void 0, value, BytesCoercer); - } catch (error) { - if (error instanceof _superstruct.StructError) { - throw new Error( - `Expected a bytes-like value, got "${String(error.value)}".` - ); - } - throw error; - } -} -function createHex(value) { - if (value instanceof Uint8Array && value.length === 0 || typeof value === "string" && value.toLowerCase() === "0x") { - return "0x"; - } - try { - return _superstruct.create.call(void 0, value, HexCoercer); - } catch (error) { - if (error instanceof _superstruct.StructError) { - throw new Error( - `Expected a bytes-like value, got "${String(error.value)}".` - ); - } - throw error; - } -} - - - - - - -exports.createNumber = createNumber; exports.createBigInt = createBigInt; exports.createBytes = createBytes; exports.createHex = createHex; -//# sourceMappingURL=chunk-DHVKFDHQ.js.map - -/***/ }), - -/***/ 1508: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({value: true})); - -var _chunk6NZW4WK4js = __webpack_require__(21848); - -// src/checksum.ts -var _superstruct = __webpack_require__(2150); -var ChecksumStruct = _superstruct.size.call(void 0, - _chunk6NZW4WK4js.base64.call(void 0, _superstruct.string.call(void 0, ), { paddingRequired: true }), - 44, - 44 -); - - - -exports.ChecksumStruct = ChecksumStruct; -//# sourceMappingURL=chunk-E4C7EW4R.js.map - -/***/ }), - -/***/ 51423: -/***/ (() => { - -"use strict"; -//# sourceMappingURL=chunk-EQMZL4XU.js.map - -/***/ }), - -/***/ 1486: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({value: true})); - - -var _chunkQVEKZRZ2js = __webpack_require__(96526); - -// src/errors.ts -var _ponycause = __webpack_require__(71843); -function isError(error) { - return error instanceof Error || _chunkQVEKZRZ2js.isObject.call(void 0, error) && error.constructor.name === "Error"; -} -function isErrorWithCode(error) { - return typeof error === "object" && error !== null && "code" in error; -} -function isErrorWithMessage(error) { - return typeof error === "object" && error !== null && "message" in error; -} -function isErrorWithStack(error) { - return typeof error === "object" && error !== null && "stack" in error; -} -function getErrorMessage(error) { - if (isErrorWithMessage(error) && typeof error.message === "string") { - return error.message; - } - if (_chunkQVEKZRZ2js.isNullOrUndefined.call(void 0, error)) { - return ""; - } - return String(error); -} -function wrapError(originalError, message) { - if (isError(originalError)) { - let error; - if (Error.length === 2) { - error = new Error(message, { cause: originalError }); - } else { - error = new (0, _ponycause.ErrorWithCause)(message, { cause: originalError }); - } - if (isErrorWithCode(originalError)) { - error.code = originalError.code; - } - return error; - } - if (message.length > 0) { - return new Error(`${String(originalError)}: ${message}`); - } - return new Error(String(originalError)); -} - - - - - - - -exports.isErrorWithCode = isErrorWithCode; exports.isErrorWithMessage = isErrorWithMessage; exports.isErrorWithStack = isErrorWithStack; exports.getErrorMessage = getErrorMessage; exports.wrapError = wrapError; -//# sourceMappingURL=chunk-IZC266HS.js.map - -/***/ }), - -/***/ 58383: -/***/ (() => { - -"use strict"; -//# sourceMappingURL=chunk-LC2CRSWD.js.map - -/***/ }), - -/***/ 87427: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({value: true})); - -var _chunk6ZDHSOUVjs = __webpack_require__(40932); - - -var _chunkQVEKZRZ2js = __webpack_require__(96526); - -// src/json.ts - - - - - - - - - - - - - - - - - - - - -var _superstruct = __webpack_require__(2150); -var object = (schema) => ( - // The type is slightly different from a regular object struct, because we - // want to make properties with `undefined` in their type optional, but not - // `undefined` itself. This means that we need a type cast. - _superstruct.object.call(void 0, schema) -); -function hasOptional({ path, branch }) { - const field = path[path.length - 1]; - return _chunkQVEKZRZ2js.hasProperty.call(void 0, branch[branch.length - 2], field); -} -function exactOptional(struct) { - return new (0, _superstruct.Struct)({ - ...struct, - type: `optional ${struct.type}`, - validator: (value, context) => !hasOptional(context) || struct.validator(value, context), - refiner: (value, context) => !hasOptional(context) || struct.refiner(value, context) - }); -} -var finiteNumber = () => _superstruct.define.call(void 0, "finite number", (value) => { - return _superstruct.is.call(void 0, value, _superstruct.number.call(void 0, )) && Number.isFinite(value); -}); -var UnsafeJsonStruct = _superstruct.union.call(void 0, [ - _superstruct.literal.call(void 0, null), - _superstruct.boolean.call(void 0, ), - finiteNumber(), - _superstruct.string.call(void 0, ), - _superstruct.array.call(void 0, _superstruct.lazy.call(void 0, () => UnsafeJsonStruct)), - _superstruct.record.call(void 0, - _superstruct.string.call(void 0, ), - _superstruct.lazy.call(void 0, () => UnsafeJsonStruct) - ) -]); -var JsonStruct = _superstruct.coerce.call(void 0, UnsafeJsonStruct, _superstruct.any.call(void 0, ), (value) => { - _chunk6ZDHSOUVjs.assertStruct.call(void 0, value, UnsafeJsonStruct); - return JSON.parse( - JSON.stringify(value, (propKey, propValue) => { - if (propKey === "__proto__" || propKey === "constructor") { - return void 0; - } - return propValue; - }) - ); -}); -function isValidJson(value) { - try { - getSafeJson(value); - return true; - } catch (e) { - return false; - } -} -function getSafeJson(value) { - return _superstruct.create.call(void 0, value, JsonStruct); -} -function getJsonSize(value) { - _chunk6ZDHSOUVjs.assertStruct.call(void 0, value, JsonStruct, "Invalid JSON value"); - const json = JSON.stringify(value); - return new TextEncoder().encode(json).byteLength; -} -var jsonrpc2 = "2.0"; -var JsonRpcVersionStruct = _superstruct.literal.call(void 0, jsonrpc2); -var JsonRpcIdStruct = _superstruct.nullable.call(void 0, _superstruct.union.call(void 0, [_superstruct.number.call(void 0, ), _superstruct.string.call(void 0, )])); -var JsonRpcErrorStruct = object({ - code: _superstruct.integer.call(void 0, ), - message: _superstruct.string.call(void 0, ), - data: exactOptional(JsonStruct), - stack: exactOptional(_superstruct.string.call(void 0, )) -}); -var JsonRpcParamsStruct = _superstruct.union.call(void 0, [_superstruct.record.call(void 0, _superstruct.string.call(void 0, ), JsonStruct), _superstruct.array.call(void 0, JsonStruct)]); -var JsonRpcRequestStruct = object({ - id: JsonRpcIdStruct, - jsonrpc: JsonRpcVersionStruct, - method: _superstruct.string.call(void 0, ), - params: exactOptional(JsonRpcParamsStruct) -}); -var JsonRpcNotificationStruct = object({ - jsonrpc: JsonRpcVersionStruct, - method: _superstruct.string.call(void 0, ), - params: exactOptional(JsonRpcParamsStruct) -}); -function isJsonRpcNotification(value) { - return _superstruct.is.call(void 0, value, JsonRpcNotificationStruct); -} -function assertIsJsonRpcNotification(value, ErrorWrapper) { - _chunk6ZDHSOUVjs.assertStruct.call(void 0, - value, - JsonRpcNotificationStruct, - "Invalid JSON-RPC notification", - ErrorWrapper - ); -} -function isJsonRpcRequest(value) { - return _superstruct.is.call(void 0, value, JsonRpcRequestStruct); -} -function assertIsJsonRpcRequest(value, ErrorWrapper) { - _chunk6ZDHSOUVjs.assertStruct.call(void 0, - value, - JsonRpcRequestStruct, - "Invalid JSON-RPC request", - ErrorWrapper - ); -} -var PendingJsonRpcResponseStruct = _superstruct.object.call(void 0, { - id: JsonRpcIdStruct, - jsonrpc: JsonRpcVersionStruct, - result: _superstruct.optional.call(void 0, _superstruct.unknown.call(void 0, )), - error: _superstruct.optional.call(void 0, JsonRpcErrorStruct) -}); -var JsonRpcSuccessStruct = object({ - id: JsonRpcIdStruct, - jsonrpc: JsonRpcVersionStruct, - result: JsonStruct -}); -var JsonRpcFailureStruct = object({ - id: JsonRpcIdStruct, - jsonrpc: JsonRpcVersionStruct, - error: JsonRpcErrorStruct -}); -var JsonRpcResponseStruct = _superstruct.union.call(void 0, [ - JsonRpcSuccessStruct, - JsonRpcFailureStruct -]); -function isPendingJsonRpcResponse(response) { - return _superstruct.is.call(void 0, response, PendingJsonRpcResponseStruct); -} -function assertIsPendingJsonRpcResponse(response, ErrorWrapper) { - _chunk6ZDHSOUVjs.assertStruct.call(void 0, - response, - PendingJsonRpcResponseStruct, - "Invalid pending JSON-RPC response", - ErrorWrapper - ); -} -function isJsonRpcResponse(response) { - return _superstruct.is.call(void 0, response, JsonRpcResponseStruct); -} -function assertIsJsonRpcResponse(value, ErrorWrapper) { - _chunk6ZDHSOUVjs.assertStruct.call(void 0, - value, - JsonRpcResponseStruct, - "Invalid JSON-RPC response", - ErrorWrapper - ); -} -function isJsonRpcSuccess(value) { - return _superstruct.is.call(void 0, value, JsonRpcSuccessStruct); -} -function assertIsJsonRpcSuccess(value, ErrorWrapper) { - _chunk6ZDHSOUVjs.assertStruct.call(void 0, - value, - JsonRpcSuccessStruct, - "Invalid JSON-RPC success response", - ErrorWrapper - ); -} -function isJsonRpcFailure(value) { - return _superstruct.is.call(void 0, value, JsonRpcFailureStruct); -} -function assertIsJsonRpcFailure(value, ErrorWrapper) { - _chunk6ZDHSOUVjs.assertStruct.call(void 0, - value, - JsonRpcFailureStruct, - "Invalid JSON-RPC failure response", - ErrorWrapper - ); -} -function isJsonRpcError(value) { - return _superstruct.is.call(void 0, value, JsonRpcErrorStruct); -} -function assertIsJsonRpcError(value, ErrorWrapper) { - _chunk6ZDHSOUVjs.assertStruct.call(void 0, - value, - JsonRpcErrorStruct, - "Invalid JSON-RPC error", - ErrorWrapper - ); -} -function getJsonRpcIdValidator(options) { - const { permitEmptyString, permitFractions, permitNull } = { - permitEmptyString: true, - permitFractions: false, - permitNull: true, - ...options - }; - const isValidJsonRpcId = (id) => { - return Boolean( - typeof id === "number" && (permitFractions || Number.isInteger(id)) || typeof id === "string" && (permitEmptyString || id.length > 0) || permitNull && id === null - ); - }; - return isValidJsonRpcId; -} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -exports.object = object; exports.exactOptional = exactOptional; exports.UnsafeJsonStruct = UnsafeJsonStruct; exports.JsonStruct = JsonStruct; exports.isValidJson = isValidJson; exports.getSafeJson = getSafeJson; exports.getJsonSize = getJsonSize; exports.jsonrpc2 = jsonrpc2; exports.JsonRpcVersionStruct = JsonRpcVersionStruct; exports.JsonRpcIdStruct = JsonRpcIdStruct; exports.JsonRpcErrorStruct = JsonRpcErrorStruct; exports.JsonRpcParamsStruct = JsonRpcParamsStruct; exports.JsonRpcRequestStruct = JsonRpcRequestStruct; exports.JsonRpcNotificationStruct = JsonRpcNotificationStruct; exports.isJsonRpcNotification = isJsonRpcNotification; exports.assertIsJsonRpcNotification = assertIsJsonRpcNotification; exports.isJsonRpcRequest = isJsonRpcRequest; exports.assertIsJsonRpcRequest = assertIsJsonRpcRequest; exports.PendingJsonRpcResponseStruct = PendingJsonRpcResponseStruct; exports.JsonRpcSuccessStruct = JsonRpcSuccessStruct; exports.JsonRpcFailureStruct = JsonRpcFailureStruct; exports.JsonRpcResponseStruct = JsonRpcResponseStruct; exports.isPendingJsonRpcResponse = isPendingJsonRpcResponse; exports.assertIsPendingJsonRpcResponse = assertIsPendingJsonRpcResponse; exports.isJsonRpcResponse = isJsonRpcResponse; exports.assertIsJsonRpcResponse = assertIsJsonRpcResponse; exports.isJsonRpcSuccess = isJsonRpcSuccess; exports.assertIsJsonRpcSuccess = assertIsJsonRpcSuccess; exports.isJsonRpcFailure = isJsonRpcFailure; exports.assertIsJsonRpcFailure = assertIsJsonRpcFailure; exports.isJsonRpcError = isJsonRpcError; exports.assertIsJsonRpcError = assertIsJsonRpcError; exports.getJsonRpcIdValidator = getJsonRpcIdValidator; -//# sourceMappingURL=chunk-OLLG4H35.js.map - -/***/ }), - -/***/ 75363: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; -/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; -Object.defineProperty(exports, "__esModule", ({value: true})); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } - -var _chunk6ZDHSOUVjs = __webpack_require__(40932); - -// src/hex.ts -var _sha3 = __webpack_require__(2214); -var _superstruct = __webpack_require__(2150); - -// src/bytes.ts -var _base = __webpack_require__(63203); -var HEX_MINIMUM_NUMBER_CHARACTER = 48; -var HEX_MAXIMUM_NUMBER_CHARACTER = 58; -var HEX_CHARACTER_OFFSET = 87; -function getPrecomputedHexValuesBuilder() { - const lookupTable = []; - return () => { - if (lookupTable.length === 0) { - for (let i = 0; i < 256; i++) { - lookupTable.push(i.toString(16).padStart(2, "0")); - } - } - return lookupTable; - }; -} -var getPrecomputedHexValues = getPrecomputedHexValuesBuilder(); -function isBytes(value) { - return value instanceof Uint8Array; -} -function assertIsBytes(value) { - _chunk6ZDHSOUVjs.assert.call(void 0, isBytes(value), "Value must be a Uint8Array."); -} -function bytesToHex(bytes) { - assertIsBytes(bytes); - if (bytes.length === 0) { - return "0x"; - } - const lookupTable = getPrecomputedHexValues(); - const hexadecimal = new Array(bytes.length); - for (let i = 0; i < bytes.length; i++) { - hexadecimal[i] = lookupTable[bytes[i]]; - } - return add0x(hexadecimal.join("")); -} -function bytesToBigInt(bytes) { - assertIsBytes(bytes); - const hexadecimal = bytesToHex(bytes); - return BigInt(hexadecimal); -} -function bytesToSignedBigInt(bytes) { - assertIsBytes(bytes); - let value = BigInt(0); - for (const byte of bytes) { - value = (value << BigInt(8)) + BigInt(byte); - } - return BigInt.asIntN(bytes.length * 8, value); -} -function bytesToNumber(bytes) { - assertIsBytes(bytes); - const bigint = bytesToBigInt(bytes); - _chunk6ZDHSOUVjs.assert.call(void 0, - bigint <= BigInt(Number.MAX_SAFE_INTEGER), - "Number is not a safe integer. Use `bytesToBigInt` instead." - ); - return Number(bigint); -} -function bytesToString(bytes) { - assertIsBytes(bytes); - return new TextDecoder().decode(bytes); -} -function bytesToBase64(bytes) { - assertIsBytes(bytes); - return _base.base64.encode(bytes); -} -function hexToBytes(value) { - if (_optionalChain([value, 'optionalAccess', _ => _.toLowerCase, 'optionalCall', _2 => _2()]) === "0x") { - return new Uint8Array(); - } - assertIsHexString(value); - const strippedValue = remove0x(value).toLowerCase(); - const normalizedValue = strippedValue.length % 2 === 0 ? strippedValue : `0${strippedValue}`; - const bytes = new Uint8Array(normalizedValue.length / 2); - for (let i = 0; i < bytes.length; i++) { - const c1 = normalizedValue.charCodeAt(i * 2); - const c2 = normalizedValue.charCodeAt(i * 2 + 1); - const n1 = c1 - (c1 < HEX_MAXIMUM_NUMBER_CHARACTER ? HEX_MINIMUM_NUMBER_CHARACTER : HEX_CHARACTER_OFFSET); - const n2 = c2 - (c2 < HEX_MAXIMUM_NUMBER_CHARACTER ? HEX_MINIMUM_NUMBER_CHARACTER : HEX_CHARACTER_OFFSET); - bytes[i] = n1 * 16 + n2; - } - return bytes; -} -function bigIntToBytes(value) { - _chunk6ZDHSOUVjs.assert.call(void 0, typeof value === "bigint", "Value must be a bigint."); - _chunk6ZDHSOUVjs.assert.call(void 0, value >= BigInt(0), "Value must be a non-negative bigint."); - const hexadecimal = value.toString(16); - return hexToBytes(hexadecimal); -} -function bigIntFits(value, bytes) { - _chunk6ZDHSOUVjs.assert.call(void 0, bytes > 0); - const mask = value >> BigInt(31); - return !((~value & mask) + (value & ~mask) >> BigInt(bytes * 8 + ~0)); -} -function signedBigIntToBytes(value, byteLength) { - _chunk6ZDHSOUVjs.assert.call(void 0, typeof value === "bigint", "Value must be a bigint."); - _chunk6ZDHSOUVjs.assert.call(void 0, typeof byteLength === "number", "Byte length must be a number."); - _chunk6ZDHSOUVjs.assert.call(void 0, byteLength > 0, "Byte length must be greater than 0."); - _chunk6ZDHSOUVjs.assert.call(void 0, - bigIntFits(value, byteLength), - "Byte length is too small to represent the given value." - ); - let numberValue = value; - const bytes = new Uint8Array(byteLength); - for (let i = 0; i < bytes.length; i++) { - bytes[i] = Number(BigInt.asUintN(8, numberValue)); - numberValue >>= BigInt(8); - } - return bytes.reverse(); -} -function numberToBytes(value) { - _chunk6ZDHSOUVjs.assert.call(void 0, typeof value === "number", "Value must be a number."); - _chunk6ZDHSOUVjs.assert.call(void 0, value >= 0, "Value must be a non-negative number."); - _chunk6ZDHSOUVjs.assert.call(void 0, - Number.isSafeInteger(value), - "Value is not a safe integer. Use `bigIntToBytes` instead." - ); - const hexadecimal = value.toString(16); - return hexToBytes(hexadecimal); -} -function stringToBytes(value) { - _chunk6ZDHSOUVjs.assert.call(void 0, typeof value === "string", "Value must be a string."); - return new TextEncoder().encode(value); -} -function base64ToBytes(value) { - _chunk6ZDHSOUVjs.assert.call(void 0, typeof value === "string", "Value must be a string."); - return _base.base64.decode(value); -} -function valueToBytes(value) { - if (typeof value === "bigint") { - return bigIntToBytes(value); - } - if (typeof value === "number") { - return numberToBytes(value); - } - if (typeof value === "string") { - if (value.startsWith("0x")) { - return hexToBytes(value); - } - return stringToBytes(value); - } - if (isBytes(value)) { - return value; - } - throw new TypeError(`Unsupported value type: "${typeof value}".`); -} -function concatBytes(values) { - const normalizedValues = new Array(values.length); - let byteLength = 0; - for (let i = 0; i < values.length; i++) { - const value = valueToBytes(values[i]); - normalizedValues[i] = value; - byteLength += value.length; - } - const bytes = new Uint8Array(byteLength); - for (let i = 0, offset = 0; i < normalizedValues.length; i++) { - bytes.set(normalizedValues[i], offset); - offset += normalizedValues[i].length; - } - return bytes; -} -function createDataView(bytes) { - if (typeof Buffer !== "undefined" && bytes instanceof Buffer) { - const buffer = bytes.buffer.slice( - bytes.byteOffset, - bytes.byteOffset + bytes.byteLength - ); - return new DataView(buffer); - } - return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); -} - -// src/hex.ts -var HexStruct = _superstruct.pattern.call(void 0, _superstruct.string.call(void 0, ), /^(?:0x)?[0-9a-f]+$/iu); -var StrictHexStruct = _superstruct.pattern.call(void 0, _superstruct.string.call(void 0, ), /^0x[0-9a-f]+$/iu); -var HexAddressStruct = _superstruct.pattern.call(void 0, - _superstruct.string.call(void 0, ), - /^0x[0-9a-f]{40}$/u -); -var HexChecksumAddressStruct = _superstruct.pattern.call(void 0, - _superstruct.string.call(void 0, ), - /^0x[0-9a-fA-F]{40}$/u -); -function isHexString(value) { - return _superstruct.is.call(void 0, value, HexStruct); -} -function isStrictHexString(value) { - return _superstruct.is.call(void 0, value, StrictHexStruct); -} -function assertIsHexString(value) { - _chunk6ZDHSOUVjs.assert.call(void 0, isHexString(value), "Value must be a hexadecimal string."); -} -function assertIsStrictHexString(value) { - _chunk6ZDHSOUVjs.assert.call(void 0, - isStrictHexString(value), - 'Value must be a hexadecimal string, starting with "0x".' - ); -} -function isValidHexAddress(possibleAddress) { - return _superstruct.is.call(void 0, possibleAddress, HexAddressStruct) || isValidChecksumAddress(possibleAddress); -} -function getChecksumAddress(address) { - _chunk6ZDHSOUVjs.assert.call(void 0, _superstruct.is.call(void 0, address, HexChecksumAddressStruct), "Invalid hex address."); - const unPrefixed = remove0x(address.toLowerCase()); - const unPrefixedHash = remove0x(bytesToHex(_sha3.keccak_256.call(void 0, unPrefixed))); - return `0x${unPrefixed.split("").map((character, nibbleIndex) => { - const hashCharacter = unPrefixedHash[nibbleIndex]; - _chunk6ZDHSOUVjs.assert.call(void 0, _superstruct.is.call(void 0, hashCharacter, _superstruct.string.call(void 0, )), "Hash shorter than address."); - return parseInt(hashCharacter, 16) > 7 ? character.toUpperCase() : character; - }).join("")}`; -} -function isValidChecksumAddress(possibleChecksum) { - if (!_superstruct.is.call(void 0, possibleChecksum, HexChecksumAddressStruct)) { - return false; - } - return getChecksumAddress(possibleChecksum) === possibleChecksum; -} -function add0x(hexadecimal) { - if (hexadecimal.startsWith("0x")) { - return hexadecimal; - } - if (hexadecimal.startsWith("0X")) { - return `0x${hexadecimal.substring(2)}`; - } - return `0x${hexadecimal}`; -} -function remove0x(hexadecimal) { - if (hexadecimal.startsWith("0x") || hexadecimal.startsWith("0X")) { - return hexadecimal.substring(2); - } - return hexadecimal; -} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -exports.HexStruct = HexStruct; exports.StrictHexStruct = StrictHexStruct; exports.HexAddressStruct = HexAddressStruct; exports.HexChecksumAddressStruct = HexChecksumAddressStruct; exports.isHexString = isHexString; exports.isStrictHexString = isStrictHexString; exports.assertIsHexString = assertIsHexString; exports.assertIsStrictHexString = assertIsStrictHexString; exports.isValidHexAddress = isValidHexAddress; exports.getChecksumAddress = getChecksumAddress; exports.isValidChecksumAddress = isValidChecksumAddress; exports.add0x = add0x; exports.remove0x = remove0x; exports.isBytes = isBytes; exports.assertIsBytes = assertIsBytes; exports.bytesToHex = bytesToHex; exports.bytesToBigInt = bytesToBigInt; exports.bytesToSignedBigInt = bytesToSignedBigInt; exports.bytesToNumber = bytesToNumber; exports.bytesToString = bytesToString; exports.bytesToBase64 = bytesToBase64; exports.hexToBytes = hexToBytes; exports.bigIntToBytes = bigIntToBytes; exports.signedBigIntToBytes = signedBigIntToBytes; exports.numberToBytes = numberToBytes; exports.stringToBytes = stringToBytes; exports.base64ToBytes = base64ToBytes; exports.valueToBytes = valueToBytes; exports.concatBytes = concatBytes; exports.createDataView = createDataView; -//# sourceMappingURL=chunk-QEPVHEP7.js.map - -/***/ }), - -/***/ 96526: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({value: true})); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// src/misc.ts -function isNonEmptyArray(value) { - return Array.isArray(value) && value.length > 0; -} -function isNullOrUndefined(value) { - return value === null || value === void 0; -} -function isObject(value) { - return Boolean(value) && typeof value === "object" && !Array.isArray(value); -} -var hasProperty = (objectToCheck, name) => Object.hasOwnProperty.call(objectToCheck, name); -function getKnownPropertyNames(object) { - return Object.getOwnPropertyNames(object); -} -var JsonSize = /* @__PURE__ */ ((JsonSize2) => { - JsonSize2[JsonSize2["Null"] = 4] = "Null"; - JsonSize2[JsonSize2["Comma"] = 1] = "Comma"; - JsonSize2[JsonSize2["Wrapper"] = 1] = "Wrapper"; - JsonSize2[JsonSize2["True"] = 4] = "True"; - JsonSize2[JsonSize2["False"] = 5] = "False"; - JsonSize2[JsonSize2["Quote"] = 1] = "Quote"; - JsonSize2[JsonSize2["Colon"] = 1] = "Colon"; - JsonSize2[JsonSize2["Date"] = 24] = "Date"; - return JsonSize2; -})(JsonSize || {}); -var ESCAPE_CHARACTERS_REGEXP = /"|\\|\n|\r|\t/gu; -function isPlainObject(value) { - if (typeof value !== "object" || value === null) { - return false; - } - try { - let proto = value; - while (Object.getPrototypeOf(proto) !== null) { - proto = Object.getPrototypeOf(proto); - } - return Object.getPrototypeOf(value) === proto; - } catch (_) { - return false; - } -} -function isASCII(character) { - return character.charCodeAt(0) <= 127; -} -function calculateStringSize(value) { - const size = value.split("").reduce((total, character) => { - if (isASCII(character)) { - return total + 1; - } - return total + 2; - }, 0); - return size + (_nullishCoalesce(value.match(ESCAPE_CHARACTERS_REGEXP), () => ( []))).length; -} -function calculateNumberSize(value) { - return value.toString().length; -} - - - - - - - - - - - - - -exports.isNonEmptyArray = isNonEmptyArray; exports.isNullOrUndefined = isNullOrUndefined; exports.isObject = isObject; exports.hasProperty = hasProperty; exports.getKnownPropertyNames = getKnownPropertyNames; exports.JsonSize = JsonSize; exports.ESCAPE_CHARACTERS_REGEXP = ESCAPE_CHARACTERS_REGEXP; exports.isPlainObject = isPlainObject; exports.isASCII = isASCII; exports.calculateStringSize = calculateStringSize; exports.calculateNumberSize = calculateNumberSize; -//# sourceMappingURL=chunk-QVEKZRZ2.js.map - -/***/ }), - -/***/ 61305: -/***/ (() => { - -"use strict"; -//# sourceMappingURL=chunk-RKRGAFXY.js.map - -/***/ }), - -/***/ 43207: -/***/ (() => { - -"use strict"; -//# sourceMappingURL=chunk-UOTVU7OQ.js.map - -/***/ }), - -/***/ 41535: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({value: true})); - - -var _chunkQEPVHEP7js = __webpack_require__(75363); - - -var _chunk6ZDHSOUVjs = __webpack_require__(40932); - -// src/number.ts -var numberToHex = (value) => { - _chunk6ZDHSOUVjs.assert.call(void 0, typeof value === "number", "Value must be a number."); - _chunk6ZDHSOUVjs.assert.call(void 0, value >= 0, "Value must be a non-negative number."); - _chunk6ZDHSOUVjs.assert.call(void 0, - Number.isSafeInteger(value), - "Value is not a safe integer. Use `bigIntToHex` instead." - ); - return _chunkQEPVHEP7js.add0x.call(void 0, value.toString(16)); -}; -var bigIntToHex = (value) => { - _chunk6ZDHSOUVjs.assert.call(void 0, typeof value === "bigint", "Value must be a bigint."); - _chunk6ZDHSOUVjs.assert.call(void 0, value >= 0, "Value must be a non-negative bigint."); - return _chunkQEPVHEP7js.add0x.call(void 0, value.toString(16)); -}; -var hexToNumber = (value) => { - _chunkQEPVHEP7js.assertIsHexString.call(void 0, value); - const numberValue = parseInt(value, 16); - _chunk6ZDHSOUVjs.assert.call(void 0, - Number.isSafeInteger(numberValue), - "Value is not a safe integer. Use `hexToBigInt` instead." - ); - return numberValue; -}; -var hexToBigInt = (value) => { - _chunkQEPVHEP7js.assertIsHexString.call(void 0, value); - return BigInt(_chunkQEPVHEP7js.add0x.call(void 0, value)); -}; - - - - - - -exports.numberToHex = numberToHex; exports.bigIntToHex = bigIntToHex; exports.hexToNumber = hexToNumber; exports.hexToBigInt = hexToBigInt; -//# sourceMappingURL=chunk-VFXTVNXN.js.map - -/***/ }), - -/***/ 2489: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({value: true})); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/caip-types.ts -var _superstruct = __webpack_require__(2150); -var CAIP_CHAIN_ID_REGEX = /^(?[-a-z0-9]{3,8}):(?[-_a-zA-Z0-9]{1,32})$/u; -var CAIP_NAMESPACE_REGEX = /^[-a-z0-9]{3,8}$/u; -var CAIP_REFERENCE_REGEX = /^[-_a-zA-Z0-9]{1,32}$/u; -var CAIP_ACCOUNT_ID_REGEX = /^(?(?[-a-z0-9]{3,8}):(?[-_a-zA-Z0-9]{1,32})):(?[-.%a-zA-Z0-9]{1,128})$/u; -var CAIP_ACCOUNT_ADDRESS_REGEX = /^[-.%a-zA-Z0-9]{1,128}$/u; -var CaipChainIdStruct = _superstruct.pattern.call(void 0, _superstruct.string.call(void 0, ), CAIP_CHAIN_ID_REGEX); -var CaipNamespaceStruct = _superstruct.pattern.call(void 0, _superstruct.string.call(void 0, ), CAIP_NAMESPACE_REGEX); -var CaipReferenceStruct = _superstruct.pattern.call(void 0, _superstruct.string.call(void 0, ), CAIP_REFERENCE_REGEX); -var CaipAccountIdStruct = _superstruct.pattern.call(void 0, _superstruct.string.call(void 0, ), CAIP_ACCOUNT_ID_REGEX); -var CaipAccountAddressStruct = _superstruct.pattern.call(void 0, - _superstruct.string.call(void 0, ), - CAIP_ACCOUNT_ADDRESS_REGEX -); -var KnownCaipNamespace = /* @__PURE__ */ ((KnownCaipNamespace2) => { - KnownCaipNamespace2["Eip155"] = "eip155"; - return KnownCaipNamespace2; -})(KnownCaipNamespace || {}); -function isCaipChainId(value) { - return _superstruct.is.call(void 0, value, CaipChainIdStruct); -} -function isCaipNamespace(value) { - return _superstruct.is.call(void 0, value, CaipNamespaceStruct); -} -function isCaipReference(value) { - return _superstruct.is.call(void 0, value, CaipReferenceStruct); -} -function isCaipAccountId(value) { - return _superstruct.is.call(void 0, value, CaipAccountIdStruct); -} -function isCaipAccountAddress(value) { - return _superstruct.is.call(void 0, value, CaipAccountAddressStruct); -} -function parseCaipChainId(caipChainId) { - const match = CAIP_CHAIN_ID_REGEX.exec(caipChainId); - if (!_optionalChain([match, 'optionalAccess', _ => _.groups])) { - throw new Error("Invalid CAIP chain ID."); - } - return { - namespace: match.groups.namespace, - reference: match.groups.reference - }; -} -function parseCaipAccountId(caipAccountId) { - const match = CAIP_ACCOUNT_ID_REGEX.exec(caipAccountId); - if (!_optionalChain([match, 'optionalAccess', _2 => _2.groups])) { - throw new Error("Invalid CAIP account ID."); - } - return { - address: match.groups.accountAddress, - chainId: match.groups.chainId, - chain: { - namespace: match.groups.namespace, - reference: match.groups.reference - } - }; -} -function toCaipChainId(namespace, reference) { - if (!isCaipNamespace(namespace)) { - throw new Error( - `Invalid "namespace", must match: ${CAIP_NAMESPACE_REGEX.toString()}` - ); - } - if (!isCaipReference(reference)) { - throw new Error( - `Invalid "reference", must match: ${CAIP_REFERENCE_REGEX.toString()}` - ); - } - return `${namespace}:${reference}`; -} - - - - - - - - - - - - - - - - - - - - - -exports.CAIP_CHAIN_ID_REGEX = CAIP_CHAIN_ID_REGEX; exports.CAIP_NAMESPACE_REGEX = CAIP_NAMESPACE_REGEX; exports.CAIP_REFERENCE_REGEX = CAIP_REFERENCE_REGEX; exports.CAIP_ACCOUNT_ID_REGEX = CAIP_ACCOUNT_ID_REGEX; exports.CAIP_ACCOUNT_ADDRESS_REGEX = CAIP_ACCOUNT_ADDRESS_REGEX; exports.CaipChainIdStruct = CaipChainIdStruct; exports.CaipNamespaceStruct = CaipNamespaceStruct; exports.CaipReferenceStruct = CaipReferenceStruct; exports.CaipAccountIdStruct = CaipAccountIdStruct; exports.CaipAccountAddressStruct = CaipAccountAddressStruct; exports.KnownCaipNamespace = KnownCaipNamespace; exports.isCaipChainId = isCaipChainId; exports.isCaipNamespace = isCaipNamespace; exports.isCaipReference = isCaipReference; exports.isCaipAccountId = isCaipAccountId; exports.isCaipAccountAddress = isCaipAccountAddress; exports.parseCaipChainId = parseCaipChainId; exports.parseCaipAccountId = parseCaipAccountId; exports.toCaipChainId = toCaipChainId; -//# sourceMappingURL=chunk-YWAID473.js.map - -/***/ }), - -/***/ 51584: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({value: true})); - - - -var _chunk3W5G4CYIjs = __webpack_require__(85244); - -// src/collections.ts -var _map; -var FrozenMap = class { - constructor(entries) { - _chunk3W5G4CYIjs.__privateAdd.call(void 0, this, _map, void 0); - _chunk3W5G4CYIjs.__privateSet.call(void 0, this, _map, new Map(entries)); - Object.freeze(this); - } - get size() { - return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _map).size; - } - [Symbol.iterator]() { - return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _map)[Symbol.iterator](); - } - entries() { - return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _map).entries(); - } - forEach(callbackfn, thisArg) { - return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _map).forEach( - (value, key, _map2) => callbackfn.call(thisArg, value, key, this) - ); - } - get(key) { - return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _map).get(key); - } - has(key) { - return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _map).has(key); - } - keys() { - return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _map).keys(); - } - values() { - return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _map).values(); - } - toString() { - return `FrozenMap(${this.size}) {${this.size > 0 ? ` ${[...this.entries()].map(([key, value]) => `${String(key)} => ${String(value)}`).join(", ")} ` : ""}}`; - } -}; -_map = new WeakMap(); -var _set; -var FrozenSet = class { - constructor(values) { - _chunk3W5G4CYIjs.__privateAdd.call(void 0, this, _set, void 0); - _chunk3W5G4CYIjs.__privateSet.call(void 0, this, _set, new Set(values)); - Object.freeze(this); - } - get size() { - return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _set).size; - } - [Symbol.iterator]() { - return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _set)[Symbol.iterator](); - } - entries() { - return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _set).entries(); - } - forEach(callbackfn, thisArg) { - return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _set).forEach( - (value, value2, _set2) => callbackfn.call(thisArg, value, value2, this) - ); - } - has(value) { - return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _set).has(value); - } - keys() { - return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _set).keys(); - } - values() { - return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _set).values(); - } - toString() { - return `FrozenSet(${this.size}) {${this.size > 0 ? ` ${[...this.values()].map((member) => String(member)).join(", ")} ` : ""}}`; - } -}; -_set = new WeakMap(); -Object.freeze(FrozenMap); -Object.freeze(FrozenMap.prototype); -Object.freeze(FrozenSet); -Object.freeze(FrozenSet.prototype); - - - - -exports.FrozenMap = FrozenMap; exports.FrozenSet = FrozenSet; -//# sourceMappingURL=chunk-Z2RGWDD7.js.map - -/***/ }), - -/***/ 22049: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({value: true}));__webpack_require__(87982); - - - - - -var _chunkVFXTVNXNjs = __webpack_require__(41535); -__webpack_require__(58383); - - -var _chunkC6HGFEYLjs = __webpack_require__(39705); - - - - -var _chunk4RMX5YWEjs = __webpack_require__(69116); -__webpack_require__(43207); - - - - - - - - - - -var _chunk4D6XQBHAjs = __webpack_require__(73631); - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -var _chunkOLLG4H35js = __webpack_require__(87427); -__webpack_require__(61305); - - - -var _chunk2LBGT4GHjs = __webpack_require__(61275); - - - - - - - - - - - - - - - - - - - - -var _chunkYWAID473js = __webpack_require__(2489); - - -var _chunkE4C7EW4Rjs = __webpack_require__(1508); - - -var _chunk6NZW4WK4js = __webpack_require__(21848); - - - - - -var _chunkDHVKFDHQjs = __webpack_require__(1203); - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -var _chunkQEPVHEP7js = __webpack_require__(75363); - - - - - -var _chunk6ZDHSOUVjs = __webpack_require__(40932); - - - - - - -var _chunkIZC266HSjs = __webpack_require__(1486); - - - - - - - - - - - - -var _chunkQVEKZRZ2js = __webpack_require__(96526); - - - -var _chunkZ2RGWDD7js = __webpack_require__(51584); -__webpack_require__(85244); -__webpack_require__(51423); - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -exports.AssertionError = _chunk6ZDHSOUVjs.AssertionError; exports.CAIP_ACCOUNT_ADDRESS_REGEX = _chunkYWAID473js.CAIP_ACCOUNT_ADDRESS_REGEX; exports.CAIP_ACCOUNT_ID_REGEX = _chunkYWAID473js.CAIP_ACCOUNT_ID_REGEX; exports.CAIP_CHAIN_ID_REGEX = _chunkYWAID473js.CAIP_CHAIN_ID_REGEX; exports.CAIP_NAMESPACE_REGEX = _chunkYWAID473js.CAIP_NAMESPACE_REGEX; exports.CAIP_REFERENCE_REGEX = _chunkYWAID473js.CAIP_REFERENCE_REGEX; exports.CaipAccountAddressStruct = _chunkYWAID473js.CaipAccountAddressStruct; exports.CaipAccountIdStruct = _chunkYWAID473js.CaipAccountIdStruct; exports.CaipChainIdStruct = _chunkYWAID473js.CaipChainIdStruct; exports.CaipNamespaceStruct = _chunkYWAID473js.CaipNamespaceStruct; exports.CaipReferenceStruct = _chunkYWAID473js.CaipReferenceStruct; exports.ChecksumStruct = _chunkE4C7EW4Rjs.ChecksumStruct; exports.Duration = _chunk4RMX5YWEjs.Duration; exports.ESCAPE_CHARACTERS_REGEXP = _chunkQVEKZRZ2js.ESCAPE_CHARACTERS_REGEXP; exports.FrozenMap = _chunkZ2RGWDD7js.FrozenMap; exports.FrozenSet = _chunkZ2RGWDD7js.FrozenSet; exports.HexAddressStruct = _chunkQEPVHEP7js.HexAddressStruct; exports.HexChecksumAddressStruct = _chunkQEPVHEP7js.HexChecksumAddressStruct; exports.HexStruct = _chunkQEPVHEP7js.HexStruct; exports.JsonRpcErrorStruct = _chunkOLLG4H35js.JsonRpcErrorStruct; exports.JsonRpcFailureStruct = _chunkOLLG4H35js.JsonRpcFailureStruct; exports.JsonRpcIdStruct = _chunkOLLG4H35js.JsonRpcIdStruct; exports.JsonRpcNotificationStruct = _chunkOLLG4H35js.JsonRpcNotificationStruct; exports.JsonRpcParamsStruct = _chunkOLLG4H35js.JsonRpcParamsStruct; exports.JsonRpcRequestStruct = _chunkOLLG4H35js.JsonRpcRequestStruct; exports.JsonRpcResponseStruct = _chunkOLLG4H35js.JsonRpcResponseStruct; exports.JsonRpcSuccessStruct = _chunkOLLG4H35js.JsonRpcSuccessStruct; exports.JsonRpcVersionStruct = _chunkOLLG4H35js.JsonRpcVersionStruct; exports.JsonSize = _chunkQVEKZRZ2js.JsonSize; exports.JsonStruct = _chunkOLLG4H35js.JsonStruct; exports.KnownCaipNamespace = _chunkYWAID473js.KnownCaipNamespace; exports.PendingJsonRpcResponseStruct = _chunkOLLG4H35js.PendingJsonRpcResponseStruct; exports.StrictHexStruct = _chunkQEPVHEP7js.StrictHexStruct; exports.UnsafeJsonStruct = _chunkOLLG4H35js.UnsafeJsonStruct; exports.VersionRangeStruct = _chunk4D6XQBHAjs.VersionRangeStruct; exports.VersionStruct = _chunk4D6XQBHAjs.VersionStruct; exports.add0x = _chunkQEPVHEP7js.add0x; exports.assert = _chunk6ZDHSOUVjs.assert; exports.assertExhaustive = _chunk6ZDHSOUVjs.assertExhaustive; exports.assertIsBytes = _chunkQEPVHEP7js.assertIsBytes; exports.assertIsHexString = _chunkQEPVHEP7js.assertIsHexString; exports.assertIsJsonRpcError = _chunkOLLG4H35js.assertIsJsonRpcError; exports.assertIsJsonRpcFailure = _chunkOLLG4H35js.assertIsJsonRpcFailure; exports.assertIsJsonRpcNotification = _chunkOLLG4H35js.assertIsJsonRpcNotification; exports.assertIsJsonRpcRequest = _chunkOLLG4H35js.assertIsJsonRpcRequest; exports.assertIsJsonRpcResponse = _chunkOLLG4H35js.assertIsJsonRpcResponse; exports.assertIsJsonRpcSuccess = _chunkOLLG4H35js.assertIsJsonRpcSuccess; exports.assertIsPendingJsonRpcResponse = _chunkOLLG4H35js.assertIsPendingJsonRpcResponse; exports.assertIsSemVerRange = _chunk4D6XQBHAjs.assertIsSemVerRange; exports.assertIsSemVerVersion = _chunk4D6XQBHAjs.assertIsSemVerVersion; exports.assertIsStrictHexString = _chunkQEPVHEP7js.assertIsStrictHexString; exports.assertStruct = _chunk6ZDHSOUVjs.assertStruct; exports.base64 = _chunk6NZW4WK4js.base64; exports.base64ToBytes = _chunkQEPVHEP7js.base64ToBytes; exports.bigIntToBytes = _chunkQEPVHEP7js.bigIntToBytes; exports.bigIntToHex = _chunkVFXTVNXNjs.bigIntToHex; exports.bytesToBase64 = _chunkQEPVHEP7js.bytesToBase64; exports.bytesToBigInt = _chunkQEPVHEP7js.bytesToBigInt; exports.bytesToHex = _chunkQEPVHEP7js.bytesToHex; exports.bytesToNumber = _chunkQEPVHEP7js.bytesToNumber; exports.bytesToSignedBigInt = _chunkQEPVHEP7js.bytesToSignedBigInt; exports.bytesToString = _chunkQEPVHEP7js.bytesToString; exports.calculateNumberSize = _chunkQVEKZRZ2js.calculateNumberSize; exports.calculateStringSize = _chunkQVEKZRZ2js.calculateStringSize; exports.concatBytes = _chunkQEPVHEP7js.concatBytes; exports.createBigInt = _chunkDHVKFDHQjs.createBigInt; exports.createBytes = _chunkDHVKFDHQjs.createBytes; exports.createDataView = _chunkQEPVHEP7js.createDataView; exports.createDeferredPromise = _chunkC6HGFEYLjs.createDeferredPromise; exports.createHex = _chunkDHVKFDHQjs.createHex; exports.createModuleLogger = _chunk2LBGT4GHjs.createModuleLogger; exports.createNumber = _chunkDHVKFDHQjs.createNumber; exports.createProjectLogger = _chunk2LBGT4GHjs.createProjectLogger; exports.exactOptional = _chunkOLLG4H35js.exactOptional; exports.getChecksumAddress = _chunkQEPVHEP7js.getChecksumAddress; exports.getErrorMessage = _chunkIZC266HSjs.getErrorMessage; exports.getJsonRpcIdValidator = _chunkOLLG4H35js.getJsonRpcIdValidator; exports.getJsonSize = _chunkOLLG4H35js.getJsonSize; exports.getKnownPropertyNames = _chunkQVEKZRZ2js.getKnownPropertyNames; exports.getSafeJson = _chunkOLLG4H35js.getSafeJson; exports.gtRange = _chunk4D6XQBHAjs.gtRange; exports.gtVersion = _chunk4D6XQBHAjs.gtVersion; exports.hasProperty = _chunkQVEKZRZ2js.hasProperty; exports.hexToBigInt = _chunkVFXTVNXNjs.hexToBigInt; exports.hexToBytes = _chunkQEPVHEP7js.hexToBytes; exports.hexToNumber = _chunkVFXTVNXNjs.hexToNumber; exports.inMilliseconds = _chunk4RMX5YWEjs.inMilliseconds; exports.isASCII = _chunkQVEKZRZ2js.isASCII; exports.isBytes = _chunkQEPVHEP7js.isBytes; exports.isCaipAccountAddress = _chunkYWAID473js.isCaipAccountAddress; exports.isCaipAccountId = _chunkYWAID473js.isCaipAccountId; exports.isCaipChainId = _chunkYWAID473js.isCaipChainId; exports.isCaipNamespace = _chunkYWAID473js.isCaipNamespace; exports.isCaipReference = _chunkYWAID473js.isCaipReference; exports.isErrorWithCode = _chunkIZC266HSjs.isErrorWithCode; exports.isErrorWithMessage = _chunkIZC266HSjs.isErrorWithMessage; exports.isErrorWithStack = _chunkIZC266HSjs.isErrorWithStack; exports.isHexString = _chunkQEPVHEP7js.isHexString; exports.isJsonRpcError = _chunkOLLG4H35js.isJsonRpcError; exports.isJsonRpcFailure = _chunkOLLG4H35js.isJsonRpcFailure; exports.isJsonRpcNotification = _chunkOLLG4H35js.isJsonRpcNotification; exports.isJsonRpcRequest = _chunkOLLG4H35js.isJsonRpcRequest; exports.isJsonRpcResponse = _chunkOLLG4H35js.isJsonRpcResponse; exports.isJsonRpcSuccess = _chunkOLLG4H35js.isJsonRpcSuccess; exports.isNonEmptyArray = _chunkQVEKZRZ2js.isNonEmptyArray; exports.isNullOrUndefined = _chunkQVEKZRZ2js.isNullOrUndefined; exports.isObject = _chunkQVEKZRZ2js.isObject; exports.isPendingJsonRpcResponse = _chunkOLLG4H35js.isPendingJsonRpcResponse; exports.isPlainObject = _chunkQVEKZRZ2js.isPlainObject; exports.isStrictHexString = _chunkQEPVHEP7js.isStrictHexString; exports.isValidChecksumAddress = _chunkQEPVHEP7js.isValidChecksumAddress; exports.isValidHexAddress = _chunkQEPVHEP7js.isValidHexAddress; exports.isValidJson = _chunkOLLG4H35js.isValidJson; exports.isValidSemVerRange = _chunk4D6XQBHAjs.isValidSemVerRange; exports.isValidSemVerVersion = _chunk4D6XQBHAjs.isValidSemVerVersion; exports.jsonrpc2 = _chunkOLLG4H35js.jsonrpc2; exports.numberToBytes = _chunkQEPVHEP7js.numberToBytes; exports.numberToHex = _chunkVFXTVNXNjs.numberToHex; exports.object = _chunkOLLG4H35js.object; exports.parseCaipAccountId = _chunkYWAID473js.parseCaipAccountId; exports.parseCaipChainId = _chunkYWAID473js.parseCaipChainId; exports.remove0x = _chunkQEPVHEP7js.remove0x; exports.satisfiesVersionRange = _chunk4D6XQBHAjs.satisfiesVersionRange; exports.signedBigIntToBytes = _chunkQEPVHEP7js.signedBigIntToBytes; exports.stringToBytes = _chunkQEPVHEP7js.stringToBytes; exports.timeSince = _chunk4RMX5YWEjs.timeSince; exports.toCaipChainId = _chunkYWAID473js.toCaipChainId; exports.valueToBytes = _chunkQEPVHEP7js.valueToBytes; exports.wrapError = _chunkIZC266HSjs.wrapError; -//# sourceMappingURL=index.js.map - -/***/ }), - /***/ 82102: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.output = exports.exists = exports.hash = exports.bytes = exports.bool = exports.number = exports.isBytes = void 0; +exports.isBytes = isBytes; +exports.number = number; +exports.bool = bool; +exports.bytes = bytes; +exports.hash = hash; +exports.exists = exists; +exports.output = output; function number(n) { if (!Number.isSafeInteger(n) || n < 0) throw new Error(`positive integer expected, not ${n}`); } -exports.number = number; function bool(b) { if (typeof b !== 'boolean') throw new Error(`boolean expected, not ${b}`); } -exports.bool = bool; // copied from utils function isBytes(a) { return (a instanceof Uint8Array || (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); } -exports.isBytes = isBytes; function bytes(b, ...lengths) { if (!isBytes(b)) throw new Error('Uint8Array expected'); if (lengths.length > 0 && !lengths.includes(b.length)) throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`); } -exports.bytes = bytes; function hash(h) { if (typeof h !== 'function' || typeof h.create !== 'function') throw new Error('Hash should be wrapped by utils.wrapConstructor'); number(h.outputLen); number(h.blockLen); } -exports.hash = hash; function exists(instance, checkFinished = true) { if (instance.destroyed) throw new Error('Hash instance has been destroyed'); if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called'); } -exports.exists = exists; function output(out, instance) { bytes(out); const min = instance.outputLen; @@ -6718,7 +4995,6 @@ function output(out, instance) { throw new Error(`digestInto() expects output buffer of length at least ${min}`); } } -exports.output = output; const assert = { number, bool, bytes, hash, exists, output }; exports["default"] = assert; //# sourceMappingURL=_assert.js.map @@ -6731,7 +5007,10 @@ exports["default"] = assert; "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.add5L = exports.add5H = exports.add4H = exports.add4L = exports.add3H = exports.add3L = exports.add = exports.rotlBL = exports.rotlBH = exports.rotlSL = exports.rotlSH = exports.rotr32L = exports.rotr32H = exports.rotrBL = exports.rotrBH = exports.rotrSL = exports.rotrSH = exports.shrSL = exports.shrSH = exports.toBig = exports.split = exports.fromBig = void 0; +exports.add5L = exports.add5H = exports.add4H = exports.add4L = exports.add3H = exports.add3L = exports.rotlBL = exports.rotlBH = exports.rotlSL = exports.rotlSH = exports.rotr32L = exports.rotr32H = exports.rotrBL = exports.rotrBH = exports.rotrSL = exports.rotrSH = exports.shrSL = exports.shrSH = exports.toBig = void 0; +exports.fromBig = fromBig; +exports.split = split; +exports.add = add; const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); const _32n = /* @__PURE__ */ BigInt(32); // We are not using BigUint64Array, because they are extremely slow as per 2022 @@ -6740,7 +5019,6 @@ function fromBig(n, le = false) { return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; } -exports.fromBig = fromBig; function split(lst, le = false) { let Ah = new Uint32Array(lst.length); let Al = new Uint32Array(lst.length); @@ -6750,7 +5028,6 @@ function split(lst, le = false) { } return [Ah, Al]; } -exports.split = split; const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); exports.toBig = toBig; // for Shift in [0, 32) @@ -6789,7 +5066,6 @@ function add(Ah, Al, Bh, Bl) { const l = (Al >>> 0) + (Bl >>> 0); return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; } -exports.add = add; // Addition with more than 2 elements const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); exports.add3L = add3L; @@ -6835,7 +5111,8 @@ exports.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? glob "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.shake256 = exports.shake128 = exports.keccak_512 = exports.keccak_384 = exports.keccak_256 = exports.keccak_224 = exports.sha3_512 = exports.sha3_384 = exports.sha3_256 = exports.sha3_224 = exports.Keccak = exports.keccakP = void 0; +exports.shake256 = exports.shake128 = exports.keccak_512 = exports.keccak_384 = exports.keccak_256 = exports.keccak_224 = exports.sha3_512 = exports.sha3_384 = exports.sha3_256 = exports.sha3_224 = exports.Keccak = void 0; +exports.keccakP = keccakP; const _assert_js_1 = __webpack_require__(82102); const _u64_js_1 = __webpack_require__(17335); const utils_js_1 = __webpack_require__(79520); @@ -6916,7 +5193,6 @@ function keccakP(s, rounds = 24) { } B.fill(0); } -exports.keccakP = keccakP; class Keccak extends utils_js_1.Hash { // NOTE: we accept arguments in bytes instead of bits here. constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { @@ -7062,7 +5338,20 @@ exports.shake256 = genShake(0x1f, 136, 256 / 8); /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.randomBytes = exports.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.checkOpts = exports.Hash = exports.concatBytes = exports.toBytes = exports.utf8ToBytes = exports.asyncLoop = exports.nextTick = exports.hexToBytes = exports.bytesToHex = exports.byteSwap32 = exports.byteSwapIfBE = exports.byteSwap = exports.isLE = exports.rotl = exports.rotr = exports.createView = exports.u32 = exports.u8 = exports.isBytes = void 0; +exports.Hash = exports.nextTick = exports.byteSwapIfBE = exports.byteSwap = exports.isLE = exports.rotl = exports.rotr = exports.createView = exports.u32 = exports.u8 = void 0; +exports.isBytes = isBytes; +exports.byteSwap32 = byteSwap32; +exports.bytesToHex = bytesToHex; +exports.hexToBytes = hexToBytes; +exports.asyncLoop = asyncLoop; +exports.utf8ToBytes = utf8ToBytes; +exports.toBytes = toBytes; +exports.concatBytes = concatBytes; +exports.checkOpts = checkOpts; +exports.wrapConstructor = wrapConstructor; +exports.wrapConstructorWithOpts = wrapConstructorWithOpts; +exports.wrapXOFConstructorWithOpts = wrapXOFConstructorWithOpts; +exports.randomBytes = randomBytes; // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. // node.js versions earlier than v19 don't declare it in global scope. // For node.js, package.json#exports field mapping rewrites import @@ -7077,7 +5366,6 @@ function isBytes(a) { return (a instanceof Uint8Array || (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); } -exports.isBytes = isBytes; // Cast array to different type const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); exports.u8 = u8; @@ -7107,7 +5395,6 @@ function byteSwap32(arr) { arr[i] = (0, exports.byteSwap)(arr[i]); } } -exports.byteSwap32 = byteSwap32; // Array where index 0xf0 (240) is mapped to string 'f0' const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); /** @@ -7122,7 +5409,6 @@ function bytesToHex(bytes) { } return hex; } -exports.bytesToHex = bytesToHex; // We use optimized technique to convert hex string to byte array const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 }; function asciiToBase16(char) { @@ -7156,7 +5442,6 @@ function hexToBytes(hex) { } return array; } -exports.hexToBytes = hexToBytes; // There is no setImmediate in browser and setTimeout is slow. // call of async fn will return Promise, which will be fullfiled only on // next scheduler queue processing step and this is exactly what we need. @@ -7175,7 +5460,6 @@ async function asyncLoop(iters, tick, cb) { ts += diff; } } -exports.asyncLoop = asyncLoop; /** * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) */ @@ -7184,7 +5468,6 @@ function utf8ToBytes(str) { throw new Error(`utf8ToBytes expected string, got ${typeof str}`); return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 } -exports.utf8ToBytes = utf8ToBytes; /** * Normalizes (non-hex) string or Uint8Array to Uint8Array. * Warning: when Uint8Array is passed, it would NOT get copied. @@ -7196,7 +5479,6 @@ function toBytes(data) { (0, _assert_js_1.bytes)(data); return data; } -exports.toBytes = toBytes; /** * Copies several Uint8Arrays into one. */ @@ -7215,7 +5497,6 @@ function concatBytes(...arrays) { } return res; } -exports.concatBytes = concatBytes; // For runtime check if class implements interface class Hash { // Safe version that clones internal state @@ -7231,7 +5512,6 @@ function checkOpts(defaults, opts) { const merged = Object.assign(defaults, opts); return merged; } -exports.checkOpts = checkOpts; function wrapConstructor(hashCons) { const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); const tmp = hashCons(); @@ -7240,7 +5520,6 @@ function wrapConstructor(hashCons) { hashC.create = () => hashCons(); return hashC; } -exports.wrapConstructor = wrapConstructor; function wrapConstructorWithOpts(hashCons) { const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); const tmp = hashCons({}); @@ -7249,7 +5528,6 @@ function wrapConstructorWithOpts(hashCons) { hashC.create = (opts) => hashCons(opts); return hashC; } -exports.wrapConstructorWithOpts = wrapConstructorWithOpts; function wrapXOFConstructorWithOpts(hashCons) { const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); const tmp = hashCons({}); @@ -7258,7 +5536,6 @@ function wrapXOFConstructorWithOpts(hashCons) { hashC.create = (opts) => hashCons(opts); return hashC; } -exports.wrapXOFConstructorWithOpts = wrapXOFConstructorWithOpts; /** * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. */ @@ -7266,9 +5543,12 @@ function randomBytes(bytesLength = 32) { if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') { return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength)); } + // Legacy Node.js compatibility + if (crypto_1.crypto && typeof crypto_1.crypto.randomBytes === 'function') { + return crypto_1.crypto.randomBytes(bytesLength); + } throw new Error('crypto.getRandomValues must be defined'); } -exports.randomBytes = randomBytes; //# sourceMappingURL=utils.js.map /***/ }), @@ -7279,7 +5559,8 @@ exports.randomBytes = randomBytes; "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createCurve = exports.getHash = void 0; +exports.getHash = getHash; +exports.createCurve = createCurve; /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ const hmac_1 = __webpack_require__(39615); const utils_1 = __webpack_require__(99175); @@ -7292,12 +5573,10 @@ function getHash(hash) { randomBytes: utils_1.randomBytes, }; } -exports.getHash = getHash; function createCurve(curveDef, defHash) { const create = (hash) => (0, weierstrass_js_1.weierstrass)({ ...curveDef, ...getHash(hash) }); return Object.freeze({ ...create(defHash), create }); } -exports.createCurve = createCurve; //# sourceMappingURL=_shortw_utils.js.map /***/ }), @@ -7308,7 +5587,8 @@ exports.createCurve = createCurve; "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.validateBasic = exports.wNAF = void 0; +exports.wNAF = wNAF; +exports.validateBasic = validateBasic; /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ // Abelian group utilities const modular_js_1 = __webpack_require__(24967); @@ -7446,7 +5726,6 @@ function wNAF(c, bits) { }, }; } -exports.wNAF = wNAF; function validateBasic(curve) { (0, modular_js_1.validateField)(curve.Fp); (0, utils_js_1.validateObject)(curve, { @@ -7465,7 +5744,6 @@ function validateBasic(curve) { ...{ p: curve.Fp.ORDER }, }); } -exports.validateBasic = validateBasic; //# sourceMappingURL=curve.js.map /***/ }), @@ -7476,16 +5754,13 @@ exports.validateBasic = validateBasic; "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createHasher = exports.isogenyMap = exports.hash_to_field = exports.expand_message_xof = exports.expand_message_xmd = void 0; +exports.expand_message_xmd = expand_message_xmd; +exports.expand_message_xof = expand_message_xof; +exports.hash_to_field = hash_to_field; +exports.isogenyMap = isogenyMap; +exports.createHasher = createHasher; const modular_js_1 = __webpack_require__(24967); const utils_js_1 = __webpack_require__(91484); -function validateDST(dst) { - if ((0, utils_js_1.isBytes)(dst)) - return dst; - if (typeof dst === 'string') - return (0, utils_js_1.utf8ToBytes)(dst); - throw new Error('DST must be Uint8Array or string'); -} // Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE. const os2ip = utils_js_1.bytesToNumberBE; // Integer to Octet Stream (numberToBytesBE) @@ -7507,20 +5782,16 @@ function strxor(a, b) { } return arr; } -function abytes(item) { - if (!(0, utils_js_1.isBytes)(item)) - throw new Error('Uint8Array expected'); -} -function isNum(item) { +function anum(item) { if (!Number.isSafeInteger(item)) throw new Error('number expected'); } // Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 function expand_message_xmd(msg, DST, lenInBytes, H) { - abytes(msg); - abytes(DST); - isNum(lenInBytes); + (0, utils_js_1.abytes)(msg); + (0, utils_js_1.abytes)(DST); + anum(lenInBytes); // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3 if (DST.length > 255) DST = H((0, utils_js_1.concatBytes)((0, utils_js_1.utf8ToBytes)('H2C-OVERSIZE-DST-'), DST)); @@ -7541,16 +5812,15 @@ function expand_message_xmd(msg, DST, lenInBytes, H) { const pseudo_random_bytes = (0, utils_js_1.concatBytes)(...b); return pseudo_random_bytes.slice(0, lenInBytes); } -exports.expand_message_xmd = expand_message_xmd; // Produces a uniformly random byte string using an extendable-output function (XOF) H. // 1. The collision resistance of H MUST be at least k bits. // 2. H MUST be an XOF that has been proved indifferentiable from // a random oracle under a reasonable cryptographic assumption. // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 function expand_message_xof(msg, DST, lenInBytes, k, H) { - abytes(msg); - abytes(DST); - isNum(lenInBytes); + (0, utils_js_1.abytes)(msg); + (0, utils_js_1.abytes)(DST); + anum(lenInBytes); // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3 // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8)); if (DST.length > 255) { @@ -7567,7 +5837,6 @@ function expand_message_xof(msg, DST, lenInBytes, k, H) { .update(i2osp(DST.length, 1)) .digest()); } -exports.expand_message_xof = expand_message_xof; /** * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F * https://www.rfc-editor.org/rfc/rfc9380#section-5.2 @@ -7585,9 +5854,9 @@ function hash_to_field(msg, count, options) { hash: 'hash', }); const { p, k, m, hash, expand, DST: _DST } = options; - abytes(msg); - isNum(count); - const DST = validateDST(_DST); + (0, utils_js_1.abytes)(msg); + anum(count); + const DST = typeof _DST === 'string' ? (0, utils_js_1.utf8ToBytes)(_DST) : _DST; const log2p = p.toString(2).length; const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above const len_in_bytes = count * m * L; @@ -7617,7 +5886,6 @@ function hash_to_field(msg, count, options) { } return u; } -exports.hash_to_field = hash_to_field; function isogenyMap(field, map) { // Make same order as in spec const COEFF = map.map((i) => Array.from(i).reverse()); @@ -7628,7 +5896,6 @@ function isogenyMap(field, map) { return { x, y }; }; } -exports.isogenyMap = isogenyMap; function createHasher(Point, mapToCurve, def) { if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined'); @@ -7651,9 +5918,19 @@ function createHasher(Point, mapToCurve, def) { P.assertValidity(); return P; }, + // Same as encodeToCurve, but without hash + mapToCurve(scalars) { + if (!Array.isArray(scalars)) + throw new Error('mapToCurve: expected array of bigints'); + for (const i of scalars) + if (typeof i !== 'bigint') + throw new Error(`mapToCurve: expected array of bigints, got ${i} in array`); + const P = Point.fromAffine(mapToCurve(scalars)).clearCofactor(); + P.assertValidity(); + return P; + }, }; } -exports.createHasher = createHasher; //# sourceMappingURL=hash-to-curve.js.map /***/ }), @@ -7664,7 +5941,26 @@ exports.createHasher = createHasher; "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.mapHashToField = exports.getMinHashLength = exports.getFieldBytesLength = exports.hashToPrivateScalar = exports.FpSqrtEven = exports.FpSqrtOdd = exports.Field = exports.nLength = exports.FpIsSquare = exports.FpDiv = exports.FpInvertBatch = exports.FpPow = exports.validateField = exports.isNegativeLE = exports.FpSqrt = exports.tonelliShanks = exports.invert = exports.pow2 = exports.pow = exports.mod = void 0; +exports.isNegativeLE = void 0; +exports.mod = mod; +exports.pow = pow; +exports.pow2 = pow2; +exports.invert = invert; +exports.tonelliShanks = tonelliShanks; +exports.FpSqrt = FpSqrt; +exports.validateField = validateField; +exports.FpPow = FpPow; +exports.FpInvertBatch = FpInvertBatch; +exports.FpDiv = FpDiv; +exports.FpIsSquare = FpIsSquare; +exports.nLength = nLength; +exports.Field = Field; +exports.FpSqrtOdd = FpSqrtOdd; +exports.FpSqrtEven = FpSqrtEven; +exports.hashToPrivateScalar = hashToPrivateScalar; +exports.getFieldBytesLength = getFieldBytesLength; +exports.getMinHashLength = getMinHashLength; +exports.mapHashToField = mapHashToField; /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ // Utilities for modular arithmetics and finite fields const utils_js_1 = __webpack_require__(91484); @@ -7679,7 +5975,6 @@ function mod(a, b) { const result = a % b; return result >= _0n ? result : b + result; } -exports.mod = mod; /** * Efficiently raise num to power and do modular division. * Unsafe in some contexts: uses ladder, so can expose bigint bits. @@ -7701,7 +5996,6 @@ function pow(num, power, modulo) { } return res; } -exports.pow = pow; // Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4) function pow2(x, power, modulo) { let res = x; @@ -7711,7 +6005,6 @@ function pow2(x, power, modulo) { } return res; } -exports.pow2 = pow2; // Inverses number over modulo function invert(number, modulo) { if (number === _0n || modulo <= _0n) { @@ -7737,7 +6030,6 @@ function invert(number, modulo) { throw new Error('invert: does not exist'); return mod(x, modulo); } -exports.invert = invert; /** * Tonelli-Shanks square root search algorithm. * 1. https://eprint.iacr.org/2012/685.pdf (page 12) @@ -7802,7 +6094,6 @@ function tonelliShanks(P) { return x; }; } -exports.tonelliShanks = tonelliShanks; function FpSqrt(P) { // NOTE: different algorithms can give different roots, it is up to user to decide which one they want. // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve). @@ -7861,7 +6152,6 @@ function FpSqrt(P) { // Other cases: Tonelli-Shanks algorithm return tonelliShanks(P); } -exports.FpSqrt = FpSqrt; // Little-endian check for first LE bit (last BE bit); const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n; exports.isNegativeLE = isNegativeLE; @@ -7884,7 +6174,6 @@ function validateField(field) { }, initial); return (0, utils_js_1.validateObject)(field, opts); } -exports.validateField = validateField; // Generic field functions /** * Same as `pow` but for Fp: non-constant-time. @@ -7909,7 +6198,6 @@ function FpPow(f, num, power) { } return p; } -exports.FpPow = FpPow; /** * Efficiently invert an array of Field elements. * `inv(0)` will return `undefined` here: make sure to throw an error. @@ -7934,11 +6222,9 @@ function FpInvertBatch(f, nums) { }, inverted); return tmp; } -exports.FpInvertBatch = FpInvertBatch; function FpDiv(f, lhs, rhs) { return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs)); } -exports.FpDiv = FpDiv; // This function returns True whenever the value x is a square in the field F. function FpIsSquare(f) { const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic @@ -7947,7 +6233,6 @@ function FpIsSquare(f) { return f.eql(p, f.ZERO) || f.eql(p, f.ONE); }; } -exports.FpIsSquare = FpIsSquare; // CURVE.n lengths function nLength(n, nBitLength) { // Bit size, byte size of CURVE.n @@ -7955,7 +6240,6 @@ function nLength(n, nBitLength) { const nByteLength = Math.ceil(_nBitLength / 8); return { nBitLength: _nBitLength, nByteLength }; } -exports.nLength = nLength; /** * Initializes a finite field over prime. **Non-primes are not supported.** * Do not init in loop: slow. Very fragile: always run a benchmark on a change. @@ -8018,21 +6302,18 @@ function Field(ORDER, bitLen, isLE = false, redef = {}) { }); return Object.freeze(f); } -exports.Field = Field; function FpSqrtOdd(Fp, elm) { if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`); const root = Fp.sqrt(elm); return Fp.isOdd(root) ? root : Fp.neg(root); } -exports.FpSqrtOdd = FpSqrtOdd; function FpSqrtEven(Fp, elm) { if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`); const root = Fp.sqrt(elm); return Fp.isOdd(root) ? Fp.neg(root) : root; } -exports.FpSqrtEven = FpSqrtEven; /** * "Constant-time" private key generation utility. * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field). @@ -8048,7 +6329,6 @@ function hashToPrivateScalar(hash, groupOrder, isLE = false) { const num = isLE ? (0, utils_js_1.bytesToNumberLE)(hash) : (0, utils_js_1.bytesToNumberBE)(hash); return mod(num, groupOrder - _1n) + _1n; } -exports.hashToPrivateScalar = hashToPrivateScalar; /** * Returns total number of bytes consumed by the field element. * For example, 32 bytes for usual 256-bit weierstrass curve. @@ -8061,7 +6341,6 @@ function getFieldBytesLength(fieldOrder) { const bitLength = fieldOrder.toString(2).length; return Math.ceil(bitLength / 8); } -exports.getFieldBytesLength = getFieldBytesLength; /** * Returns minimal amount of bytes that can be safely reduced * by field order. @@ -8073,7 +6352,6 @@ function getMinHashLength(fieldOrder) { const length = getFieldBytesLength(fieldOrder); return length + Math.ceil(length / 2); } -exports.getMinHashLength = getMinHashLength; /** * "Constant-time" private key generation utility. * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF @@ -8099,7 +6377,6 @@ function mapHashToField(key, fieldOrder, isLE = false) { const reduced = mod(num, fieldOrder - _1n) + _1n; return isLE ? (0, utils_js_1.numberToBytesLE)(reduced, fieldLen) : (0, utils_js_1.numberToBytesBE)(reduced, fieldLen); } -exports.mapHashToField = mapHashToField; //# sourceMappingURL=modular.js.map /***/ }), @@ -8110,28 +6387,50 @@ exports.mapHashToField = mapHashToField; "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.validateObject = exports.createHmacDrbg = exports.bitMask = exports.bitSet = exports.bitGet = exports.bitLen = exports.utf8ToBytes = exports.equalBytes = exports.concatBytes = exports.ensureBytes = exports.numberToVarBytesBE = exports.numberToBytesLE = exports.numberToBytesBE = exports.bytesToNumberLE = exports.bytesToNumberBE = exports.hexToBytes = exports.hexToNumber = exports.numberToHexUnpadded = exports.bytesToHex = exports.isBytes = void 0; +exports.bitMask = void 0; +exports.isBytes = isBytes; +exports.abytes = abytes; +exports.bytesToHex = bytesToHex; +exports.numberToHexUnpadded = numberToHexUnpadded; +exports.hexToNumber = hexToNumber; +exports.hexToBytes = hexToBytes; +exports.bytesToNumberBE = bytesToNumberBE; +exports.bytesToNumberLE = bytesToNumberLE; +exports.numberToBytesBE = numberToBytesBE; +exports.numberToBytesLE = numberToBytesLE; +exports.numberToVarBytesBE = numberToVarBytesBE; +exports.ensureBytes = ensureBytes; +exports.concatBytes = concatBytes; +exports.equalBytes = equalBytes; +exports.utf8ToBytes = utf8ToBytes; +exports.bitLen = bitLen; +exports.bitGet = bitGet; +exports.bitSet = bitSet; +exports.createHmacDrbg = createHmacDrbg; +exports.validateObject = validateObject; /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ // 100 lines of code in the file are duplicated from noble-hashes (utils). // This is OK: `abstract` directory does not use noble-hashes. // User may opt-in into using different hashing library. This way, noble-hashes // won't be included into their bundle. -const _0n = BigInt(0); -const _1n = BigInt(1); -const _2n = BigInt(2); +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); +const _2n = /* @__PURE__ */ BigInt(2); function isBytes(a) { return (a instanceof Uint8Array || (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); } -exports.isBytes = isBytes; +function abytes(item) { + if (!isBytes(item)) + throw new Error('Uint8Array expected'); +} // Array where index 0xf0 (240) is mapped to string 'f0' const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); /** * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' */ function bytesToHex(bytes) { - if (!isBytes(bytes)) - throw new Error('Uint8Array expected'); + abytes(bytes); // pre-caching improves the speed 6x let hex = ''; for (let i = 0; i < bytes.length; i++) { @@ -8139,19 +6438,16 @@ function bytesToHex(bytes) { } return hex; } -exports.bytesToHex = bytesToHex; function numberToHexUnpadded(num) { const hex = num.toString(16); return hex.length & 1 ? `0${hex}` : hex; } -exports.numberToHexUnpadded = numberToHexUnpadded; function hexToNumber(hex) { if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex); // Big Endian return BigInt(hex === '' ? '0' : `0x${hex}`); } -exports.hexToNumber = hexToNumber; // We use optimized technique to convert hex string to byte array const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 }; function asciiToBase16(char) { @@ -8185,31 +6481,24 @@ function hexToBytes(hex) { } return array; } -exports.hexToBytes = hexToBytes; // BE: Big Endian, LE: Little Endian function bytesToNumberBE(bytes) { return hexToNumber(bytesToHex(bytes)); } -exports.bytesToNumberBE = bytesToNumberBE; function bytesToNumberLE(bytes) { - if (!isBytes(bytes)) - throw new Error('Uint8Array expected'); + abytes(bytes); return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); } -exports.bytesToNumberLE = bytesToNumberLE; function numberToBytesBE(n, len) { return hexToBytes(n.toString(16).padStart(len * 2, '0')); } -exports.numberToBytesBE = numberToBytesBE; function numberToBytesLE(n, len) { return numberToBytesBE(n, len).reverse(); } -exports.numberToBytesLE = numberToBytesLE; // Unpadded, rarely used function numberToVarBytesBE(n) { return hexToBytes(numberToHexUnpadded(n)); } -exports.numberToVarBytesBE = numberToVarBytesBE; /** * Takes hex string or Uint8Array, converts to Uint8Array. * Validates output length. @@ -8242,7 +6531,6 @@ function ensureBytes(title, hex, expectedLength) { throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); return res; } -exports.ensureBytes = ensureBytes; /** * Copies several Uint8Arrays into one. */ @@ -8250,20 +6538,17 @@ function concatBytes(...arrays) { let sum = 0; for (let i = 0; i < arrays.length; i++) { const a = arrays[i]; - if (!isBytes(a)) - throw new Error('Uint8Array expected'); + abytes(a); sum += a.length; } - let res = new Uint8Array(sum); - let pad = 0; - for (let i = 0; i < arrays.length; i++) { + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { const a = arrays[i]; res.set(a, pad); pad += a.length; } return res; } -exports.concatBytes = concatBytes; // Compares 2 u8a-s in kinda constant time function equalBytes(a, b) { if (a.length !== b.length) @@ -8273,7 +6558,6 @@ function equalBytes(a, b) { diff |= a[i] ^ b[i]; return diff === 0; } -exports.equalBytes = equalBytes; /** * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) */ @@ -8282,7 +6566,6 @@ function utf8ToBytes(str) { throw new Error(`utf8ToBytes expected string, got ${typeof str}`); return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 } -exports.utf8ToBytes = utf8ToBytes; // Bit operations /** * Calculates amount of bits in a bigint. @@ -8294,7 +6577,6 @@ function bitLen(n) { ; return len; } -exports.bitLen = bitLen; /** * Gets single bit at position. * NOTE: first bit position is 0 (same as arrays) @@ -8303,14 +6585,12 @@ exports.bitLen = bitLen; function bitGet(n, pos) { return (n >> BigInt(pos)) & _1n; } -exports.bitGet = bitGet; /** * Sets single bit at position. */ -const bitSet = (n, pos, value) => { +function bitSet(n, pos, value) { return n | ((value ? _1n : _0n) << BigInt(pos)); -}; -exports.bitSet = bitSet; +} /** * Calculate mask for N bits. Not using ** operator with bigints because of old engines. * Same as BigInt(`0b${Array(i).fill('1').join('')}`) @@ -8378,7 +6658,6 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) { }; return genUntil; } -exports.createHmacDrbg = createHmacDrbg; // Validating curves and fields const validatorFns = { bigint: (val) => typeof val === 'bigint', @@ -8410,7 +6689,6 @@ function validateObject(object, validators, optValidators = {}) { checkField(fieldName, type, true); return object; } -exports.validateObject = validateObject; // validate type tests // const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 }; // const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok! @@ -8429,13 +6707,17 @@ exports.validateObject = validateObject; "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.mapToCurveSimpleSWU = exports.SWUFpSqrtRatio = exports.weierstrass = exports.weierstrassPoints = exports.DER = void 0; +exports.DER = void 0; +exports.weierstrassPoints = weierstrassPoints; +exports.weierstrass = weierstrass; +exports.SWUFpSqrtRatio = SWUFpSqrtRatio; +exports.mapToCurveSimpleSWU = mapToCurveSimpleSWU; /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ // Short Weierstrass curve. The formula is: y² = x³ + ax + b +const curve_js_1 = __webpack_require__(62422); const mod = __webpack_require__(24967); const ut = __webpack_require__(91484); const utils_js_1 = __webpack_require__(91484); -const curve_js_1 = __webpack_require__(62422); function validatePointOpts(curve) { const opts = (0, curve_js_1.validateBasic)(curve); ut.validateObject(opts, { @@ -8494,8 +6776,7 @@ exports.DER = { // parse DER signature const { Err: E } = exports.DER; const data = typeof hex === 'string' ? h2b(hex) : hex; - if (!ut.isBytes(data)) - throw new Error('ui8a expected'); + ut.abytes(data); let l = data.length; if (l < 2 || data[0] != 0x30) throw new E('Invalid signature tag'); @@ -8953,7 +7234,6 @@ function weierstrassPoints(opts) { isWithinCurveOrder, }; } -exports.weierstrassPoints = weierstrassPoints; function validateOpts(curve) { const opts = (0, curve_js_1.validateBasic)(curve); ut.validateObject(opts, { @@ -9004,7 +7284,14 @@ function weierstrass(curveDef) { if (!isValidFieldElement(x)) throw new Error('Point is not on curve'); const y2 = weierstrassEquation(x); // y² = x³ + ax + b - let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + let y; + try { + y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + } + catch (sqrtError) { + const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : ''; + throw new Error('Point is not on curve' + suffix); + } const isYOdd = (y & _1n) === _1n; // ECDSA const isHeadOdd = (head & 1) === 1; @@ -9231,7 +7518,7 @@ function weierstrass(curveDef) { const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint const seedArgs = [int2octets(d), int2octets(h1int)]; // extraEntropy. RFC6979 3.6: additional k' (optional). - if (ent != null) { + if (ent != null && ent !== false) { // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is seedArgs.push((0, utils_js_1.ensureBytes)('extraEntropy', e)); // check for being bytes @@ -9364,7 +7651,6 @@ function weierstrass(curveDef) { utils, }; } -exports.weierstrass = weierstrass; /** * Implementation of the Shallue and van de Woestijne method for any weierstrass curve. * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular. @@ -9443,7 +7729,6 @@ function SWUFpSqrtRatio(Fp, Z) { // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8 return sqrtRatio; } -exports.SWUFpSqrtRatio = SWUFpSqrtRatio; /** * Simplified Shallue-van de Woestijne-Ulas Method * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2 @@ -9488,7 +7773,6 @@ function mapToCurveSimpleSWU(Fp, opts) { return { x, y }; }; } -exports.mapToCurveSimpleSWU = mapToCurveSimpleSWU; //# sourceMappingURL=weierstrass.js.map /***/ }), @@ -9503,11 +7787,11 @@ exports.encodeToCurve = exports.hashToCurve = exports.schnorr = exports.secp256k /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ const sha256_1 = __webpack_require__(22623); const utils_1 = __webpack_require__(99175); -const modular_js_1 = __webpack_require__(24967); -const weierstrass_js_1 = __webpack_require__(91705); -const utils_js_1 = __webpack_require__(91484); -const hash_to_curve_js_1 = __webpack_require__(71761); const _shortw_utils_js_1 = __webpack_require__(73562); +const hash_to_curve_js_1 = __webpack_require__(71761); +const modular_js_1 = __webpack_require__(24967); +const utils_js_1 = __webpack_require__(91484); +const weierstrass_js_1 = __webpack_require__(91705); const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'); const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); const _1n = BigInt(1); @@ -9763,15 +8047,15 @@ exports.encodeToCurve = (() => htf.encodeToCurve)(); "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.output = exports.exists = exports.hash = exports.bytes = exports.bool = exports.number = void 0; +exports.output = exports.exists = exports.hash = exports.bytes = exports.bool = exports.number = exports.isBytes = void 0; function number(n) { if (!Number.isSafeInteger(n) || n < 0) - throw new Error(`Wrong positive integer: ${n}`); + throw new Error(`positive integer expected, not ${n}`); } exports.number = number; function bool(b) { if (typeof b !== 'boolean') - throw new Error(`Expected boolean, not ${b}`); + throw new Error(`boolean expected, not ${b}`); } exports.bool = bool; // copied from utils @@ -9779,18 +8063,19 @@ function isBytes(a) { return (a instanceof Uint8Array || (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); } +exports.isBytes = isBytes; function bytes(b, ...lengths) { if (!isBytes(b)) - throw new Error('Expected Uint8Array'); + throw new Error('Uint8Array expected'); if (lengths.length > 0 && !lengths.includes(b.length)) - throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); + throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`); } exports.bytes = bytes; -function hash(hash) { - if (typeof hash !== 'function' || typeof hash.create !== 'function') +function hash(h) { + if (typeof h !== 'function' || typeof h.create !== 'function') throw new Error('Hash should be wrapped by utils.wrapConstructor'); - number(hash.outputLen); - number(hash.blockLen); + number(h.outputLen); + number(h.blockLen); } exports.hash = hash; function exists(instance, checkFinished = true) { @@ -9814,13 +8099,13 @@ exports["default"] = assert; /***/ }), -/***/ 90915: +/***/ 37202: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SHA2 = void 0; +exports.HashMD = exports.Maj = exports.Chi = void 0; const _assert_js_1 = __webpack_require__(67557); const utils_js_1 = __webpack_require__(99175); // Polyfill for Safari 14 @@ -9836,8 +8121,17 @@ function setBigUint64(view, byteOffset, value, isLE) { view.setUint32(byteOffset + h, wh, isLE); view.setUint32(byteOffset + l, wl, isLE); } -// Base SHA2 class (RFC 6234) -class SHA2 extends utils_js_1.Hash { +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +exports.Chi = Chi; +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +exports.Maj = Maj; +/** + * Merkle-Damgard hash construction base class. + * Could be used to create MD5, RIPEMD, SHA1, SHA2. + */ +class HashMD extends utils_js_1.Hash { constructor(blockLen, outputLen, padOffset, isLE) { super(); this.blockLen = blockLen; @@ -9889,7 +8183,8 @@ class SHA2 extends utils_js_1.Hash { // append the bit '1' to the message buffer[pos++] = 0b10000000; this.buffer.subarray(pos).fill(0); - // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again + // we have less than padOffset left in buffer, so we cannot put length in + // current block, need process it and pad again if (this.padOffset > blockLen - pos) { this.process(view, 0); pos = 0; @@ -9934,8 +8229,8 @@ class SHA2 extends utils_js_1.Hash { return to; } } -exports.SHA2 = SHA2; -//# sourceMappingURL=_sha2.js.map +exports.HashMD = HashMD; +//# sourceMappingURL=_md.js.map /***/ }), @@ -10139,14 +8434,10 @@ exports.hmac.create = (hash, key) => new HMAC(hash, key); Object.defineProperty(exports, "__esModule", ({ value: true })); exports.sha224 = exports.sha256 = void 0; -const _sha2_js_1 = __webpack_require__(90915); +const _md_js_1 = __webpack_require__(37202); const utils_js_1 = __webpack_require__(99175); // SHA2-256 need to try 2^128 hashes to execute birthday attack. // BTC network is doing 2^67 hashes/sec as per early 2023. -// Choice: a ? b : c -const Chi = (a, b, c) => (a & b) ^ (~a & c); -// Majority function, true if any two inpust is true -const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); // Round constants: // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) // prettier-ignore @@ -10160,27 +8451,28 @@ const SHA256_K = /* @__PURE__ */ new Uint32Array([ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ]); -// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19 // prettier-ignore -const IV = /* @__PURE__ */ new Uint32Array([ +const SHA256_IV = /* @__PURE__ */ new Uint32Array([ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ]); // Temporary buffer, not used to store anything between runs // Named this way because it matches specification. const SHA256_W = /* @__PURE__ */ new Uint32Array(64); -class SHA256 extends _sha2_js_1.SHA2 { +class SHA256 extends _md_js_1.HashMD { constructor() { super(64, 32, 8, false); // We cannot use array here since array allows indexing by variable // which means optimizer/compiler cannot use registers. - this.A = IV[0] | 0; - this.B = IV[1] | 0; - this.C = IV[2] | 0; - this.D = IV[3] | 0; - this.E = IV[4] | 0; - this.F = IV[5] | 0; - this.G = IV[6] | 0; - this.H = IV[7] | 0; + this.A = SHA256_IV[0] | 0; + this.B = SHA256_IV[1] | 0; + this.C = SHA256_IV[2] | 0; + this.D = SHA256_IV[3] | 0; + this.E = SHA256_IV[4] | 0; + this.F = SHA256_IV[5] | 0; + this.G = SHA256_IV[6] | 0; + this.H = SHA256_IV[7] | 0; } get() { const { A, B, C, D, E, F, G, H } = this; @@ -10212,9 +8504,9 @@ class SHA256 extends _sha2_js_1.SHA2 { let { A, B, C, D, E, F, G, H } = this; for (let i = 0; i < 64; i++) { const sigma1 = (0, utils_js_1.rotr)(E, 6) ^ (0, utils_js_1.rotr)(E, 11) ^ (0, utils_js_1.rotr)(E, 25); - const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const T1 = (H + sigma1 + (0, _md_js_1.Chi)(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; const sigma0 = (0, utils_js_1.rotr)(A, 2) ^ (0, utils_js_1.rotr)(A, 13) ^ (0, utils_js_1.rotr)(A, 22); - const T2 = (sigma0 + Maj(A, B, C)) | 0; + const T2 = (sigma0 + (0, _md_js_1.Maj)(A, B, C)) | 0; H = G; G = F; F = E; @@ -10281,7 +8573,9 @@ const utils_js_1 = __webpack_require__(99175); // SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. // It's called a sponge function. // Various per round constants calculations -const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []]; +const SHA3_PI = []; +const SHA3_ROTL = []; +const _SHA3_IOTA = []; const _0n = /* @__PURE__ */ BigInt(0); const _1n = /* @__PURE__ */ BigInt(1); const _2n = /* @__PURE__ */ BigInt(2); @@ -10376,7 +8670,11 @@ class Keccak extends utils_js_1.Hash { this.state32 = (0, utils_js_1.u32)(this.state); } keccak() { + if (!utils_js_1.isLE) + (0, utils_js_1.byteSwap32)(this.state32); keccakP(this.state32, this.rounds); + if (!utils_js_1.isLE) + (0, utils_js_1.byteSwap32)(this.state32); this.posOut = 0; this.pos = 0; } @@ -10495,7 +8793,7 @@ exports.shake256 = genShake(0x1f, 136, 256 / 8); /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.randomBytes = exports.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.checkOpts = exports.Hash = exports.concatBytes = exports.toBytes = exports.utf8ToBytes = exports.asyncLoop = exports.nextTick = exports.hexToBytes = exports.bytesToHex = exports.isLE = exports.rotr = exports.createView = exports.u32 = exports.u8 = void 0; +exports.randomBytes = exports.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.checkOpts = exports.Hash = exports.concatBytes = exports.toBytes = exports.utf8ToBytes = exports.asyncLoop = exports.nextTick = exports.hexToBytes = exports.bytesToHex = exports.byteSwap32 = exports.byteSwapIfBE = exports.byteSwap = exports.isLE = exports.rotl = exports.rotr = exports.createView = exports.u32 = exports.u8 = exports.isBytes = void 0; // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. // node.js versions earlier than v19 don't declare it in global scope. // For node.js, package.json#exports field mapping rewrites import @@ -10503,36 +8801,51 @@ exports.randomBytes = exports.wrapXOFConstructorWithOpts = exports.wrapConstruct // Makes the utils un-importable in browsers without a bundler. // Once node.js 18 is deprecated (2025-04-30), we can just drop the import. const crypto_1 = __webpack_require__(25145); +const _assert_js_1 = __webpack_require__(67557); +// export { isBytes } from './_assert.js'; +// We can't reuse isBytes from _assert, because somehow this causes huge perf issues +function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +exports.isBytes = isBytes; // Cast array to different type const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); exports.u8 = u8; const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); exports.u32 = u32; -function isBytes(a) { - return (a instanceof Uint8Array || - (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); -} // Cast array to view const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); exports.createView = createView; // The rotate right (circular right shift) operation for uint32 const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); exports.rotr = rotr; -// big-endian hardware is rare. Just in case someone still decides to run hashes: -// early-throw an error because we don't support BE yet. -// Other libraries would silently corrupt the data instead of throwing an error, -// when they don't support it. +// The rotate left (circular left shift) operation for uint32 +const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +exports.rotl = rotl; exports.isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; -if (!exports.isLE) - throw new Error('Non little-endian hardware is not supported'); +// The byte swap operation for uint32 +const byteSwap = (word) => ((word << 24) & 0xff000000) | + ((word << 8) & 0xff0000) | + ((word >>> 8) & 0xff00) | + ((word >>> 24) & 0xff); +exports.byteSwap = byteSwap; +// Conditionally byte swap if on a big-endian platform +exports.byteSwapIfBE = exports.isLE ? (n) => n : (n) => (0, exports.byteSwap)(n); +// In place byte swap for Uint32Array +function byteSwap32(arr) { + for (let i = 0; i < arr.length; i++) { + arr[i] = (0, exports.byteSwap)(arr[i]); + } +} +exports.byteSwap32 = byteSwap32; // Array where index 0xf0 (240) is mapped to string 'f0' const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); /** * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' */ function bytesToHex(bytes) { - if (!isBytes(bytes)) - throw new Error('Uint8Array expected'); + (0, _assert_js_1.bytes)(bytes); // pre-caching improves the speed 6x let hex = ''; for (let i = 0; i < bytes.length; i++) { @@ -10611,8 +8924,7 @@ exports.utf8ToBytes = utf8ToBytes; function toBytes(data) { if (typeof data === 'string') data = utf8ToBytes(data); - if (!isBytes(data)) - throw new Error(`expected Uint8Array, got ${typeof data}`); + (0, _assert_js_1.bytes)(data); return data; } exports.toBytes = toBytes; @@ -10623,8 +8935,7 @@ function concatBytes(...arrays) { let sum = 0; for (let i = 0; i < arrays.length; i++) { const a = arrays[i]; - if (!isBytes(a)) - throw new Error('Uint8Array expected'); + (0, _assert_js_1.bytes)(a); sum += a.length; } const res = new Uint8Array(sum); @@ -10700,7 +9011,8 @@ exports.randomBytes = randomBytes; /*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.bytes = exports.stringToBytes = exports.str = exports.bytesToString = exports.hex = exports.utf8 = exports.bech32m = exports.bech32 = exports.base58check = exports.createBase58check = exports.base58xmr = exports.base58xrp = exports.base58flickr = exports.base58 = exports.base64urlnopad = exports.base64url = exports.base64nopad = exports.base64 = exports.base32crockford = exports.base32hex = exports.base32 = exports.base16 = exports.utils = exports.assertNumber = void 0; +exports.bytes = exports.stringToBytes = exports.str = exports.bytesToString = exports.hex = exports.utf8 = exports.bech32m = exports.bech32 = exports.base58check = exports.createBase58check = exports.base58xmr = exports.base58xrp = exports.base58flickr = exports.base58 = exports.base64urlnopad = exports.base64url = exports.base64nopad = exports.base64 = exports.base32crockford = exports.base32hexnopad = exports.base32hex = exports.base32nopad = exports.base32 = exports.base16 = exports.utils = void 0; +exports.assertNumber = assertNumber; // Utilities /** * @__NO_SIDE_EFFECTS__ @@ -10709,7 +9021,6 @@ function assertNumber(n) { if (!Number.isSafeInteger(n)) throw new Error(`Wrong integer: ${n}`); } -exports.assertNumber = assertNumber; function isBytes(a) { return (a instanceof Uint8Array || (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); @@ -11010,7 +9321,9 @@ exports.utils = { // --------------------- exports.base16 = chain(radix2(4), alphabet('0123456789ABCDEF'), join('')); exports.base32 = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join('')); +exports.base32nopad = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), join('')); exports.base32hex = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join('')); +exports.base32hexnopad = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), join('')); exports.base32crockford = chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))); exports.base64 = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join('')); exports.base64nopad = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), join('')); @@ -11102,6 +9415,8 @@ function genBech32(encoding) { function encode(prefix, words, limit = 90) { if (typeof prefix !== 'string') throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`); + if (words instanceof Uint8Array) + words = Array.from(words); if (!Array.isArray(words) || (words.length && typeof words[0] !== 'number')) throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`); if (prefix.length === 0) @@ -11140,7 +9455,19 @@ function genBech32(encoding) { const { prefix, words } = decode(str, false); return { prefix, words, bytes: fromWords(words) }; } - return { encode, decode, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords }; + function encodeFromBytes(prefix, bytes) { + return encode(prefix, toWords(bytes)); + } + return { + encode, + decode, + encodeFromBytes, + decodeToBytes, + decodeUnsafe, + fromWords, + fromWordsUnsafe, + toWords, + }; } exports.bech32 = genBech32('bech32'); exports.bech32m = genBech32('bech32m'); @@ -11184,160 +9511,160 @@ exports.bytes = exports.stringToBytes; /***/ ((__unused_webpack_module, exports) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BaseTree = void 0; -class BaseTree { - get capacity() { - return 2 ** this.levels; - } - get layers() { - return this._layers.slice(); - } - get zeros() { - return this._zeros.slice(); - } - get elements() { - return this._layers[0].slice(); - } - get root() { - var _a; - return (_a = this._layers[this.levels][0]) !== null && _a !== void 0 ? _a : this._zeros[this.levels]; - } - /** - * Find an element in the tree - * @param elements elements of tree - * @param element An element to find - * @param comparator A function that checks leaf value equality - * @param fromIndex The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned - * @returns {number} Index if element is found, otherwise -1 - */ - static indexOf(elements, element, fromIndex, comparator) { - if (comparator) { - return elements.findIndex((el) => comparator(element, el)); - } - else { - return elements.indexOf(element, fromIndex); - } - } - /** - * Insert new element into the tree - * @param element Element to insert - */ - insert(element) { - if (this._layers[0].length >= this.capacity) { - throw new Error('Tree is full'); - } - this.update(this._layers[0].length, element); - } - /* - * Insert multiple elements into the tree. - * @param {Array} elements Elements to insert - */ - bulkInsert(elements) { - if (!elements.length) { - return; - } - if (this._layers[0].length + elements.length > this.capacity) { - throw new Error('Tree is full'); - } - // First we insert all elements except the last one - // updating only full subtree hashes (all layers where inserted element has odd index) - // the last element will update the full path to the root making the tree consistent again - for (let i = 0; i < elements.length - 1; i++) { - this._layers[0].push(elements[i]); - let level = 0; - let index = this._layers[0].length - 1; - while (index % 2 === 1) { - level++; - index >>= 1; - const left = this._layers[level - 1][index * 2]; - const right = this._layers[level - 1][index * 2 + 1]; - this._layers[level][index] = this._hashFn(left, right); - } - } - this.insert(elements[elements.length - 1]); - } - /** - * Change an element in the tree - * @param {number} index Index of element to change - * @param element Updated element value - */ - update(index, element) { - if (isNaN(Number(index)) || index < 0 || index > this._layers[0].length || index >= this.capacity) { - throw new Error('Insert index out of bounds: ' + index); - } - this._layers[0][index] = element; - this._processUpdate(index); - } - /** - * Get merkle path to a leaf - * @param {number} index Leaf index to generate path for - * @returns {{pathElements: Object[], pathIndex: number[]}} An object containing adjacent elements and left-right index - */ - path(index) { - if (isNaN(Number(index)) || index < 0 || index >= this._layers[0].length) { - throw new Error('Index out of bounds: ' + index); - } - let elIndex = +index; - const pathElements = []; - const pathIndices = []; - const pathPositions = []; - for (let level = 0; level < this.levels; level++) { - pathIndices[level] = elIndex % 2; - const leafIndex = elIndex ^ 1; - if (leafIndex < this._layers[level].length) { - pathElements[level] = this._layers[level][leafIndex]; - pathPositions[level] = leafIndex; - } - else { - pathElements[level] = this._zeros[level]; - pathPositions[level] = 0; - } - elIndex >>= 1; - } - return { - pathElements, - pathIndices, - pathPositions, - pathRoot: this.root, - }; - } - _buildZeros() { - this._zeros = [this.zeroElement]; - for (let i = 1; i <= this.levels; i++) { - this._zeros[i] = this._hashFn(this._zeros[i - 1], this._zeros[i - 1]); - } - } - _processNodes(nodes, layerIndex) { - const length = nodes.length; - let currentLength = Math.ceil(length / 2); - const currentLayer = new Array(currentLength); - currentLength--; - const starFrom = length - ((length % 2) ^ 1); - let j = 0; - for (let i = starFrom; i >= 0; i -= 2) { - if (nodes[i - 1] === undefined) - break; - const left = nodes[i - 1]; - const right = (i === starFrom && length % 2 === 1) ? this._zeros[layerIndex - 1] : nodes[i]; - currentLayer[currentLength - j] = this._hashFn(left, right); - j++; - } - return currentLayer; - } - _processUpdate(index) { - for (let level = 1; level <= this.levels; level++) { - index >>= 1; - const left = this._layers[level - 1][index * 2]; - const right = index * 2 + 1 < this._layers[level - 1].length - ? this._layers[level - 1][index * 2 + 1] - : this._zeros[level - 1]; - this._layers[level][index] = this._hashFn(left, right); - } - } -} -exports.BaseTree = BaseTree; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BaseTree = void 0; +class BaseTree { + get capacity() { + return 2 ** this.levels; + } + get layers() { + return this._layers.slice(); + } + get zeros() { + return this._zeros.slice(); + } + get elements() { + return this._layers[0].slice(); + } + get root() { + var _a; + return (_a = this._layers[this.levels][0]) !== null && _a !== void 0 ? _a : this._zeros[this.levels]; + } + /** + * Find an element in the tree + * @param elements elements of tree + * @param element An element to find + * @param comparator A function that checks leaf value equality + * @param fromIndex The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned + * @returns {number} Index if element is found, otherwise -1 + */ + static indexOf(elements, element, fromIndex, comparator) { + if (comparator) { + return elements.findIndex((el) => comparator(element, el)); + } + else { + return elements.indexOf(element, fromIndex); + } + } + /** + * Insert new element into the tree + * @param element Element to insert + */ + insert(element) { + if (this._layers[0].length >= this.capacity) { + throw new Error('Tree is full'); + } + this.update(this._layers[0].length, element); + } + /* + * Insert multiple elements into the tree. + * @param {Array} elements Elements to insert + */ + bulkInsert(elements) { + if (!elements.length) { + return; + } + if (this._layers[0].length + elements.length > this.capacity) { + throw new Error('Tree is full'); + } + // First we insert all elements except the last one + // updating only full subtree hashes (all layers where inserted element has odd index) + // the last element will update the full path to the root making the tree consistent again + for (let i = 0; i < elements.length - 1; i++) { + this._layers[0].push(elements[i]); + let level = 0; + let index = this._layers[0].length - 1; + while (index % 2 === 1) { + level++; + index >>= 1; + const left = this._layers[level - 1][index * 2]; + const right = this._layers[level - 1][index * 2 + 1]; + this._layers[level][index] = this._hashFn(left, right); + } + } + this.insert(elements[elements.length - 1]); + } + /** + * Change an element in the tree + * @param {number} index Index of element to change + * @param element Updated element value + */ + update(index, element) { + if (isNaN(Number(index)) || index < 0 || index > this._layers[0].length || index >= this.capacity) { + throw new Error('Insert index out of bounds: ' + index); + } + this._layers[0][index] = element; + this._processUpdate(index); + } + /** + * Get merkle path to a leaf + * @param {number} index Leaf index to generate path for + * @returns {{pathElements: Object[], pathIndex: number[]}} An object containing adjacent elements and left-right index + */ + path(index) { + if (isNaN(Number(index)) || index < 0 || index >= this._layers[0].length) { + throw new Error('Index out of bounds: ' + index); + } + let elIndex = +index; + const pathElements = []; + const pathIndices = []; + const pathPositions = []; + for (let level = 0; level < this.levels; level++) { + pathIndices[level] = elIndex % 2; + const leafIndex = elIndex ^ 1; + if (leafIndex < this._layers[level].length) { + pathElements[level] = this._layers[level][leafIndex]; + pathPositions[level] = leafIndex; + } + else { + pathElements[level] = this._zeros[level]; + pathPositions[level] = 0; + } + elIndex >>= 1; + } + return { + pathElements, + pathIndices, + pathPositions, + pathRoot: this.root, + }; + } + _buildZeros() { + this._zeros = [this.zeroElement]; + for (let i = 1; i <= this.levels; i++) { + this._zeros[i] = this._hashFn(this._zeros[i - 1], this._zeros[i - 1]); + } + } + _processNodes(nodes, layerIndex) { + const length = nodes.length; + let currentLength = Math.ceil(length / 2); + const currentLayer = new Array(currentLength); + currentLength--; + const starFrom = length - ((length % 2) ^ 1); + let j = 0; + for (let i = starFrom; i >= 0; i -= 2) { + if (nodes[i - 1] === undefined) + break; + const left = nodes[i - 1]; + const right = (i === starFrom && length % 2 === 1) ? this._zeros[layerIndex - 1] : nodes[i]; + currentLayer[currentLength - j] = this._hashFn(left, right); + j++; + } + return currentLayer; + } + _processUpdate(index) { + for (let level = 1; level <= this.levels; level++) { + index >>= 1; + const left = this._layers[level - 1][index * 2]; + const right = index * 2 + 1 < this._layers[level - 1].length + ? this._layers[level - 1][index * 2 + 1] + : this._zeros[level - 1]; + this._layers[level][index] = this._hashFn(left, right); + } + } +} +exports.BaseTree = BaseTree; /***/ }), @@ -11346,120 +9673,120 @@ exports.BaseTree = BaseTree; /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const simpleHash_1 = __importDefault(__webpack_require__(5319)); -const BaseTree_1 = __webpack_require__(7736); -class MerkleTree extends BaseTree_1.BaseTree { - constructor(levels, elements = [], { hashFunction = simpleHash_1.default, zeroElement = 0, } = {}) { - super(); - this.levels = levels; - if (elements.length > this.capacity) { - throw new Error('Tree is full'); - } - this._hashFn = hashFunction; - this.zeroElement = zeroElement; - this._layers = []; - const leaves = elements.slice(); - this._layers = [leaves]; - this._buildZeros(); - this._buildHashes(); - } - _buildHashes() { - for (let layerIndex = 1; layerIndex <= this.levels; layerIndex++) { - const nodes = this._layers[layerIndex - 1]; - this._layers[layerIndex] = this._processNodes(nodes, layerIndex); - } - } - /** - * Insert multiple elements into the tree. - * @param {Array} elements Elements to insert - */ - bulkInsert(elements) { - if (!elements.length) { - return; - } - if (this._layers[0].length + elements.length > this.capacity) { - throw new Error('Tree is full'); - } - // First we insert all elements except the last one - // updating only full subtree hashes (all layers where inserted element has odd index) - // the last element will update the full path to the root making the tree consistent again - for (let i = 0; i < elements.length - 1; i++) { - this._layers[0].push(elements[i]); - let level = 0; - let index = this._layers[0].length - 1; - while (index % 2 === 1) { - level++; - index >>= 1; - this._layers[level][index] = this._hashFn(this._layers[level - 1][index * 2], this._layers[level - 1][index * 2 + 1]); - } - } - this.insert(elements[elements.length - 1]); - } - indexOf(element, comparator) { - return BaseTree_1.BaseTree.indexOf(this._layers[0], element, 0, comparator); - } - proof(element) { - const index = this.indexOf(element); - return this.path(index); - } - getTreeEdge(edgeIndex) { - const edgeElement = this._layers[0][edgeIndex]; - if (edgeElement === undefined) { - throw new Error('Element not found'); - } - const edgePath = this.path(edgeIndex); - return { edgePath, edgeElement, edgeIndex, edgeElementsCount: this._layers[0].length }; - } - /** - * 🪓 - * @param count - */ - getTreeSlices(count = 4) { - const length = this._layers[0].length; - let size = Math.ceil(length / count); - if (size % 2) - size++; - const slices = []; - for (let i = 0; i < length; i += size) { - const edgeLeft = i; - const edgeRight = i + size; - slices.push({ edge: this.getTreeEdge(edgeLeft), elements: this.elements.slice(edgeLeft, edgeRight) }); - } - return slices; - } - /** - * Serialize entire tree state including intermediate layers into a plain object - * Deserializing it back will not require to recompute any hashes - * Elements are not converted to a plain type, this is responsibility of the caller - */ - serialize() { - return { - levels: this.levels, - _zeros: this._zeros, - _layers: this._layers, - }; - } - /** - * Deserialize data into a MerkleTree instance - * Make sure to provide the same hashFunction as was used in the source tree, - * otherwise the tree state will be invalid - */ - static deserialize(data, hashFunction) { - const instance = Object.assign(Object.create(this.prototype), data); - instance._hashFn = hashFunction || simpleHash_1.default; - instance.zeroElement = instance._zeros[0]; - return instance; - } - toString() { - return JSON.stringify(this.serialize()); - } -} -exports["default"] = MerkleTree; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const simpleHash_1 = __importDefault(__webpack_require__(5319)); +const BaseTree_1 = __webpack_require__(7736); +class MerkleTree extends BaseTree_1.BaseTree { + constructor(levels, elements = [], { hashFunction = simpleHash_1.default, zeroElement = 0, } = {}) { + super(); + this.levels = levels; + if (elements.length > this.capacity) { + throw new Error('Tree is full'); + } + this._hashFn = hashFunction; + this.zeroElement = zeroElement; + this._layers = []; + const leaves = elements.slice(); + this._layers = [leaves]; + this._buildZeros(); + this._buildHashes(); + } + _buildHashes() { + for (let layerIndex = 1; layerIndex <= this.levels; layerIndex++) { + const nodes = this._layers[layerIndex - 1]; + this._layers[layerIndex] = this._processNodes(nodes, layerIndex); + } + } + /** + * Insert multiple elements into the tree. + * @param {Array} elements Elements to insert + */ + bulkInsert(elements) { + if (!elements.length) { + return; + } + if (this._layers[0].length + elements.length > this.capacity) { + throw new Error('Tree is full'); + } + // First we insert all elements except the last one + // updating only full subtree hashes (all layers where inserted element has odd index) + // the last element will update the full path to the root making the tree consistent again + for (let i = 0; i < elements.length - 1; i++) { + this._layers[0].push(elements[i]); + let level = 0; + let index = this._layers[0].length - 1; + while (index % 2 === 1) { + level++; + index >>= 1; + this._layers[level][index] = this._hashFn(this._layers[level - 1][index * 2], this._layers[level - 1][index * 2 + 1]); + } + } + this.insert(elements[elements.length - 1]); + } + indexOf(element, comparator) { + return BaseTree_1.BaseTree.indexOf(this._layers[0], element, 0, comparator); + } + proof(element) { + const index = this.indexOf(element); + return this.path(index); + } + getTreeEdge(edgeIndex) { + const edgeElement = this._layers[0][edgeIndex]; + if (edgeElement === undefined) { + throw new Error('Element not found'); + } + const edgePath = this.path(edgeIndex); + return { edgePath, edgeElement, edgeIndex, edgeElementsCount: this._layers[0].length }; + } + /** + * 🪓 + * @param count + */ + getTreeSlices(count = 4) { + const length = this._layers[0].length; + let size = Math.ceil(length / count); + if (size % 2) + size++; + const slices = []; + for (let i = 0; i < length; i += size) { + const edgeLeft = i; + const edgeRight = i + size; + slices.push({ edge: this.getTreeEdge(edgeLeft), elements: this.elements.slice(edgeLeft, edgeRight) }); + } + return slices; + } + /** + * Serialize entire tree state including intermediate layers into a plain object + * Deserializing it back will not require to recompute any hashes + * Elements are not converted to a plain type, this is responsibility of the caller + */ + serialize() { + return { + levels: this.levels, + _zeros: this._zeros, + _layers: this._layers, + }; + } + /** + * Deserialize data into a MerkleTree instance + * Make sure to provide the same hashFunction as was used in the source tree, + * otherwise the tree state will be invalid + */ + static deserialize(data, hashFunction) { + const instance = Object.assign(Object.create(this.prototype), data); + instance._hashFn = hashFunction || simpleHash_1.default; + instance.zeroElement = instance._zeros[0]; + return instance; + } + toString() { + return JSON.stringify(this.serialize()); + } +} +exports["default"] = MerkleTree; /***/ }), @@ -11468,165 +9795,165 @@ exports["default"] = MerkleTree; /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PartialMerkleTree = void 0; -const simpleHash_1 = __importDefault(__webpack_require__(5319)); -const BaseTree_1 = __webpack_require__(7736); -class PartialMerkleTree extends BaseTree_1.BaseTree { - constructor(levels, { edgePath, edgeElement, edgeIndex, edgeElementsCount, }, leaves, { hashFunction, zeroElement } = {}) { - super(); - if (edgeIndex + leaves.length !== edgeElementsCount) - throw new Error('Invalid number of elements'); - this._edgeLeafProof = edgePath; - this._initialRoot = edgePath.pathRoot; - this.zeroElement = zeroElement !== null && zeroElement !== void 0 ? zeroElement : 0; - this._edgeLeaf = { data: edgeElement, index: edgeIndex }; - this._leavesAfterEdge = leaves; - this.levels = levels; - this._hashFn = hashFunction || simpleHash_1.default; - this._createProofMap(); - this._buildTree(); - } - get edgeIndex() { - return this._edgeLeaf.index; - } - get edgeElement() { - return this._edgeLeaf.data; - } - get edgeLeafProof() { - return this._edgeLeafProof; - } - _createProofMap() { - this._proofMap = this.edgeLeafProof.pathPositions.reduce((p, c, i) => { - p.set(i, [c, this.edgeLeafProof.pathElements[i]]); - return p; - }, new Map()); - this._proofMap.set(this.levels, [0, this.edgeLeafProof.pathRoot]); - } - _buildTree() { - const edgeLeafIndex = this._edgeLeaf.index; - this._leaves = Array(edgeLeafIndex).concat(this._leavesAfterEdge); - if (this._proofMap.has(0)) { - const [proofPos, proofEl] = this._proofMap.get(0); - this._leaves[proofPos] = proofEl; - } - this._layers = [this._leaves]; - this._buildZeros(); - this._buildHashes(); - } - _buildHashes() { - for (let layerIndex = 1; layerIndex <= this.levels; layerIndex++) { - const nodes = this._layers[layerIndex - 1]; - const currentLayer = this._processNodes(nodes, layerIndex); - if (this._proofMap.has(layerIndex)) { - const [proofPos, proofEl] = this._proofMap.get(layerIndex); - if (!currentLayer[proofPos]) - currentLayer[proofPos] = proofEl; - } - this._layers[layerIndex] = currentLayer; - } - } - /** - * Change an element in the tree - * @param {number} index Index of element to change - * @param element Updated element value - */ - update(index, element) { - if (isNaN(Number(index)) || index < 0 || index > this._layers[0].length || index >= this.capacity) { - throw new Error('Insert index out of bounds: ' + index); - } - if (index < this._edgeLeaf.index) { - throw new Error(`Index ${index} is below the edge: ${this._edgeLeaf.index}`); - } - this._layers[0][index] = element; - this._processUpdate(index); - } - path(index) { - var _a; - if (isNaN(Number(index)) || index < 0 || index >= this._layers[0].length) { - throw new Error('Index out of bounds: ' + index); - } - if (index < this._edgeLeaf.index) { - throw new Error(`Index ${index} is below the edge: ${this._edgeLeaf.index}`); - } - let elIndex = Number(index); - const pathElements = []; - const pathIndices = []; - const pathPositions = []; - for (let level = 0; level < this.levels; level++) { - pathIndices[level] = elIndex % 2; - const leafIndex = elIndex ^ 1; - if (leafIndex < this._layers[level].length) { - pathElements[level] = this._layers[level][leafIndex]; - pathPositions[level] = leafIndex; - } - else { - pathElements[level] = this._zeros[level]; - pathPositions[level] = 0; - } - const [proofPos, proofEl] = this._proofMap.get(level); - pathElements[level] = (_a = pathElements[level]) !== null && _a !== void 0 ? _a : (proofPos === leafIndex ? proofEl : this._zeros[level]); - elIndex >>= 1; - } - return { - pathElements, - pathIndices, - pathPositions, - pathRoot: this.root, - }; - } - indexOf(element, comparator) { - return BaseTree_1.BaseTree.indexOf(this._layers[0], element, this.edgeIndex, comparator); - } - proof(element) { - const index = this.indexOf(element); - return this.path(index); - } - /** - * Shifts edge of tree to left - * @param edge new TreeEdge below current edge - * @param elements leaves between old and new edge - */ - shiftEdge(edge, elements) { - if (this._edgeLeaf.index <= edge.edgeIndex) { - throw new Error(`New edgeIndex should be smaller then ${this._edgeLeaf.index}`); - } - if (elements.length !== (this._edgeLeaf.index - edge.edgeIndex)) { - throw new Error(`Elements length should be ${this._edgeLeaf.index - edge.edgeIndex}`); - } - this._edgeLeafProof = edge.edgePath; - this._edgeLeaf = { index: edge.edgeIndex, data: edge.edgeElement }; - this._leavesAfterEdge = [...elements, ...this._leavesAfterEdge]; - this._createProofMap(); - this._buildTree(); - } - serialize() { - return { - _edgeLeafProof: this._edgeLeafProof, - _edgeLeaf: this._edgeLeaf, - _layers: this._layers, - _zeros: this._zeros, - levels: this.levels, - }; - } - static deserialize(data, hashFunction) { - const instance = Object.assign(Object.create(this.prototype), data); - instance._hashFn = hashFunction || simpleHash_1.default; - instance._initialRoot = data._edgeLeafProof.pathRoot; - instance.zeroElement = instance._zeros[0]; - instance._leavesAfterEdge = instance._layers[0].slice(data._edgeLeaf.index); - instance._createProofMap(); - return instance; - } - toString() { - return JSON.stringify(this.serialize()); - } -} -exports.PartialMerkleTree = PartialMerkleTree; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PartialMerkleTree = void 0; +const simpleHash_1 = __importDefault(__webpack_require__(5319)); +const BaseTree_1 = __webpack_require__(7736); +class PartialMerkleTree extends BaseTree_1.BaseTree { + constructor(levels, { edgePath, edgeElement, edgeIndex, edgeElementsCount, }, leaves, { hashFunction, zeroElement } = {}) { + super(); + if (edgeIndex + leaves.length !== edgeElementsCount) + throw new Error('Invalid number of elements'); + this._edgeLeafProof = edgePath; + this._initialRoot = edgePath.pathRoot; + this.zeroElement = zeroElement !== null && zeroElement !== void 0 ? zeroElement : 0; + this._edgeLeaf = { data: edgeElement, index: edgeIndex }; + this._leavesAfterEdge = leaves; + this.levels = levels; + this._hashFn = hashFunction || simpleHash_1.default; + this._createProofMap(); + this._buildTree(); + } + get edgeIndex() { + return this._edgeLeaf.index; + } + get edgeElement() { + return this._edgeLeaf.data; + } + get edgeLeafProof() { + return this._edgeLeafProof; + } + _createProofMap() { + this._proofMap = this.edgeLeafProof.pathPositions.reduce((p, c, i) => { + p.set(i, [c, this.edgeLeafProof.pathElements[i]]); + return p; + }, new Map()); + this._proofMap.set(this.levels, [0, this.edgeLeafProof.pathRoot]); + } + _buildTree() { + const edgeLeafIndex = this._edgeLeaf.index; + this._leaves = Array(edgeLeafIndex).concat(this._leavesAfterEdge); + if (this._proofMap.has(0)) { + const [proofPos, proofEl] = this._proofMap.get(0); + this._leaves[proofPos] = proofEl; + } + this._layers = [this._leaves]; + this._buildZeros(); + this._buildHashes(); + } + _buildHashes() { + for (let layerIndex = 1; layerIndex <= this.levels; layerIndex++) { + const nodes = this._layers[layerIndex - 1]; + const currentLayer = this._processNodes(nodes, layerIndex); + if (this._proofMap.has(layerIndex)) { + const [proofPos, proofEl] = this._proofMap.get(layerIndex); + if (!currentLayer[proofPos]) + currentLayer[proofPos] = proofEl; + } + this._layers[layerIndex] = currentLayer; + } + } + /** + * Change an element in the tree + * @param {number} index Index of element to change + * @param element Updated element value + */ + update(index, element) { + if (isNaN(Number(index)) || index < 0 || index > this._layers[0].length || index >= this.capacity) { + throw new Error('Insert index out of bounds: ' + index); + } + if (index < this._edgeLeaf.index) { + throw new Error(`Index ${index} is below the edge: ${this._edgeLeaf.index}`); + } + this._layers[0][index] = element; + this._processUpdate(index); + } + path(index) { + var _a; + if (isNaN(Number(index)) || index < 0 || index >= this._layers[0].length) { + throw new Error('Index out of bounds: ' + index); + } + if (index < this._edgeLeaf.index) { + throw new Error(`Index ${index} is below the edge: ${this._edgeLeaf.index}`); + } + let elIndex = Number(index); + const pathElements = []; + const pathIndices = []; + const pathPositions = []; + for (let level = 0; level < this.levels; level++) { + pathIndices[level] = elIndex % 2; + const leafIndex = elIndex ^ 1; + if (leafIndex < this._layers[level].length) { + pathElements[level] = this._layers[level][leafIndex]; + pathPositions[level] = leafIndex; + } + else { + pathElements[level] = this._zeros[level]; + pathPositions[level] = 0; + } + const [proofPos, proofEl] = this._proofMap.get(level); + pathElements[level] = (_a = pathElements[level]) !== null && _a !== void 0 ? _a : (proofPos === leafIndex ? proofEl : this._zeros[level]); + elIndex >>= 1; + } + return { + pathElements, + pathIndices, + pathPositions, + pathRoot: this.root, + }; + } + indexOf(element, comparator) { + return BaseTree_1.BaseTree.indexOf(this._layers[0], element, this.edgeIndex, comparator); + } + proof(element) { + const index = this.indexOf(element); + return this.path(index); + } + /** + * Shifts edge of tree to left + * @param edge new TreeEdge below current edge + * @param elements leaves between old and new edge + */ + shiftEdge(edge, elements) { + if (this._edgeLeaf.index <= edge.edgeIndex) { + throw new Error(`New edgeIndex should be smaller then ${this._edgeLeaf.index}`); + } + if (elements.length !== (this._edgeLeaf.index - edge.edgeIndex)) { + throw new Error(`Elements length should be ${this._edgeLeaf.index - edge.edgeIndex}`); + } + this._edgeLeafProof = edge.edgePath; + this._edgeLeaf = { index: edge.edgeIndex, data: edge.edgeElement }; + this._leavesAfterEdge = [...elements, ...this._leavesAfterEdge]; + this._createProofMap(); + this._buildTree(); + } + serialize() { + return { + _edgeLeafProof: this._edgeLeafProof, + _edgeLeaf: this._edgeLeaf, + _layers: this._layers, + _zeros: this._zeros, + levels: this.levels, + }; + } + static deserialize(data, hashFunction) { + const instance = Object.assign(Object.create(this.prototype), data); + instance._hashFn = hashFunction || simpleHash_1.default; + instance._initialRoot = data._edgeLeafProof.pathRoot; + instance.zeroElement = instance._zeros[0]; + instance._leavesAfterEdge = instance._layers[0].slice(data._edgeLeaf.index); + instance._createProofMap(); + return instance; + } + toString() { + return JSON.stringify(this.serialize()); + } +} +exports.PartialMerkleTree = PartialMerkleTree; /***/ }), @@ -11635,19 +9962,19 @@ exports.PartialMerkleTree = PartialMerkleTree; /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.MerkleTree = exports.simpleHash = exports.PartialMerkleTree = void 0; -const FixedMerkleTree_1 = __importDefault(__webpack_require__(9093)); -Object.defineProperty(exports, "MerkleTree", ({ enumerable: true, get: function () { return FixedMerkleTree_1.default; } })); -var PartialMerkleTree_1 = __webpack_require__(91230); -Object.defineProperty(exports, "PartialMerkleTree", ({ enumerable: true, get: function () { return PartialMerkleTree_1.PartialMerkleTree; } })); -var simpleHash_1 = __webpack_require__(5319); -Object.defineProperty(exports, "simpleHash", ({ enumerable: true, get: function () { return simpleHash_1.simpleHash; } })); -exports["default"] = FixedMerkleTree_1.default; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MerkleTree = exports.simpleHash = exports.PartialMerkleTree = void 0; +const FixedMerkleTree_1 = __importDefault(__webpack_require__(9093)); +Object.defineProperty(exports, "MerkleTree", ({ enumerable: true, get: function () { return FixedMerkleTree_1.default; } })); +var PartialMerkleTree_1 = __webpack_require__(91230); +Object.defineProperty(exports, "PartialMerkleTree", ({ enumerable: true, get: function () { return PartialMerkleTree_1.PartialMerkleTree; } })); +var simpleHash_1 = __webpack_require__(5319); +Object.defineProperty(exports, "simpleHash", ({ enumerable: true, get: function () { return simpleHash_1.simpleHash; } })); +exports["default"] = FixedMerkleTree_1.default; /***/ }), @@ -11656,27 +9983,27 @@ exports["default"] = FixedMerkleTree_1.default; /***/ ((__unused_webpack_module, exports) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.simpleHash = void 0; -/*** - * This is insecure hash function, just for example only - * @param data - * @param seed - * @param hashLength - */ -function simpleHash(data, seed, hashLength = 40) { - const str = data.join(''); - let i, l, hval = seed !== null && seed !== void 0 ? seed : 0x811c9dcc5; - for (i = 0, l = str.length; i < l; i++) { - hval ^= str.charCodeAt(i); - hval += (hval << 1) + (hval << 4) + (hval << 6) + (hval << 8) + (hval << 24); - } - const hash = (hval >>> 0).toString(16); - return BigInt('0x' + hash.padEnd(hashLength - (hash.length - 1), '0')).toString(10); -} -exports.simpleHash = simpleHash; -exports["default"] = (left, right) => simpleHash([left, right]); + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.simpleHash = void 0; +/*** + * This is insecure hash function, just for example only + * @param data + * @param seed + * @param hashLength + */ +function simpleHash(data, seed, hashLength = 40) { + const str = data.join(''); + let i, l, hval = seed !== null && seed !== void 0 ? seed : 0x811c9dcc5; + for (i = 0, l = str.length; i < l; i++) { + hval ^= str.charCodeAt(i); + hval += (hval << 1) + (hval << 4) + (hval << 6) + (hval << 8) + (hval << 24); + } + const hash = (hval >>> 0).toString(16); + return BigInt('0x' + hash.padEnd(hashLength - (hash.length - 1), '0')).toString(10); +} +exports.simpleHash = simpleHash; +exports["default"] = (left, right) => simpleHash([left, right]); /***/ }), @@ -12214,7 +10541,6 @@ module.exports = wBigInt; /***/ 28803: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/* provided dependency */ var console = __webpack_require__(96763); /* Copyright 2018 0kims association. @@ -12455,7 +10781,6 @@ class RTCtx { /***/ 98665: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/* provided dependency */ var console = __webpack_require__(96763); /* Copyright 2018 0kims association. @@ -14185,7 +12510,6 @@ if (true) { /***/ 36336: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/* provided dependency */ var process = __webpack_require__(65606); /* Copyright 2019 0KIMS association. @@ -15022,7 +13346,7 @@ function unhexifyBigInts(o) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; +exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; const core_1 = __webpack_require__(4042); const draft7_1 = __webpack_require__(86144); const discriminator_1 = __webpack_require__(36653); @@ -15051,7 +13375,9 @@ class Ajv extends core_1.default { super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)); } } +exports.Ajv = Ajv; module.exports = exports = Ajv; +module.exports.Ajv = Ajv; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = Ajv; var validate_1 = __webpack_require__(62586); @@ -15078,6 +13404,7 @@ Object.defineProperty(exports, "MissingRefError", ({ enumerable: true, get: func Object.defineProperty(exports, "__esModule", ({ value: true })); exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; +// eslint-disable-next-line @typescript-eslint/no-extraneous-class class _CodeOrName { } exports._CodeOrName = _CodeOrName; @@ -15955,7 +14282,7 @@ var UsedValueState; (function (UsedValueState) { UsedValueState[UsedValueState["Started"] = 0] = "Started"; UsedValueState[UsedValueState["Completed"] = 1] = "Completed"; -})(UsedValueState = exports.UsedValueState || (exports.UsedValueState = {})); +})(UsedValueState || (exports.UsedValueState = UsedValueState = {})); exports.varKinds = { const: new code_1.Name("const"), let: new code_1.Name("let"), @@ -16165,7 +14492,7 @@ function returnErrors(it, errs) { } const E = { keyword: new codegen_1.Name("keyword"), - schemaPath: new codegen_1.Name("schemaPath"), + schemaPath: new codegen_1.Name("schemaPath"), // also used in JTD errors params: new codegen_1.Name("params"), propertyName: new codegen_1.Name("propertyName"), message: new codegen_1.Name("message"), @@ -16278,7 +14605,7 @@ function compileSchema(sch) { parentData: names_1.default.parentData, parentDataProperty: names_1.default.parentDataProperty, dataNames: [names_1.default.data], - dataPathArr: [codegen_1.nil], + dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed? dataLevel: 0, dataTypes: [], definedProperties: new Set(), @@ -16475,17 +14802,17 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); const codegen_1 = __webpack_require__(99029); const names = { // validation function arguments - data: new codegen_1.Name("data"), + data: new codegen_1.Name("data"), // data passed to validation function // args passed from referencing schema - valCxt: new codegen_1.Name("valCxt"), + valCxt: new codegen_1.Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below instancePath: new codegen_1.Name("instancePath"), parentData: new codegen_1.Name("parentData"), parentDataProperty: new codegen_1.Name("parentDataProperty"), - rootData: new codegen_1.Name("rootData"), - dynamicAnchors: new codegen_1.Name("dynamicAnchors"), + rootData: new codegen_1.Name("rootData"), // root data - same as the data passed to the first/top validation function + dynamicAnchors: new codegen_1.Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef // function scoped variables - vErrors: new codegen_1.Name("vErrors"), - errors: new codegen_1.Name("errors"), + vErrors: new codegen_1.Name("vErrors"), // null or array of validation errors + errors: new codegen_1.Name("errors"), // counter of validation errors this: new codegen_1.Name("this"), // "globals" self: new codegen_1.Name("self"), @@ -16630,16 +14957,16 @@ function getSchemaRefs(schema, baseId) { if (parentJsonPtr === undefined) return; const fullPath = pathPrefix + jsonPtr; - let baseId = baseIds[parentJsonPtr]; + let innerBaseId = baseIds[parentJsonPtr]; if (typeof sch[schemaId] == "string") - baseId = addRef.call(this, sch[schemaId]); + innerBaseId = addRef.call(this, sch[schemaId]); addAnchor.call(this, sch.$anchor); addAnchor.call(this, sch.$dynamicAnchor); - baseIds[jsonPtr] = baseId; + baseIds[jsonPtr] = innerBaseId; function addRef(ref) { // eslint-disable-next-line @typescript-eslint/unbound-method const _resolve = this.opts.uriResolver.resolve; - ref = normalizeId(baseId ? _resolve(baseId, ref) : ref); + ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); if (schemaRefs.has(ref)) throw ambiguos(ref); schemaRefs.add(ref); @@ -16871,7 +15198,7 @@ var Type; (function (Type) { Type[Type["Num"] = 0] = "Num"; Type[Type["Str"] = 1] = "Str"; -})(Type = exports.Type || (exports.Type = {})); +})(Type || (exports.Type = Type = {})); function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { // let path if (dataProp instanceof codegen_1.Name) { @@ -16999,7 +15326,7 @@ var DataType; (function (DataType) { DataType[DataType["Correct"] = 0] = "Correct"; DataType[DataType["Wrong"] = 1] = "Wrong"; -})(DataType = exports.DataType || (exports.DataType = {})); +})(DataType || (exports.DataType = DataType = {})); function getSchemaTypes(schema) { const types = getJSONTypes(schema.type); const hasNull = types.includes("null"); @@ -17017,6 +15344,7 @@ function getSchemaTypes(schema) { return types; } exports.getSchemaTypes = getSchemaTypes; +// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents function getJSONTypes(ts) { const types = Array.isArray(ts) ? ts : ts ? [ts] : []; if (types.every(rules_1.isJSONType)) @@ -17984,7 +16312,6 @@ exports.extendSubschemaMode = extendSubschemaMode; /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var console = __webpack_require__(96763); Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; @@ -18125,6 +16452,7 @@ class Ajv { return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined); } validate(schemaKeyRef, // key, ref or schema object + // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents data // to be validated ) { let v; @@ -18473,9 +16801,9 @@ class Ajv { } } } -exports["default"] = Ajv; Ajv.ValidationError = validation_error_1.default; Ajv.MissingRefError = ref_error_1.default; +exports["default"] = Ajv; function checkOptions(checkOpts, options, msg, log = "error") { for (const key in checkOpts) { const opt = key; @@ -18656,7 +16984,7 @@ ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const uri = __webpack_require__(46579); +const uri = __webpack_require__(48343); uri.code = 'require("ajv/dist/runtime/uri").default'; exports["default"] = uri; //# sourceMappingURL=uri.js.map @@ -19956,6 +18284,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); const codegen_1 = __webpack_require__(99029); const types_1 = __webpack_require__(97652); const compile_1 = __webpack_require__(73835); +const ref_error_1 = __webpack_require__(34551); const util_1 = __webpack_require__(94227); const error = { message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag @@ -20010,9 +18339,12 @@ const def = { for (let i = 0; i < oneOf.length; i++) { let sch = oneOf[i]; if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { - sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, sch === null || sch === void 0 ? void 0 : sch.$ref); + const ref = sch.$ref; + sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; + if (sch === undefined) + throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); } const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; if (typeof propSch != "object") { @@ -20065,7 +18397,7 @@ var DiscrError; (function (DiscrError) { DiscrError["Tag"] = "tag"; DiscrError["Mapping"] = "mapping"; -})(DiscrError = exports.DiscrError || (exports.DiscrError = {})); +})(DiscrError || (exports.DiscrError = DiscrError = {})); //# sourceMappingURL=types.js.map /***/ }), @@ -25970,8 +24302,6 @@ PEMEncoder.prototype.encode = function encode(data, options) { /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(65606); -/* provided dependency */ var console = __webpack_require__(96763); // Currently in sync with Node.js lib/assert.js // https://github.com/nodejs/node/commit/2a51ae424a513ec9a6aa3466baa0cc1d55dd4f3b @@ -26569,7 +24899,6 @@ assert.strict.strict = assert.strict; /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(65606); // Currently in sync with Node.js lib/internal/assert/assertion_error.js // https://github.com/nodejs/node/commit/0817840f775032169ddd70c85ac059f18ffcc81c @@ -36785,7 +35114,6 @@ PassThrough.prototype._transform = function (chunk, encoding, cb) { /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(65606); // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -38033,7 +36361,6 @@ function done(stream, er, data) { /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(65606); // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -39366,7 +37693,6 @@ SafeBuffer.allocUnsafeSlow = function (size) { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; -/* provided dependency */ var process = __webpack_require__(65606); /* eslint camelcase: "off" */ @@ -39783,7 +38109,6 @@ exports.Zlib = Zlib; /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(65606); var Buffer = (__webpack_require__(48287).Buffer); @@ -40418,7 +38743,6 @@ module.exports = function xor (a, b) { /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var console = __webpack_require__(96763); /*! * The buffer module from node.js, for the browser. * @@ -42770,100 +41094,6 @@ CipherBase.prototype._toString = function (value, enc, fin) { module.exports = CipherBase -/***/ }), - -/***/ 96763: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/*global window, global*/ -var util = __webpack_require__(40537) -var assert = __webpack_require__(94148) -function now() { return new Date().getTime() } - -var slice = Array.prototype.slice -var console -var times = {} - -if (typeof __webpack_require__.g !== "undefined" && __webpack_require__.g.console) { - console = __webpack_require__.g.console -} else if (typeof window !== "undefined" && window.console) { - console = window.console -} else { - console = {} -} - -var functions = [ - [log, "log"], - [info, "info"], - [warn, "warn"], - [error, "error"], - [time, "time"], - [timeEnd, "timeEnd"], - [trace, "trace"], - [dir, "dir"], - [consoleAssert, "assert"] -] - -for (var i = 0; i < functions.length; i++) { - var tuple = functions[i] - var f = tuple[0] - var name = tuple[1] - - if (!console[name]) { - console[name] = f - } -} - -module.exports = console - -function log() {} - -function info() { - console.log.apply(console, arguments) -} - -function warn() { - console.log.apply(console, arguments) -} - -function error() { - console.warn.apply(console, arguments) -} - -function time(label) { - times[label] = now() -} - -function timeEnd(label) { - var time = times[label] - if (!time) { - throw new Error("No such label: " + label) - } - - delete times[label] - var duration = now() - time - console.log(label + ": " + duration + "ms") -} - -function trace() { - var err = new Error() - err.name = "Trace" - err.message = util.format.apply(null, arguments) - console.error(err.stack) -} - -function dir(object) { - console.log(util.inspect(object) + "\n") -} - -function consoleAssert(expression) { - if (!expression) { - var arr = slice.call(arguments, 1) - assert.ok(false, util.format.apply(null, arr)) - } -} - - /***/ }), /***/ 15622: @@ -47502,8 +45732,6 @@ exports.constants = { /***/ 17833: /***/ ((module, exports, __webpack_require__) => { -/* provided dependency */ var console = __webpack_require__(96763); -/* provided dependency */ var process = __webpack_require__(65606); /* eslint-env browser */ /** @@ -47631,6 +45859,8 @@ function useColors() { return false; } + let m; + // Is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || @@ -47638,7 +45868,7 @@ function useColors() { (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) || // Double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } @@ -47780,7 +46010,6 @@ formatters.j = function (v) { /***/ 40736: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/* provided dependency */ var console = __webpack_require__(96763); /** * This is the common logic for both the Node.js and web browser @@ -55327,6 +53556,10 @@ function getLength(buf, p) { return false; } + if(buf[p.place] === 0x00) { + return false; + } + var val = 0; for (var i = 0, off = p.place; i < octetLen; i++, off++) { val <<= 8; @@ -55375,6 +53608,9 @@ Signature.prototype._importDER = function _importDER(data, enc) { if (rlen === false) { return false; } + if ((data[p.place] & 128) !== 0) { + return false; + } var r = data.slice(p.place, rlen + p.place); p.place += rlen; if (data[p.place++] !== 0x02) { @@ -55387,6 +53623,9 @@ Signature.prototype._importDER = function _importDER(data, enc) { if (data.length !== slen + p.place) { return false; } + if ((data[p.place] & 128) !== 0) { + return false; + } var s = data.slice(p.place, slen + p.place); if (r[0] === 0) { if (r[1] & 0x80) { @@ -55515,6 +53754,9 @@ EDDSA.prototype.sign = function sign(message, secret) { EDDSA.prototype.verify = function verify(message, sig, pub) { message = parseBytes(message); sig = this.makeSignature(sig); + if (sig.S().gte(sig.eddsa.curve.n) || sig.S().isNeg()) { + return false; + } var key = this.keyFromPublic(pub); var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); var SG = this.g.mul(sig.S()); @@ -55713,6 +53955,7 @@ function Signature(eddsa, sig) { sig = parseBytes(sig); if (Array.isArray(sig)) { + assert(sig.length === eddsa.encodingLength * 2, 'Signature has invalid size'); sig = { R: sig.slice(0, eddsa.encodingLength), S: sig.slice(eddsa.encodingLength), @@ -60829,7 +59072,6 @@ class NoteAccount { /* harmony import */ var ethers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(30031); /* harmony import */ var _graphql__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(52049); /* harmony import */ var _batch__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9723); -/* provided dependency */ var console = __webpack_require__(96763); var __defProp = Object.defineProperty; var __defProps = Object.defineProperties; @@ -60946,11 +59188,15 @@ class BaseEventsService { }; }); } + /** + * Events from remote cache (Either from local cache, CDN, or from IPFS) + */ getEventsFromCache() { return __async(this, null, function* () { return { events: [], - lastBlock: null + lastBlock: null, + fromCache: true }; }); } @@ -61078,7 +59324,9 @@ class BaseEventsService { }); const lastBlock = newEvents ? newEvents.lastBlock : allEvents[allEvents.length - 1] ? allEvents[allEvents.length - 1].blockNumber : null; this.validateEvents({ events: allEvents, lastBlock }); - this.saveEventsPromise = this.saveEvents({ events: allEvents, lastBlock }); + if (savedEvents.fromCache || newEvents.events.length) { + yield this.saveEvents({ events: allEvents, lastBlock }); + } return { events: allEvents, lastBlock @@ -61786,7 +60034,6 @@ const GET_GOVERNANCE_APY = ` `; ;// CONCATENATED MODULE: ./src/graphql/index.ts -/* provided dependency */ var console = __webpack_require__(96763); var __defProp = Object.defineProperty; var __defProps = Object.defineProperties; @@ -62589,7 +60836,6 @@ function getAllGovernanceEvents(_0) { /* harmony import */ var _tornado_fixed_merkle_tree__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_tornado_fixed_merkle_tree__WEBPACK_IMPORTED_MODULE_1__); /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(67418); /* harmony import */ var _mimc__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(22901); -/* provided dependency */ var console = __webpack_require__(96763); var __async = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { @@ -62775,7 +61021,7 @@ Creating deposit tree for ${this.netId} ${this.amount} ${this.currency.toUpperCa /* harmony export */ f: () => (/* binding */ mimc), /* harmony export */ p: () => (/* binding */ Mimc) /* harmony export */ }); -/* harmony import */ var circomlibjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(89082); +/* harmony import */ var circomlibjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(90294); var __async = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { @@ -63133,7 +61379,6 @@ const defaultConfig = { routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", - gasPriceOracleContract: "0xF81A8D8D3581985D3969fe53bFA67074aDFa8F3C", tornadoSubgraph: "tornadocash/matic-tornado-subgraph", subgraphs: { tornado, @@ -63506,7 +61751,7 @@ function getSubdomains() { /* harmony export */ NO: () => (/* binding */ pedersen), /* harmony export */ UB: () => (/* binding */ buffPedersenHash) /* harmony export */ }); -/* harmony import */ var circomlibjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(89082); +/* harmony import */ var circomlibjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(90294); var __async = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { @@ -63638,7 +61883,6 @@ __webpack_require__.d(__webpack_exports__, { hd: () => (/* binding */ providers_fetch), Fd: () => (/* binding */ fetchData), uY: () => (/* binding */ fetchGetUrlFunc), - bD: () => (/* binding */ getGasOraclePlugin), WU: () => (/* binding */ getHttpAgent), sO: () => (/* binding */ getProvider), MF: () => (/* binding */ getProviderWithNetId), @@ -63648,219 +61892,6 @@ __webpack_require__.d(__webpack_exports__, { // EXTERNAL MODULE: ./node_modules/cross-fetch/dist/browser-ponyfill.js var browser_ponyfill = __webpack_require__(74945); var browser_ponyfill_default = /*#__PURE__*/__webpack_require__.n(browser_ponyfill); -// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/properties.js -var properties = __webpack_require__(88081); -// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/errors.js -var errors = __webpack_require__(57339); -;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/providers/plugins-network.js - - -const EnsAddress = "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"; -/** - * A **NetworkPlugin** provides additional functionality on a [[Network]]. - */ -class NetworkPlugin { - /** - * The name of the plugin. - * - * It is recommended to use reverse-domain-notation, which permits - * unique names with a known authority as well as hierarchal entries. - */ - name; - /** - * Creates a new **NetworkPlugin**. - */ - constructor(name) { - (0,properties/* defineProperties */.n)(this, { name }); - } - /** - * Creates a copy of this plugin. - */ - clone() { - return new NetworkPlugin(this.name); - } -} -/** - * A **GasCostPlugin** allows a network to provide alternative values when - * computing the intrinsic gas required for a transaction. - */ -class GasCostPlugin extends NetworkPlugin { - /** - * The block number to treat these values as valid from. - * - * This allows a hardfork to have updated values included as well as - * mulutiple hardforks to be supported. - */ - effectiveBlock; - /** - * The transactions base fee. - */ - txBase; - /** - * The fee for creating a new account. - */ - txCreate; - /** - * The fee per zero-byte in the data. - */ - txDataZero; - /** - * The fee per non-zero-byte in the data. - */ - txDataNonzero; - /** - * The fee per storage key in the [[link-eip-2930]] access list. - */ - txAccessListStorageKey; - /** - * The fee per address in the [[link-eip-2930]] access list. - */ - txAccessListAddress; - /** - * Creates a new GasCostPlugin from %%effectiveBlock%% until the - * latest block or another GasCostPlugin supercedes that block number, - * with the associated %%costs%%. - */ - constructor(effectiveBlock, costs) { - if (effectiveBlock == null) { - effectiveBlock = 0; - } - super(`org.ethers.network.plugins.GasCost#${(effectiveBlock || 0)}`); - const props = { effectiveBlock }; - function set(name, nullish) { - let value = (costs || {})[name]; - if (value == null) { - value = nullish; - } - (0,errors/* assertArgument */.MR)(typeof (value) === "number", `invalud value for ${name}`, "costs", costs); - props[name] = value; - } - set("txBase", 21000); - set("txCreate", 32000); - set("txDataZero", 4); - set("txDataNonzero", 16); - set("txAccessListStorageKey", 1900); - set("txAccessListAddress", 2400); - (0,properties/* defineProperties */.n)(this, props); - } - clone() { - return new GasCostPlugin(this.effectiveBlock, this); - } -} -/** - * An **EnsPlugin** allows a [[Network]] to specify the ENS Registry - * Contract address and the target network to use when using that - * contract. - * - * Various testnets have their own instance of the contract to use, but - * in general, the mainnet instance supports multi-chain addresses and - * should be used. - */ -class EnsPlugin extends NetworkPlugin { - /** - * The ENS Registrty Contract address. - */ - address; - /** - * The chain ID that the ENS contract lives on. - */ - targetNetwork; - /** - * Creates a new **EnsPlugin** connected to %%address%% on the - * %%targetNetwork%%. The default ENS address and mainnet is used - * if unspecified. - */ - constructor(address, targetNetwork) { - super("org.ethers.plugins.network.Ens"); - (0,properties/* defineProperties */.n)(this, { - address: (address || EnsAddress), - targetNetwork: ((targetNetwork == null) ? 1 : targetNetwork) - }); - } - clone() { - return new EnsPlugin(this.address, this.targetNetwork); - } -} -/** - * A **FeeDataNetworkPlugin** allows a network to provide and alternate - * means to specify its fee data. - * - * For example, a network which does not support [[link-eip-1559]] may - * choose to use a Gas Station site to approximate the gas price. - */ -class FeeDataNetworkPlugin extends NetworkPlugin { - #feeDataFunc; - /** - * The fee data function provided to the constructor. - */ - get feeDataFunc() { - return this.#feeDataFunc; - } - /** - * Creates a new **FeeDataNetworkPlugin**. - */ - constructor(feeDataFunc) { - super("org.ethers.plugins.network.FeeData"); - this.#feeDataFunc = feeDataFunc; - } - /** - * Resolves to the fee data. - */ - async getFeeData(provider) { - return await this.#feeDataFunc(provider); - } - clone() { - return new FeeDataNetworkPlugin(this.#feeDataFunc); - } -} -class FetchUrlFeeDataNetworkPlugin extends NetworkPlugin { - #url; - #processFunc; - /** - * The URL to initialize the FetchRequest with in %%processFunc%%. - */ - get url() { return this.#url; } - /** - * The callback to use when computing the FeeData. - */ - get processFunc() { return this.#processFunc; } - /** - * Creates a new **FetchUrlFeeDataNetworkPlugin** which will - * be used when computing the fee data for the network. - */ - constructor(url, processFunc) { - super("org.ethers.plugins.network.FetchUrlFeeDataPlugin"); - this.#url = url; - this.#processFunc = processFunc; - } - // We are immutable, so we can serve as our own clone - clone() { return this; } -} -/* -export class CustomBlockNetworkPlugin extends NetworkPlugin { - readonly #blockFunc: (provider: Provider, block: BlockParams) => Block; - readonly #blockWithTxsFunc: (provider: Provider, block: BlockParams) => Block; - - constructor(blockFunc: (provider: Provider, block: BlockParams) => Block, blockWithTxsFunc: (provider: Provider, block: BlockParams) => Block) { - super("org.ethers.network-plugins.custom-block"); - this.#blockFunc = blockFunc; - this.#blockWithTxsFunc = blockWithTxsFunc; - } - - async getBlock(provider: Provider, block: BlockParams): Promise> { - return await this.#blockFunc(provider, block); - } - - async getBlockions(provider: Provider, block: BlockParams): Promise> { - return await this.#blockWithTxsFunc(provider, block); - } - - clone(): CustomBlockNetworkPlugin { - return new CustomBlockNetworkPlugin(this.#blockFunc, this.#blockWithTxsFunc); - } -} -*/ -//# sourceMappingURL=plugins-network.js.map // EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/data.js var utils_data = __webpack_require__(36212); ;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/utils/base64-browser.js @@ -63883,13 +61914,17 @@ function encodeBase64(_data) { return btoa(textData); } //# sourceMappingURL=base64-browser.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/errors.js +var errors = __webpack_require__(57339); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/properties.js +var properties = __webpack_require__(88081); // EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/utf8.js var utf8 = __webpack_require__(87303); ;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/utils/geturl-browser.js -// @TODO: timeout is completely ignored; start a Promise.any with a reject? function createGetUrl(options) { async function getUrl(req, _signal) { + (0,errors/* assert */.vA)(_signal == null || !_signal.cancelled, "request cancelled before sending", "CANCELLED"); const protocol = req.url.split(":")[0].toLowerCase(); (0,errors/* assert */.vA)(protocol === "http" || protocol === "https", `unsupported protocol ${protocol}`, "UNSUPPORTED_OPERATION", { info: { protocol }, @@ -63898,19 +61933,36 @@ function createGetUrl(options) { (0,errors/* assert */.vA)(protocol === "https" || !req.credentials || req.allowInsecureAuthentication, "insecure authorized connections unsupported", "UNSUPPORTED_OPERATION", { operation: "request" }); - let signal = undefined; + let error = null; + const controller = new AbortController(); + const timer = setTimeout(() => { + error = (0,errors/* makeError */.xz)("request timeout", "TIMEOUT"); + controller.abort(); + }, req.timeout); if (_signal) { - const controller = new AbortController(); - signal = controller.signal; - _signal.addListener(() => { controller.abort(); }); + _signal.addListener(() => { + error = (0,errors/* makeError */.xz)("request cancelled", "CANCELLED"); + controller.abort(); + }); } const init = { method: req.method, headers: new Headers(Array.from(req)), body: req.body || undefined, - signal + signal: controller.signal }; - const resp = await fetch(req.url, init); + let resp; + try { + resp = await fetch(req.url, init); + } + catch (_error) { + clearTimeout(timer); + if (error) { + throw error; + } + throw _error; + } + clearTimeout(timer); const headers = {}; resp.headers.forEach((value, key) => { headers[key.toLowerCase()] = value; @@ -64784,8 +62836,6 @@ function wait(delay) { return new Promise((resolve) => setTimeout(resolve, delay)); } //# sourceMappingURL=fetch.js.map -// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/units.js + 1 modules -var units = __webpack_require__(99770); // EXTERNAL MODULE: ./node_modules/ethers/lib.esm/abi/abi-coder.js + 10 modules var abi_coder = __webpack_require__(35273); // EXTERNAL MODULE: ./node_modules/ethers/lib.esm/address/address.js @@ -65446,13 +63496,13 @@ class MulticoinProviderPlugin { return false; } /** - * Resovles to the encoded %%address%% for %%coinType%%. + * Resolves to the encoded %%address%% for %%coinType%%. */ async encodeAddress(coinType, address) { throw new Error("unsupported coin"); } /** - * Resovles to the decoded %%data%% for %%coinType%%. + * Resolves to the decoded %%data%% for %%coinType%%. */ async decodeAddress(coinType, data) { throw new Error("unsupported coin"); @@ -66241,6 +64291,215 @@ function formatTransactionResponse(value) { return result; } //# sourceMappingURL=format.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/providers/plugins-network.js + + +const EnsAddress = "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"; +/** + * A **NetworkPlugin** provides additional functionality on a [[Network]]. + */ +class NetworkPlugin { + /** + * The name of the plugin. + * + * It is recommended to use reverse-domain-notation, which permits + * unique names with a known authority as well as hierarchal entries. + */ + name; + /** + * Creates a new **NetworkPlugin**. + */ + constructor(name) { + (0,properties/* defineProperties */.n)(this, { name }); + } + /** + * Creates a copy of this plugin. + */ + clone() { + return new NetworkPlugin(this.name); + } +} +/** + * A **GasCostPlugin** allows a network to provide alternative values when + * computing the intrinsic gas required for a transaction. + */ +class GasCostPlugin extends NetworkPlugin { + /** + * The block number to treat these values as valid from. + * + * This allows a hardfork to have updated values included as well as + * mulutiple hardforks to be supported. + */ + effectiveBlock; + /** + * The transactions base fee. + */ + txBase; + /** + * The fee for creating a new account. + */ + txCreate; + /** + * The fee per zero-byte in the data. + */ + txDataZero; + /** + * The fee per non-zero-byte in the data. + */ + txDataNonzero; + /** + * The fee per storage key in the [[link-eip-2930]] access list. + */ + txAccessListStorageKey; + /** + * The fee per address in the [[link-eip-2930]] access list. + */ + txAccessListAddress; + /** + * Creates a new GasCostPlugin from %%effectiveBlock%% until the + * latest block or another GasCostPlugin supercedes that block number, + * with the associated %%costs%%. + */ + constructor(effectiveBlock, costs) { + if (effectiveBlock == null) { + effectiveBlock = 0; + } + super(`org.ethers.network.plugins.GasCost#${(effectiveBlock || 0)}`); + const props = { effectiveBlock }; + function set(name, nullish) { + let value = (costs || {})[name]; + if (value == null) { + value = nullish; + } + (0,errors/* assertArgument */.MR)(typeof (value) === "number", `invalud value for ${name}`, "costs", costs); + props[name] = value; + } + set("txBase", 21000); + set("txCreate", 32000); + set("txDataZero", 4); + set("txDataNonzero", 16); + set("txAccessListStorageKey", 1900); + set("txAccessListAddress", 2400); + (0,properties/* defineProperties */.n)(this, props); + } + clone() { + return new GasCostPlugin(this.effectiveBlock, this); + } +} +/** + * An **EnsPlugin** allows a [[Network]] to specify the ENS Registry + * Contract address and the target network to use when using that + * contract. + * + * Various testnets have their own instance of the contract to use, but + * in general, the mainnet instance supports multi-chain addresses and + * should be used. + */ +class EnsPlugin extends NetworkPlugin { + /** + * The ENS Registrty Contract address. + */ + address; + /** + * The chain ID that the ENS contract lives on. + */ + targetNetwork; + /** + * Creates a new **EnsPlugin** connected to %%address%% on the + * %%targetNetwork%%. The default ENS address and mainnet is used + * if unspecified. + */ + constructor(address, targetNetwork) { + super("org.ethers.plugins.network.Ens"); + (0,properties/* defineProperties */.n)(this, { + address: (address || EnsAddress), + targetNetwork: ((targetNetwork == null) ? 1 : targetNetwork) + }); + } + clone() { + return new EnsPlugin(this.address, this.targetNetwork); + } +} +/** + * A **FeeDataNetworkPlugin** allows a network to provide and alternate + * means to specify its fee data. + * + * For example, a network which does not support [[link-eip-1559]] may + * choose to use a Gas Station site to approximate the gas price. + */ +class FeeDataNetworkPlugin extends NetworkPlugin { + #feeDataFunc; + /** + * The fee data function provided to the constructor. + */ + get feeDataFunc() { + return this.#feeDataFunc; + } + /** + * Creates a new **FeeDataNetworkPlugin**. + */ + constructor(feeDataFunc) { + super("org.ethers.plugins.network.FeeData"); + this.#feeDataFunc = feeDataFunc; + } + /** + * Resolves to the fee data. + */ + async getFeeData(provider) { + return await this.#feeDataFunc(provider); + } + clone() { + return new FeeDataNetworkPlugin(this.#feeDataFunc); + } +} +class FetchUrlFeeDataNetworkPlugin extends NetworkPlugin { + #url; + #processFunc; + /** + * The URL to initialize the FetchRequest with in %%processFunc%%. + */ + get url() { return this.#url; } + /** + * The callback to use when computing the FeeData. + */ + get processFunc() { return this.#processFunc; } + /** + * Creates a new **FetchUrlFeeDataNetworkPlugin** which will + * be used when computing the fee data for the network. + */ + constructor(url, processFunc) { + super("org.ethers.plugins.network.FetchUrlFeeDataPlugin"); + this.#url = url; + this.#processFunc = processFunc; + } + // We are immutable, so we can serve as our own clone + clone() { return this; } +} +/* +export class CustomBlockNetworkPlugin extends NetworkPlugin { + readonly #blockFunc: (provider: Provider, block: BlockParams) => Block; + readonly #blockWithTxsFunc: (provider: Provider, block: BlockParams) => Block; + + constructor(blockFunc: (provider: Provider, block: BlockParams) => Block, blockWithTxsFunc: (provider: Provider, block: BlockParams) => Block) { + super("org.ethers.network-plugins.custom-block"); + this.#blockFunc = blockFunc; + this.#blockWithTxsFunc = blockWithTxsFunc; + } + + async getBlock(provider: Provider, block: BlockParams): Promise> { + return await this.#blockFunc(provider, block); + } + + async getBlockions(provider: Provider, block: BlockParams): Promise> { + return await this.#blockWithTxsFunc(provider, block); + } + + clone(): CustomBlockNetworkPlugin { + return new CustomBlockNetworkPlugin(this.#blockFunc, this.#blockWithTxsFunc); + } +} +*/ +//# sourceMappingURL=plugins-network.js.map ;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/providers/network.js /** * A **Network** encapsulates the various properties required to @@ -66608,7 +64867,6 @@ function injectCommonNetworks() { // EXTERNAL MODULE: ./node_modules/ethers/lib.esm/providers/provider.js var providers_provider = __webpack_require__(43948); ;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/providers/subscriber-polling.js -/* provided dependency */ var console = __webpack_require__(96763); function copy(obj) { return JSON.parse(JSON.stringify(obj)); @@ -66903,7 +65161,6 @@ class PollingEventSubscriber { } //# sourceMappingURL=subscriber-polling.js.map ;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/providers/abstract-provider.js -/* provided dependency */ var abstract_provider_console = __webpack_require__(96763); /** * The available providers should suffice for most developers purposes, * but the [[AbstractProvider]] class has many features which enable @@ -67406,7 +65663,7 @@ class AbstractProvider { return resolve(address, fromBlock, toBlock); } /** - * Returns or resovles to a transaction for %%request%%, resolving + * Returns or resolves to a transaction for %%request%%, resolving * any ENS names or [[Addressable]] and returning if already a valid * transaction. */ @@ -67806,7 +66063,7 @@ class AbstractProvider { } } catch (error) { - abstract_provider_console.log("EEE", error); + console.log("EEE", error); } this.once("block", listener); }); @@ -68522,7 +66779,6 @@ class VoidSigner extends AbstractSigner { } //# sourceMappingURL=abstract-signer.js.map ;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/providers/subscriber-filterid.js -/* provided dependency */ var subscriber_filterid_console = __webpack_require__(96763); function subscriber_filterid_copy(obj) { @@ -68613,7 +66869,7 @@ class FilterIdSubscriber { await this._emitResults(this.#provider, result); } catch (error) { - subscriber_filterid_console.log("@TODO", error); + console.log("@TODO", error); } this.#provider.once("block", this.#poller); } @@ -68698,7 +66954,6 @@ class FilterIdPendingSubscriber extends FilterIdSubscriber { } //# sourceMappingURL=subscriber-filterid.js.map ;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/providers/provider-jsonrpc.js -/* provided dependency */ var provider_jsonrpc_console = __webpack_require__(96763); /** * One of the most common ways to interact with the blockchain is * by a node running a JSON-RPC interface which can be connected to, @@ -69070,7 +67325,7 @@ class JsonRpcApiProvider extends AbstractProvider { if (req.method === "call" || req.method === "estimateGas") { let tx = req.transaction; if (tx && tx.type != null && (0,maths/* getBigInt */.Ab)(tx.type)) { - // If there are no EIP-1559 properties, it might be non-EIP-a559 + // If there are no EIP-1559 or newer properties, it might be pre-EIP-1559 if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) { const feeData = await this.getFeeData(); if (feeData.maxFeePerGas == null && feeData.maxPriorityFeePerGas == null) { @@ -69172,7 +67427,7 @@ class JsonRpcApiProvider extends AbstractProvider { if (this.destroyed) { break; } - provider_jsonrpc_console.log("JsonRpcProvider failed to detect network and cannot start up; retry in 1s (perhaps the URL is wrong or the node is not started)"); + console.log("JsonRpcProvider failed to detect network and cannot start up; retry in 1s (perhaps the URL is wrong or the node is not started)"); this.emit("error", (0,errors/* makeError */.xz)("failed to bootstrap network detection", "NETWORK_ERROR", { event: "initial-network-discovery", info: { error } })); await stall(1000); } @@ -69249,6 +67504,14 @@ class JsonRpcApiProvider extends AbstractProvider { if (tx.accessList) { result["accessList"] = (0,accesslist/* accessListify */.$)(tx.accessList); } + if (tx.blobVersionedHashes) { + // @TODO: Remove this case once EIP-4844 added to prepared tx + result["blobVersionedHashes"] = tx.blobVersionedHashes.map(h => h.toLowerCase()); + } + // @TODO: blobs should probably also be copied over, optionally + // accounting for the kzg property to backfill blobVersionedHashes + // using the commitment. Or should that be left as an exercise to + // the caller? return result; } /** @@ -69515,7 +67778,11 @@ class JsonRpcApiPollingProvider extends JsonRpcApiProvider { #pollingInterval; constructor(network, options) { super(network, options); - this.#pollingInterval = 4000; + let pollingInterval = this._getOption("pollingInterval"); + if (pollingInterval == null) { + pollingInterval = provider_jsonrpc_defaultOptions.pollingInterval; + } + this.#pollingInterval = pollingInterval; } _getSubscriber(sub) { const subscriber = super._getSubscriber(sub); @@ -69764,6 +68031,7 @@ class BaseWallet extends AbstractSigner { return new BaseWallet(this.#signingKey, provider); } async signTransaction(tx) { + tx = (0,providers_provider/* copyRequest */.VS)(tx); // Replace any Addressable or ENS name with an address const { to, from } = await (0,properties/* resolveProperties */.k)({ to: (tx.to ? (0,checks/* resolveAddress */.tG)(tx.to, this.provider) : undefined), @@ -71940,9 +70208,9 @@ class HDNodeWallet extends BaseWallet { /** * The derivation path of this wallet. * - * Since extended keys do not provider full path details, this + * Since extended keys do not provide full path details, this * may be ``null``, if instantiated from a source that does not - * enocde it. + * encode it. */ path; /** @@ -72370,7 +70638,6 @@ function decryptCrowdsaleJson(json, _password) { } //# sourceMappingURL=json-crowdsale.js.map ;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/wallet/wallet.js -/* provided dependency */ var wallet_console = __webpack_require__(96763); @@ -72439,7 +70706,7 @@ class Wallet extends BaseWallet { if (wallet.address === account.address && wallet.privateKey === account.privateKey) { return wallet; } - wallet_console.log("WARNING: JSON mismatch address/privateKey != mnemonic; fallback onto private key"); + console.log("WARNING: JSON mismatch address/privateKey != mnemonic; fallback onto private key"); } const wallet = new Wallet(account.privateKey); (0,errors/* assertArgument */.MR)(wallet.address === account.address, "address/privateKey mismatch", "json", "[ REDACTED ]"); @@ -72530,9 +70797,11 @@ class BrowserProvider extends JsonRpcApiPollingProvider { * Connnect to the %%ethereum%% provider, optionally forcing the * %%network%%. */ - constructor(ethereum, network) { + constructor(ethereum, network, _options) { + // Copy the options + const options = Object.assign({}, ((_options != null) ? _options : {}), { batchMaxCount: 1 }); (0,errors/* assertArgument */.MR)(ethereum && ethereum.request, "invalid EIP-1193 provider", "ethereum", ethereum); - super(network, { batchMaxCount: 1 }); + super(network, options); this.#request = async (method, params) => { const payload = { method, params }; this.emit("debug", { action: "sendEip1193Request", payload }); @@ -72615,14 +70884,9 @@ class BrowserProvider extends JsonRpcApiPollingProvider { } } //# sourceMappingURL=provider-browser.js.map -// EXTERNAL MODULE: ./src/typechain/index.ts + 8 modules -var typechain = __webpack_require__(67276); // EXTERNAL MODULE: ./src/utils.ts var src_utils = __webpack_require__(67418); -// EXTERNAL MODULE: ./src/multicall.ts -var multicall = __webpack_require__(48486); ;// CONCATENATED MODULE: ./src/providers.ts -/* provided dependency */ var providers_console = __webpack_require__(96763); var __defProp = Object.defineProperty; var __defProps = Object.defineProperties; @@ -72669,8 +70933,6 @@ var __async = (__this, __arguments, generator) => { - - const defaultUserAgent = "Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/115.0"; const providers_fetch = (browser_ponyfill_default()); function getHttpAgent({ @@ -72822,97 +71084,20 @@ const fetchGetUrlFunc = (options = {}) => (req, _signal) => __async(void 0, null body }; }); -const oracleMapper = /* @__PURE__ */ new Map(); -const multicallMapper = /* @__PURE__ */ new Map(); -function getGasOraclePlugin(networkKey, fetchOptions) { - const gasStationApi = (fetchOptions == null ? void 0 : fetchOptions.gasStationApi) || "https://gasstation.polygon.technology/v2"; - return new FetchUrlFeeDataNetworkPlugin(gasStationApi, (fetchFeeData, provider, request) => __async(this, null, function* () { - if (!oracleMapper.has(networkKey)) { - oracleMapper.set(networkKey, typechain/* GasPriceOracle__factory */.Hu.connect(fetchOptions == null ? void 0 : fetchOptions.gasPriceOracle, provider)); - } - if (!multicallMapper.has(networkKey)) { - multicallMapper.set( - networkKey, - typechain/* Multicall__factory */.Q2.connect("0xcA11bde05977b3631167028862bE2a173976CA11", provider) - ); - } - const Oracle = oracleMapper.get(networkKey); - const Multicall2 = multicallMapper.get(networkKey); - const [timestamp, heartbeat, feePerGas, priorityFeePerGas] = yield (0,multicall/* multicall */.C)(Multicall2, [ - { - contract: Oracle, - name: "timestamp" - }, - { - contract: Oracle, - name: "heartbeat" - }, - { - contract: Oracle, - name: "maxFeePerGas" - }, - { - contract: Oracle, - name: "maxPriorityFeePerGas" - } - ]); - const isOutdated = Number(timestamp) <= Date.now() / 1e3 - Number(heartbeat); - if (!isOutdated) { - const maxPriorityFeePerGas = priorityFeePerGas * BigInt(13) / BigInt(10); - const maxFeePerGas = feePerGas * BigInt(2) + maxPriorityFeePerGas; - return { - gasPrice: maxFeePerGas, - maxFeePerGas, - maxPriorityFeePerGas - }; - } - const fetchReq = new FetchRequest(gasStationApi); - fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); - if (src_utils/* isNode */.Ll) { - fetchReq.setHeader("User-Agent", "ethers"); - } - const [ - { - bodyJson: { fast } - }, - { gasPrice } - ] = yield Promise.all([fetchReq.send(), fetchFeeData()]); - return { - gasPrice, - maxFeePerGas: (0,units/* parseUnits */.XS)(`${fast.maxFee}`, 9), - maxPriorityFeePerGas: (0,units/* parseUnits */.XS)(`${fast.maxPriorityFee}`, 9) - }; - })); -} function getProvider(rpcUrl, fetchOptions) { return __async(this, null, function* () { const fetchReq = new FetchRequest(rpcUrl); fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); - const _staticNetwork = yield new JsonRpcProvider(fetchReq).getNetwork(); - const ensPlugin = _staticNetwork.getPlugin("org.ethers.plugins.network.Ens"); - const gasCostPlugin = _staticNetwork.getPlugin("org.ethers.plugins.network.GasCost"); - const gasStationPlugin = _staticNetwork.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin"); - const staticNetwork = new Network(_staticNetwork.name, _staticNetwork.chainId); - if (ensPlugin) { - staticNetwork.attachPlugin(ensPlugin); - } - if (gasCostPlugin) { - staticNetwork.attachPlugin(gasCostPlugin); - } - if (fetchOptions == null ? void 0 : fetchOptions.gasPriceOracle) { - staticNetwork.attachPlugin(getGasOraclePlugin(`${_staticNetwork.chainId}_${rpcUrl}`, fetchOptions)); - } else if (gasStationPlugin) { - staticNetwork.attachPlugin(gasStationPlugin); - } + const staticNetwork = yield new JsonRpcProvider(fetchReq).getNetwork(); const provider = new JsonRpcProvider(fetchReq, staticNetwork, { - staticNetwork + staticNetwork, + pollingInterval: (fetchOptions == null ? void 0 : fetchOptions.pollingInterval) || 1e3 }); - provider.pollingInterval = (fetchOptions == null ? void 0 : fetchOptions.pollingInterval) || 1e3; return provider; }); } function getProviderWithNetId(netId, rpcUrl, config, fetchOptions) { - const { networkName, reverseRecordsContract, gasPriceOracleContract, gasStationApi, pollInterval } = config; + const { networkName, reverseRecordsContract, pollInterval } = config; const hasEns = Boolean(reverseRecordsContract); const fetchReq = new FetchRequest(rpcUrl); fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); @@ -72921,18 +71106,10 @@ function getProviderWithNetId(netId, rpcUrl, config, fetchOptions) { staticNetwork.attachPlugin(new EnsPlugin(null, Number(netId))); } staticNetwork.attachPlugin(new GasCostPlugin()); - if (gasPriceOracleContract) { - staticNetwork.attachPlugin( - getGasOraclePlugin(`${netId}_${rpcUrl}`, { - gasPriceOracle: gasPriceOracleContract, - gasStationApi - }) - ); - } const provider = new JsonRpcProvider(fetchReq, staticNetwork, { - staticNetwork + staticNetwork, + pollingInterval: (fetchOptions == null ? void 0 : fetchOptions.pollingInterval) || pollInterval * 1e3 }); - provider.pollingInterval = (fetchOptions == null ? void 0 : fetchOptions.pollingInterval) || pollInterval * 1e3; return provider; } const populateTransaction = (signer, tx) => __async(void 0, null, function* () { @@ -72972,7 +71149,7 @@ const populateTransaction = (signer, tx) => __async(void 0, null, function* () { } let fetchedNonce = yield provider.getTransactionCount(signer.address, "pending"); if (signer.bumpNonce && signer.nonce && signer.nonce >= fetchedNonce) { - providers_console.log( + console.log( `populateTransaction: bumping nonce from ${fetchedNonce} to ${fetchedNonce + 1} for ${signer.address}` ); fetchedNonce++; @@ -73002,7 +71179,7 @@ const populateTransaction = (signer, tx) => __async(void 0, null, function* () { return gasLimit === BigInt(21e3) ? gasLimit : gasLimit * (BigInt(1e4) + BigInt(signer.gasLimitBump)) / BigInt(1e4); } catch (err) { if (signer.gasFailover) { - providers_console.log("populateTransaction: warning gas estimation failed falling back to 3M gas"); + console.log("populateTransaction: warning gas estimation failed falling back to 3M gas"); return BigInt("3000000"); } throw err; @@ -73111,7 +71288,6 @@ class TornadoBrowserProvider extends BrowserProvider { /* harmony import */ var _networkConfig__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(59499); /* harmony import */ var _providers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(68434); /* harmony import */ var _schemas__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(7613); -/* provided dependency */ var console = __webpack_require__(96763); var __defProp = Object.defineProperty; var __defProps = Object.defineProperties; @@ -73167,8 +71343,7 @@ function isRelayerUpdated(relayerVersion, netId) { const { major, patch, prerelease } = parseSemanticVersion(relayerVersion); const requiredMajor = netId === _networkConfig__WEBPACK_IMPORTED_MODULE_1__/* .NetId */ .zr.MAINNET ? "4" : "5"; const isUpdatedMajor = major === requiredMajor; - if (prerelease) - return false; + if (prerelease) return false; return isUpdatedMajor && (Number(patch) >= 5 || netId !== _networkConfig__WEBPACK_IMPORTED_MODULE_1__/* .NetId */ .zr.MAINNET); } function calculateScore({ stakeBalance, tornadoServiceFee }, minFee = 0.33, maxFee = 0.53) { @@ -73566,7 +71741,7 @@ schemas_ajv.addKeyword({ /* harmony export */ H: () => (/* binding */ getTokenBalances) /* harmony export */ }); /* harmony import */ var ethers__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(98982); -/* harmony import */ var _typechain__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(67276); +/* harmony import */ var _typechain__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21278); /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(67418); /* harmony import */ var _multicall__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(48486); @@ -73661,7 +71836,7 @@ function getTokenBalances(_0) { /***/ }), -/***/ 67276: +/***/ 21278: /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; @@ -73670,7 +71845,6 @@ function getTokenBalances(_0) { __webpack_require__.d(__webpack_exports__, { p2: () => (/* reexport */ ENS__factory), Xc: () => (/* reexport */ ERC20__factory), - Hu: () => (/* reexport */ GasPriceOracle__factory), Q2: () => (/* reexport */ Multicall__factory), Hk: () => (/* reexport */ OffchainOracle__factory), Ld: () => (/* reexport */ OvmGasPriceOracle__factory), @@ -73684,7 +71858,6 @@ __webpack_require__.r(factories_namespaceObject); __webpack_require__.d(factories_namespaceObject, { ENS__factory: () => (ENS__factory), ERC20__factory: () => (ERC20__factory), - GasPriceOracle__factory: () => (GasPriceOracle__factory), Multicall__factory: () => (Multicall__factory), OffchainOracle__factory: () => (OffchainOracle__factory), OvmGasPriceOracle__factory: () => (OvmGasPriceOracle__factory), @@ -74703,208 +72876,6 @@ class ERC20__factory { } ERC20__factory.abi = ERC20_factory_abi; -;// CONCATENATED MODULE: ./src/typechain/factories/GasPriceOracle__factory.ts - - -const GasPriceOracle_factory_abi = [ - { - inputs: [], - stateMutability: "nonpayable", - type: "constructor" - }, - { - inputs: [], - name: "GAS_UNIT", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [ - { - internalType: "uint32", - name: "_derivationThresold", - type: "uint32" - } - ], - name: "changeDerivationThresold", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [ - { - internalType: "uint32", - name: "_gasUnit", - type: "uint32" - } - ], - name: "changeGasUnit", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [ - { - internalType: "uint32", - name: "_heartbeat", - type: "uint32" - } - ], - name: "changeHeartbeat", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [ - { - internalType: "address", - name: "_owner", - type: "address" - } - ], - name: "changeOwnership", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [], - name: "derivationThresold", - outputs: [ - { - internalType: "uint32", - name: "", - type: "uint32" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [], - name: "gasPrice", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [], - name: "heartbeat", - outputs: [ - { - internalType: "uint32", - name: "", - type: "uint32" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [], - name: "maxFeePerGas", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [], - name: "maxPriorityFeePerGas", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [], - name: "owner", - outputs: [ - { - internalType: "address", - name: "", - type: "address" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [], - name: "pastGasPrice", - outputs: [ - { - internalType: "uint32", - name: "", - type: "uint32" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [ - { - internalType: "uint32", - name: "_gasPrice", - type: "uint32" - } - ], - name: "setGasPrice", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [], - name: "timestamp", - outputs: [ - { - internalType: "uint32", - name: "", - type: "uint32" - } - ], - stateMutability: "view", - type: "function" - } -]; -class GasPriceOracle__factory { - static createInterface() { - return new abi_interface/* Interface */.KA(GasPriceOracle_factory_abi); - } - static connect(address, runner) { - return new contract/* Contract */.NZ(address, GasPriceOracle_factory_abi, runner); - } -} -GasPriceOracle__factory.abi = GasPriceOracle_factory_abi; - ;// CONCATENATED MODULE: ./src/typechain/factories/Multicall__factory.ts @@ -76251,7 +74222,6 @@ ReverseRecords__factory.abi = ReverseRecords_factory_abi; - ;// CONCATENATED MODULE: ./src/typechain/index.ts @@ -76264,7 +74234,6 @@ ReverseRecords__factory.abi = ReverseRecords_factory_abi; - /***/ }), /***/ 67418: @@ -76296,7 +74265,6 @@ ReverseRecords__factory.abi = ReverseRecords_factory_abi; /* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(91565); /* harmony import */ var bn_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(39404); /* harmony import */ var bn_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(bn_js__WEBPACK_IMPORTED_MODULE_1__); -/* provided dependency */ var process = __webpack_require__(65606); @@ -76405,7 +74373,6 @@ function substring(str, length = 10) { /* harmony import */ var _tornado_websnark_src_groth16__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(36336); /* harmony import */ var _tornado_websnark_src_groth16__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_tornado_websnark_src_groth16__WEBPACK_IMPORTED_MODULE_1__); /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(67418); -/* provided dependency */ var console = __webpack_require__(96763); var __async = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { @@ -76519,7 +74486,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.crypto = exports.wrapHash = exports.equalsBytes = exports.hexToBytes = exports.bytesToUtf8 = exports.utf8ToBytes = exports.createView = exports.concatBytes = exports.toHex = exports.bytesToHex = exports.assertBytes = exports.assertBool = void 0; +exports.crypto = exports.utf8ToBytes = exports.createView = exports.concatBytes = exports.toHex = exports.bytesToHex = exports.assertBytes = exports.assertBool = void 0; +exports.bytesToUtf8 = bytesToUtf8; +exports.hexToBytes = hexToBytes; +exports.equalsBytes = equalsBytes; +exports.wrapHash = wrapHash; const _assert_1 = __importDefault(__webpack_require__(67557)); const utils_1 = __webpack_require__(99175); const assertBool = _assert_1.default.bool; @@ -76539,12 +74510,10 @@ function bytesToUtf8(data) { } return new TextDecoder().decode(data); } -exports.bytesToUtf8 = bytesToUtf8; function hexToBytes(data) { const sliced = data.startsWith("0x") ? data.substring(2) : data; return (0, utils_1.hexToBytes)(sliced); } -exports.hexToBytes = hexToBytes; // buf.equals(buf2) -> equalsBytes(buf, buf2) function equalsBytes(a, b) { if (a.length !== b.length) { @@ -76557,7 +74526,6 @@ function equalsBytes(a, b) { } return true; } -exports.equalsBytes = equalsBytes; // Internal utils function wrapHash(hash) { return (msg) => { @@ -76565,7 +74533,6 @@ function wrapHash(hash) { return hash(msg); }; } -exports.wrapHash = wrapHash; // TODO(v3): switch away from node crypto, remove this unnecessary variable. exports.crypto = (() => { const webCrypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : undefined; @@ -76582,10 +74549,9 @@ exports.crypto = (() => { /***/ }), /***/ 37007: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ ((module) => { "use strict"; -/* provided dependency */ var console = __webpack_require__(96763); // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -79803,7 +77769,6 @@ module.exports = function isTypedArray(value) { /***/ 31176: /***/ ((module, exports, __webpack_require__) => { -/* provided dependency */ var process = __webpack_require__(65606); var __WEBPACK_AMD_DEFINE_RESULT__;/** * [js-sha3]{@link https://github.com/emn178/js-sha3} * @@ -80564,348 +78529,6 @@ function escapeJsonPtr(str) { } -/***/ }), - -/***/ 69749: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -// A linked list to keep track of recently-used-ness -const Yallist = __webpack_require__(28799) - -const MAX = Symbol('max') -const LENGTH = Symbol('length') -const LENGTH_CALCULATOR = Symbol('lengthCalculator') -const ALLOW_STALE = Symbol('allowStale') -const MAX_AGE = Symbol('maxAge') -const DISPOSE = Symbol('dispose') -const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') -const LRU_LIST = Symbol('lruList') -const CACHE = Symbol('cache') -const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') - -const naiveLength = () => 1 - -// lruList is a yallist where the head is the youngest -// item, and the tail is the oldest. the list contains the Hit -// objects as the entries. -// Each Hit object has a reference to its Yallist.Node. This -// never changes. -// -// cache is a Map (or PseudoMap) that matches the keys to -// the Yallist.Node object. -class LRUCache { - constructor (options) { - if (typeof options === 'number') - options = { max: options } - - if (!options) - options = {} - - if (options.max && (typeof options.max !== 'number' || options.max < 0)) - throw new TypeError('max must be a non-negative number') - // Kind of weird to have a default max of Infinity, but oh well. - const max = this[MAX] = options.max || Infinity - - const lc = options.length || naiveLength - this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc - this[ALLOW_STALE] = options.stale || false - if (options.maxAge && typeof options.maxAge !== 'number') - throw new TypeError('maxAge must be a number') - this[MAX_AGE] = options.maxAge || 0 - this[DISPOSE] = options.dispose - this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false - this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false - this.reset() - } - - // resize the cache when the max changes. - set max (mL) { - if (typeof mL !== 'number' || mL < 0) - throw new TypeError('max must be a non-negative number') - - this[MAX] = mL || Infinity - trim(this) - } - get max () { - return this[MAX] - } - - set allowStale (allowStale) { - this[ALLOW_STALE] = !!allowStale - } - get allowStale () { - return this[ALLOW_STALE] - } - - set maxAge (mA) { - if (typeof mA !== 'number') - throw new TypeError('maxAge must be a non-negative number') - - this[MAX_AGE] = mA - trim(this) - } - get maxAge () { - return this[MAX_AGE] - } - - // resize the cache when the lengthCalculator changes. - set lengthCalculator (lC) { - if (typeof lC !== 'function') - lC = naiveLength - - if (lC !== this[LENGTH_CALCULATOR]) { - this[LENGTH_CALCULATOR] = lC - this[LENGTH] = 0 - this[LRU_LIST].forEach(hit => { - hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) - this[LENGTH] += hit.length - }) - } - trim(this) - } - get lengthCalculator () { return this[LENGTH_CALCULATOR] } - - get length () { return this[LENGTH] } - get itemCount () { return this[LRU_LIST].length } - - rforEach (fn, thisp) { - thisp = thisp || this - for (let walker = this[LRU_LIST].tail; walker !== null;) { - const prev = walker.prev - forEachStep(this, fn, walker, thisp) - walker = prev - } - } - - forEach (fn, thisp) { - thisp = thisp || this - for (let walker = this[LRU_LIST].head; walker !== null;) { - const next = walker.next - forEachStep(this, fn, walker, thisp) - walker = next - } - } - - keys () { - return this[LRU_LIST].toArray().map(k => k.key) - } - - values () { - return this[LRU_LIST].toArray().map(k => k.value) - } - - reset () { - if (this[DISPOSE] && - this[LRU_LIST] && - this[LRU_LIST].length) { - this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) - } - - this[CACHE] = new Map() // hash of items by key - this[LRU_LIST] = new Yallist() // list of items in order of use recency - this[LENGTH] = 0 // length of items in the list - } - - dump () { - return this[LRU_LIST].map(hit => - isStale(this, hit) ? false : { - k: hit.key, - v: hit.value, - e: hit.now + (hit.maxAge || 0) - }).toArray().filter(h => h) - } - - dumpLru () { - return this[LRU_LIST] - } - - set (key, value, maxAge) { - maxAge = maxAge || this[MAX_AGE] - - if (maxAge && typeof maxAge !== 'number') - throw new TypeError('maxAge must be a number') - - const now = maxAge ? Date.now() : 0 - const len = this[LENGTH_CALCULATOR](value, key) - - if (this[CACHE].has(key)) { - if (len > this[MAX]) { - del(this, this[CACHE].get(key)) - return false - } - - const node = this[CACHE].get(key) - const item = node.value - - // dispose of the old one before overwriting - // split out into 2 ifs for better coverage tracking - if (this[DISPOSE]) { - if (!this[NO_DISPOSE_ON_SET]) - this[DISPOSE](key, item.value) - } - - item.now = now - item.maxAge = maxAge - item.value = value - this[LENGTH] += len - item.length - item.length = len - this.get(key) - trim(this) - return true - } - - const hit = new Entry(key, value, len, now, maxAge) - - // oversized objects fall out of cache automatically. - if (hit.length > this[MAX]) { - if (this[DISPOSE]) - this[DISPOSE](key, value) - - return false - } - - this[LENGTH] += hit.length - this[LRU_LIST].unshift(hit) - this[CACHE].set(key, this[LRU_LIST].head) - trim(this) - return true - } - - has (key) { - if (!this[CACHE].has(key)) return false - const hit = this[CACHE].get(key).value - return !isStale(this, hit) - } - - get (key) { - return get(this, key, true) - } - - peek (key) { - return get(this, key, false) - } - - pop () { - const node = this[LRU_LIST].tail - if (!node) - return null - - del(this, node) - return node.value - } - - del (key) { - del(this, this[CACHE].get(key)) - } - - load (arr) { - // reset the cache - this.reset() - - const now = Date.now() - // A previous serialized cache has the most recent items first - for (let l = arr.length - 1; l >= 0; l--) { - const hit = arr[l] - const expiresAt = hit.e || 0 - if (expiresAt === 0) - // the item was created without expiration in a non aged cache - this.set(hit.k, hit.v) - else { - const maxAge = expiresAt - now - // dont add already expired items - if (maxAge > 0) { - this.set(hit.k, hit.v, maxAge) - } - } - } - } - - prune () { - this[CACHE].forEach((value, key) => get(this, key, false)) - } -} - -const get = (self, key, doUse) => { - const node = self[CACHE].get(key) - if (node) { - const hit = node.value - if (isStale(self, hit)) { - del(self, node) - if (!self[ALLOW_STALE]) - return undefined - } else { - if (doUse) { - if (self[UPDATE_AGE_ON_GET]) - node.value.now = Date.now() - self[LRU_LIST].unshiftNode(node) - } - } - return hit.value - } -} - -const isStale = (self, hit) => { - if (!hit || (!hit.maxAge && !self[MAX_AGE])) - return false - - const diff = Date.now() - hit.now - return hit.maxAge ? diff > hit.maxAge - : self[MAX_AGE] && (diff > self[MAX_AGE]) -} - -const trim = self => { - if (self[LENGTH] > self[MAX]) { - for (let walker = self[LRU_LIST].tail; - self[LENGTH] > self[MAX] && walker !== null;) { - // We know that we're about to delete this one, and also - // what the next least recently used key will be, so just - // go ahead and set it now. - const prev = walker.prev - del(self, walker) - walker = prev - } - } -} - -const del = (self, node) => { - if (node) { - const hit = node.value - if (self[DISPOSE]) - self[DISPOSE](hit.key, hit.value) - - self[LENGTH] -= hit.length - self[CACHE].delete(hit.key) - self[LRU_LIST].removeNode(node) - } -} - -class Entry { - constructor (key, value, length, now, maxAge) { - this.key = key - this.value = value - this.length = length - this.now = now - this.maxAge = maxAge || 0 - } -} - -const forEachStep = (self, fn, node, thisp) => { - let hit = node.value - if (isStale(self, hit)) { - del(self, node) - if (!self[ALLOW_STALE]) - hit = undefined - } - if (hit) - fn.call(thisp, hit.value, hit.key, self) -} - -module.exports = LRUCache - - /***/ }), /***/ 88276: @@ -81170,7 +78793,6 @@ module.exports = HashBase "use strict"; /* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; -/* provided dependency */ var process = __webpack_require__(65606); Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InvalidStatusCodeError = exports.InvalidCertError = void 0; @@ -85080,7 +82702,7 @@ var y = d * 365.25; * @api public */ -module.exports = function(val, options) { +module.exports = function (val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { @@ -85646,62 +83268,6 @@ module.exports = function getPolyfill() { }; -/***/ }), - -/***/ 51072: -/***/ ((__unused_webpack_module, exports) => { - -exports.endianness = function () { return 'LE' }; - -exports.hostname = function () { - if (typeof location !== 'undefined') { - return location.hostname - } - else return ''; -}; - -exports.loadavg = function () { return [] }; - -exports.uptime = function () { return 0 }; - -exports.freemem = function () { - return Number.MAX_VALUE; -}; - -exports.totalmem = function () { - return Number.MAX_VALUE; -}; - -exports.cpus = function () { return [] }; - -exports.type = function () { return 'Browser' }; - -exports.release = function () { - if (typeof navigator !== 'undefined') { - return navigator.appVersion; - } - return ''; -}; - -exports.networkInterfaces -= exports.getNetworkInterfaces -= function () { return {} }; - -exports.arch = function () { return 'javascript' }; - -exports.platform = function () { return 'browser' }; - -exports.tmpdir = exports.tmpDir = function () { - return '/tmp'; -}; - -exports.EOL = '\n'; - -exports.homedir = function () { - return '/' -}; - - /***/ }), /***/ 9805: @@ -92019,7 +89585,6 @@ module.exports = function (password, salt, iterations, keylen, digest, callback) /***/ 2455: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/* provided dependency */ var process = __webpack_require__(65606); var defaultEncoding /* istanbul ignore next */ if (__webpack_require__.g.process && __webpack_require__.g.process.browser) { @@ -92429,10 +89994,9 @@ module.exports = [ /***/ }), /***/ 33225: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ ((module) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(65606); if (typeof process === 'undefined' || @@ -92480,197 +90044,6 @@ function nextTick(fn, arg1, arg2, arg3) { -/***/ }), - -/***/ 65606: -/***/ ((module) => { - -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - - /***/ }), /***/ 97168: @@ -96415,7 +93788,6 @@ module.exports = function xor (a, b) { /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(65606); // limit of Crypto.getRandomValues() @@ -96474,7 +93846,6 @@ function randomBytes (size, cb) { /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(65606); function oldBrowser () { @@ -96726,7 +94097,6 @@ module.exports.F = codes; /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(65606); // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -96904,7 +94274,6 @@ PassThrough.prototype._transform = function (chunk, encoding, cb) { /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(65606); // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -98136,7 +95505,6 @@ function done(stream, er, data) { /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(65606); // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -98785,7 +96153,6 @@ Writable.prototype._destroy = function (err, cb) { /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(65606); var _Object$setPrototypeO; @@ -99160,10 +96527,9 @@ module.exports = /*#__PURE__*/function () { /***/ }), /***/ 75896: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ ((module) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(65606); // undocumented cb() API, needed for core, not for public API @@ -100009,6 +97375,8 @@ const Range = __webpack_require__(78311) /***/ 78311: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { +const SPACE_CHARACTERS = /\s+/g + // hoisted class for cyclic dependency class Range { constructor (range, options) { @@ -100029,7 +97397,7 @@ class Range { // just put it in the set and return this.raw = range.value this.set = [[range]] - this.format() + this.formatted = undefined return this } @@ -100040,10 +97408,7 @@ class Range { // First reduce all whitespace as much as possible so we do not have to rely // on potentially slow regexes like \s*. This is then stored and used for // future error messages as well. - this.raw = range - .trim() - .split(/\s+/) - .join(' ') + this.raw = range.trim().replace(SPACE_CHARACTERS, ' ') // First, split on || this.set = this.raw @@ -100077,14 +97442,29 @@ class Range { } } - this.format() + this.formatted = undefined + } + + get range () { + if (this.formatted === undefined) { + this.formatted = '' + for (let i = 0; i < this.set.length; i++) { + if (i > 0) { + this.formatted += '||' + } + const comps = this.set[i] + for (let k = 0; k < comps.length; k++) { + if (k > 0) { + this.formatted += ' ' + } + this.formatted += comps[k].toString().trim() + } + } + } + return this.formatted } format () { - this.range = this.set - .map((comps) => comps.join(' ').trim()) - .join('||') - .trim() return this.range } @@ -100209,8 +97589,8 @@ class Range { module.exports = Range -const LRU = __webpack_require__(69749) -const cache = new LRU({ max: 1000 }) +const LRU = __webpack_require__(68794) +const cache = new LRU() const parseOptions = __webpack_require__(98587) const Comparator = __webpack_require__(93904) @@ -100481,9 +97861,10 @@ const replaceGTE0 = (comp, options) => { // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 +// TODO build? const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) => { + to, tM, tm, tp, tpr) => { if (isX(fM)) { from = '' } else if (isX(fm)) { @@ -100715,7 +98096,7 @@ class SemVer { do { const a = this.build[i] const b = other.build[i] - debug('prerelease compare', i, a, b) + debug('build compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { @@ -101459,10 +98840,8 @@ module.exports = { /***/ }), /***/ 57272: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ ((module) => { -/* provided dependency */ var process = __webpack_require__(65606); -/* provided dependency */ var console = __webpack_require__(96763); const debug = ( typeof process === 'object' && process.env && @@ -101504,6 +98883,53 @@ module.exports = { } +/***/ }), + +/***/ 68794: +/***/ ((module) => { + +class LRUCache { + constructor () { + this.max = 1000 + this.map = new Map() + } + + get (key) { + const value = this.map.get(key) + if (value === undefined) { + return undefined + } else { + // Remove the key from the map and add it to the end + this.map.delete(key) + this.map.set(key, value) + return value + } + } + + delete (key) { + return this.map.delete(key) + } + + set (key, value) { + const deleted = this.delete(key) + + if (!deleted && value !== undefined) { + // If cache is full, delete the least recently used item + if (this.map.size >= this.max) { + const firstKey = this.map.keys().next().value + this.delete(firstKey) + } + + this.map.set(key, value) + } + + return this + } +} + +module.exports = LRUCache + + /***/ }), /***/ 98587: @@ -103544,7 +100970,6 @@ xhr = null // Help gc /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; -/* provided dependency */ var process = __webpack_require__(65606); var capability = __webpack_require__(6688) var inherits = __webpack_require__(56698) var response = __webpack_require__(6917) @@ -103904,7 +101329,6 @@ var unsafeHeaders = [ /***/ 6917: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { -/* provided dependency */ var process = __webpack_require__(65606); /* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; var capability = __webpack_require__(6688) var inherits = __webpack_require__(56698) @@ -104422,95 +101846,6 @@ function simpleEnd(buf) { return buf && buf.length ? this.write(buf) : ''; } -/***/ }), - -/***/ 76386: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; -// Written in 2014-2016 by Dmitry Chestnykh and Devi Mandiri. -// Public domain. -(function(root, f) { - 'use strict'; - if ( true && module.exports) module.exports = f(); - else if (root.nacl) root.nacl.util = f(); - else { - root.nacl = {}; - root.nacl.util = f(); - } -}(this, function() { - 'use strict'; - - var util = {}; - - function validateBase64(s) { - if (!(/^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(s))) { - throw new TypeError('invalid encoding'); - } - } - - util.decodeUTF8 = function(s) { - if (typeof s !== 'string') throw new TypeError('expected string'); - var i, d = unescape(encodeURIComponent(s)), b = new Uint8Array(d.length); - for (i = 0; i < d.length; i++) b[i] = d.charCodeAt(i); - return b; - }; - - util.encodeUTF8 = function(arr) { - var i, s = []; - for (i = 0; i < arr.length; i++) s.push(String.fromCharCode(arr[i])); - return decodeURIComponent(escape(s.join(''))); - }; - - if (typeof atob === 'undefined') { - // Node.js - - if (typeof Buffer.from !== 'undefined') { - // Node v6 and later - util.encodeBase64 = function (arr) { // v6 and later - return Buffer.from(arr).toString('base64'); - }; - - util.decodeBase64 = function (s) { - validateBase64(s); - return new Uint8Array(Array.prototype.slice.call(Buffer.from(s, 'base64'), 0)); - }; - - } else { - // Node earlier than v6 - util.encodeBase64 = function (arr) { // v6 and later - return (new Buffer(arr)).toString('base64'); - }; - - util.decodeBase64 = function(s) { - validateBase64(s); - return new Uint8Array(Array.prototype.slice.call(new Buffer(s, 'base64'), 0)); - }; - } - - } else { - // Browsers - - util.encodeBase64 = function(arr) { - var i, s = [], len = arr.length; - for (i = 0; i < len; i++) s.push(String.fromCharCode(arr[i])); - return btoa(s.join('')); - }; - - util.decodeBase64 = function(s) { - validateBase64(s); - var i, d = atob(s), b = new Uint8Array(d.length); - for (i = 0; i < d.length; i++) b[i] = d.charCodeAt(i); - return b; - }; - - } - - return util; - -})); - - /***/ }), /***/ 88947: @@ -106909,1461 +104244,11 @@ nacl.setPRNG = function(fn) { })( true && module.exports ? module.exports : (self.nacl = self.nacl || {})); -/***/ }), - -/***/ 46579: -/***/ (function(__unused_webpack_module, exports) { - -/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */ -(function (global, factory) { - true ? factory(exports) : - 0; -}(this, (function (exports) { 'use strict'; - -function merge() { - for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) { - sets[_key] = arguments[_key]; - } - - if (sets.length > 1) { - sets[0] = sets[0].slice(0, -1); - var xl = sets.length - 1; - for (var x = 1; x < xl; ++x) { - sets[x] = sets[x].slice(1, -1); - } - sets[xl] = sets[xl].slice(1); - return sets.join(''); - } else { - return sets[0]; - } -} -function subexp(str) { - return "(?:" + str + ")"; -} -function typeOf(o) { - return o === undefined ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase(); -} -function toUpperCase(str) { - return str.toUpperCase(); -} -function toArray(obj) { - return obj !== undefined && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : []; -} -function assign(target, source) { - var obj = target; - if (source) { - for (var key in source) { - obj[key] = source[key]; - } - } - return obj; -} - -function buildExps(isIRI) { - var ALPHA$$ = "[A-Za-z]", - CR$ = "[\\x0D]", - DIGIT$$ = "[0-9]", - DQUOTE$$ = "[\\x22]", - HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"), - //case-insensitive - LF$$ = "[\\x0A]", - SP$$ = "[\\x20]", - PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)), - //expanded - GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", - SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", - RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$), - UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", - //subset, excludes bidi control characters - IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]", - //subset - UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$), - SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"), - USERINFO$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"), - DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$), - DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$), - //relaxed parsing rules - IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), - H16$ = subexp(HEXDIG$$ + "{1,4}"), - LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), - IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), - // 6( h16 ":" ) ls32 - IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), - // "::" 5( h16 ":" ) ls32 - IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), - //[ h16 ] "::" 4( h16 ":" ) ls32 - IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), - //[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 - IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), - //[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 - IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), - //[ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 - IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), - //[ *4( h16 ":" ) h16 ] "::" ls32 - IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), - //[ *5( h16 ":" ) h16 ] "::" h16 - IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), - //[ *6( h16 ":" ) h16 ] "::" - IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")), - ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"), - //RFC 6874 - IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$), - //RFC 6874 - IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + ZONEID$), - //RFC 6874, with relaxed parsing rules - IPVFUTURE$ = subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"), - IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"), - //RFC 6874 - REG_NAME$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"), - HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")" + "|" + REG_NAME$), - PORT$ = subexp(DIGIT$$ + "*"), - AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"), - PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")), - SEGMENT$ = subexp(PCHAR$ + "*"), - SEGMENT_NZ$ = subexp(PCHAR$ + "+"), - SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"), - PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"), - PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"), - //simplified - PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), - //simplified - PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), - //simplified - PATH_EMPTY$ = "(?!" + PCHAR$ + ")", - PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), - QUERY$ = subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"), - FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"), - HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), - URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), - RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$), - RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), - URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$), - ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"), - GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", - RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", - ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$", - SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", - AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$"; - return { - NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"), - NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), - NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), - NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), - NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), - NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"), - NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"), - ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"), - UNRESERVED: new RegExp(UNRESERVED$$, "g"), - OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"), - PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"), - IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"), - IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules - }; -} -var URI_PROTOCOL = buildExps(false); - -var IRI_PROTOCOL = buildExps(true); - -var slicedToArray = function () { - function sliceIterator(arr, i) { - var _arr = []; - var _n = true; - var _d = false; - var _e = undefined; - - try { - for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); - - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"]) _i["return"](); - } finally { - if (_d) throw _e; - } - } - - return _arr; - } - - return function (arr, i) { - if (Array.isArray(arr)) { - return arr; - } else if (Symbol.iterator in Object(arr)) { - return sliceIterator(arr, i); - } else { - throw new TypeError("Invalid attempt to destructure non-iterable instance"); - } - }; -}(); - - - - - - - - - - - - - -var toConsumableArray = function (arr) { - if (Array.isArray(arr)) { - for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; - - return arr2; - } else { - return Array.from(arr); - } -}; - -/** Highest positive signed 32-bit float value */ - -var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 - -/** Bootstring parameters */ -var base = 36; -var tMin = 1; -var tMax = 26; -var skew = 38; -var damp = 700; -var initialBias = 72; -var initialN = 128; // 0x80 -var delimiter = '-'; // '\x2D' - -/** Regular expressions */ -var regexPunycode = /^xn--/; -var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars -var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators - -/** Error messages */ -var errors = { - 'overflow': 'Overflow: input needs wider integers to process', - 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', - 'invalid-input': 'Invalid input' -}; - -/** Convenience shortcuts */ -var baseMinusTMin = base - tMin; -var floor = Math.floor; -var stringFromCharCode = String.fromCharCode; - -/*--------------------------------------------------------------------------*/ - -/** - * A generic error utility function. - * @private - * @param {String} type The error type. - * @returns {Error} Throws a `RangeError` with the applicable error message. - */ -function error$1(type) { - throw new RangeError(errors[type]); -} - -/** - * A generic `Array#map` utility function. - * @private - * @param {Array} array The array to iterate over. - * @param {Function} callback The function that gets called for every array - * item. - * @returns {Array} A new array of values returned by the callback function. - */ -function map(array, fn) { - var result = []; - var length = array.length; - while (length--) { - result[length] = fn(array[length]); - } - return result; -} - -/** - * A simple `Array#map`-like wrapper to work with domain name strings or email - * addresses. - * @private - * @param {String} domain The domain name or email address. - * @param {Function} callback The function that gets called for every - * character. - * @returns {Array} A new string of characters returned by the callback - * function. - */ -function mapDomain(string, fn) { - var parts = string.split('@'); - var result = ''; - if (parts.length > 1) { - // In email addresses, only the domain name should be punycoded. Leave - // the local part (i.e. everything up to `@`) intact. - result = parts[0] + '@'; - string = parts[1]; - } - // Avoid `split(regex)` for IE8 compatibility. See #17. - string = string.replace(regexSeparators, '\x2E'); - var labels = string.split('.'); - var encoded = map(labels, fn).join('.'); - return result + encoded; -} - -/** - * Creates an array containing the numeric code points of each Unicode - * character in the string. While JavaScript uses UCS-2 internally, - * this function will convert a pair of surrogate halves (each of which - * UCS-2 exposes as separate characters) into a single code point, - * matching UTF-16. - * @see `punycode.ucs2.encode` - * @see - * @memberOf punycode.ucs2 - * @name decode - * @param {String} string The Unicode input string (UCS-2). - * @returns {Array} The new array of code points. - */ -function ucs2decode(string) { - var output = []; - var counter = 0; - var length = string.length; - while (counter < length) { - var value = string.charCodeAt(counter++); - if (value >= 0xD800 && value <= 0xDBFF && counter < length) { - // It's a high surrogate, and there is a next character. - var extra = string.charCodeAt(counter++); - if ((extra & 0xFC00) == 0xDC00) { - // Low surrogate. - output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); - } else { - // It's an unmatched surrogate; only append this code unit, in case the - // next code unit is the high surrogate of a surrogate pair. - output.push(value); - counter--; - } - } else { - output.push(value); - } - } - return output; -} - -/** - * Creates a string based on an array of numeric code points. - * @see `punycode.ucs2.decode` - * @memberOf punycode.ucs2 - * @name encode - * @param {Array} codePoints The array of numeric code points. - * @returns {String} The new Unicode string (UCS-2). - */ -var ucs2encode = function ucs2encode(array) { - return String.fromCodePoint.apply(String, toConsumableArray(array)); -}; - -/** - * Converts a basic code point into a digit/integer. - * @see `digitToBasic()` - * @private - * @param {Number} codePoint The basic numeric code point value. - * @returns {Number} The numeric value of a basic code point (for use in - * representing integers) in the range `0` to `base - 1`, or `base` if - * the code point does not represent a value. - */ -var basicToDigit = function basicToDigit(codePoint) { - if (codePoint - 0x30 < 0x0A) { - return codePoint - 0x16; - } - if (codePoint - 0x41 < 0x1A) { - return codePoint - 0x41; - } - if (codePoint - 0x61 < 0x1A) { - return codePoint - 0x61; - } - return base; -}; - -/** - * Converts a digit/integer into a basic code point. - * @see `basicToDigit()` - * @private - * @param {Number} digit The numeric value of a basic code point. - * @returns {Number} The basic code point whose value (when used for - * representing integers) is `digit`, which needs to be in the range - * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is - * used; else, the lowercase form is used. The behavior is undefined - * if `flag` is non-zero and `digit` has no uppercase form. - */ -var digitToBasic = function digitToBasic(digit, flag) { - // 0..25 map to ASCII a..z or A..Z - // 26..35 map to ASCII 0..9 - return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); -}; - -/** - * Bias adaptation function as per section 3.4 of RFC 3492. - * https://tools.ietf.org/html/rfc3492#section-3.4 - * @private - */ -var adapt = function adapt(delta, numPoints, firstTime) { - var k = 0; - delta = firstTime ? floor(delta / damp) : delta >> 1; - delta += floor(delta / numPoints); - for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) { - delta = floor(delta / baseMinusTMin); - } - return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); -}; - -/** - * Converts a Punycode string of ASCII-only symbols to a string of Unicode - * symbols. - * @memberOf punycode - * @param {String} input The Punycode string of ASCII-only symbols. - * @returns {String} The resulting string of Unicode symbols. - */ -var decode = function decode(input) { - // Don't use UCS-2. - var output = []; - var inputLength = input.length; - var i = 0; - var n = initialN; - var bias = initialBias; - - // Handle the basic code points: let `basic` be the number of input code - // points before the last delimiter, or `0` if there is none, then copy - // the first basic code points to the output. - - var basic = input.lastIndexOf(delimiter); - if (basic < 0) { - basic = 0; - } - - for (var j = 0; j < basic; ++j) { - // if it's not a basic code point - if (input.charCodeAt(j) >= 0x80) { - error$1('not-basic'); - } - output.push(input.charCodeAt(j)); - } - - // Main decoding loop: start just after the last delimiter if any basic code - // points were copied; start at the beginning otherwise. - - for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{ - - // `index` is the index of the next character to be consumed. - // Decode a generalized variable-length integer into `delta`, - // which gets added to `i`. The overflow checking is easier - // if we increase `i` as we go, then subtract off its starting - // value at the end to obtain `delta`. - var oldi = i; - for (var w = 1, k = base;; /* no condition */k += base) { - - if (index >= inputLength) { - error$1('invalid-input'); - } - - var digit = basicToDigit(input.charCodeAt(index++)); - - if (digit >= base || digit > floor((maxInt - i) / w)) { - error$1('overflow'); - } - - i += digit * w; - var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; - - if (digit < t) { - break; - } - - var baseMinusT = base - t; - if (w > floor(maxInt / baseMinusT)) { - error$1('overflow'); - } - - w *= baseMinusT; - } - - var out = output.length + 1; - bias = adapt(i - oldi, out, oldi == 0); - - // `i` was supposed to wrap around from `out` to `0`, - // incrementing `n` each time, so we'll fix that now: - if (floor(i / out) > maxInt - n) { - error$1('overflow'); - } - - n += floor(i / out); - i %= out; - - // Insert `n` at position `i` of the output. - output.splice(i++, 0, n); - } - - return String.fromCodePoint.apply(String, output); -}; - -/** - * Converts a string of Unicode symbols (e.g. a domain name label) to a - * Punycode string of ASCII-only symbols. - * @memberOf punycode - * @param {String} input The string of Unicode symbols. - * @returns {String} The resulting Punycode string of ASCII-only symbols. - */ -var encode = function encode(input) { - var output = []; - - // Convert the input in UCS-2 to an array of Unicode code points. - input = ucs2decode(input); - - // Cache the length. - var inputLength = input.length; - - // Initialize the state. - var n = initialN; - var delta = 0; - var bias = initialBias; - - // Handle the basic code points. - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var _currentValue2 = _step.value; - - if (_currentValue2 < 0x80) { - output.push(stringFromCharCode(_currentValue2)); - } - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - - var basicLength = output.length; - var handledCPCount = basicLength; - - // `handledCPCount` is the number of code points that have been handled; - // `basicLength` is the number of basic code points. - - // Finish the basic string with a delimiter unless it's empty. - if (basicLength) { - output.push(delimiter); - } - - // Main encoding loop: - while (handledCPCount < inputLength) { - - // All non-basic code points < n have been handled already. Find the next - // larger one: - var m = maxInt; - var _iteratorNormalCompletion2 = true; - var _didIteratorError2 = false; - var _iteratorError2 = undefined; - - try { - for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { - var currentValue = _step2.value; - - if (currentValue >= n && currentValue < m) { - m = currentValue; - } - } - - // Increase `delta` enough to advance the decoder's state to , - // but guard against overflow. - } catch (err) { - _didIteratorError2 = true; - _iteratorError2 = err; - } finally { - try { - if (!_iteratorNormalCompletion2 && _iterator2.return) { - _iterator2.return(); - } - } finally { - if (_didIteratorError2) { - throw _iteratorError2; - } - } - } - - var handledCPCountPlusOne = handledCPCount + 1; - if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { - error$1('overflow'); - } - - delta += (m - n) * handledCPCountPlusOne; - n = m; - - var _iteratorNormalCompletion3 = true; - var _didIteratorError3 = false; - var _iteratorError3 = undefined; - - try { - for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { - var _currentValue = _step3.value; - - if (_currentValue < n && ++delta > maxInt) { - error$1('overflow'); - } - if (_currentValue == n) { - // Represent delta as a generalized variable-length integer. - var q = delta; - for (var k = base;; /* no condition */k += base) { - var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; - if (q < t) { - break; - } - var qMinusT = q - t; - var baseMinusT = base - t; - output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); - q = floor(qMinusT / baseMinusT); - } - - output.push(stringFromCharCode(digitToBasic(q, 0))); - bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); - delta = 0; - ++handledCPCount; - } - } - } catch (err) { - _didIteratorError3 = true; - _iteratorError3 = err; - } finally { - try { - if (!_iteratorNormalCompletion3 && _iterator3.return) { - _iterator3.return(); - } - } finally { - if (_didIteratorError3) { - throw _iteratorError3; - } - } - } - - ++delta; - ++n; - } - return output.join(''); -}; - -/** - * Converts a Punycode string representing a domain name or an email address - * to Unicode. Only the Punycoded parts of the input will be converted, i.e. - * it doesn't matter if you call it on a string that has already been - * converted to Unicode. - * @memberOf punycode - * @param {String} input The Punycoded domain name or email address to - * convert to Unicode. - * @returns {String} The Unicode representation of the given Punycode - * string. - */ -var toUnicode = function toUnicode(input) { - return mapDomain(input, function (string) { - return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; - }); -}; - -/** - * Converts a Unicode string representing a domain name or an email address to - * Punycode. Only the non-ASCII parts of the domain name will be converted, - * i.e. it doesn't matter if you call it with a domain that's already in - * ASCII. - * @memberOf punycode - * @param {String} input The domain name or email address to convert, as a - * Unicode string. - * @returns {String} The Punycode representation of the given domain name or - * email address. - */ -var toASCII = function toASCII(input) { - return mapDomain(input, function (string) { - return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; - }); -}; - -/*--------------------------------------------------------------------------*/ - -/** Define the public API */ -var punycode = { - /** - * A string representing the current Punycode.js version number. - * @memberOf punycode - * @type String - */ - 'version': '2.1.0', - /** - * An object of methods to convert from JavaScript's internal character - * representation (UCS-2) to Unicode code points, and back. - * @see - * @memberOf punycode - * @type Object - */ - 'ucs2': { - 'decode': ucs2decode, - 'encode': ucs2encode - }, - 'decode': decode, - 'encode': encode, - 'toASCII': toASCII, - 'toUnicode': toUnicode -}; - -/** - * URI.js - * - * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript. - * @author Gary Court - * @see http://github.com/garycourt/uri-js - */ -/** - * Copyright 2011 Gary Court. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are - * permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of Gary Court. - */ -var SCHEMES = {}; -function pctEncChar(chr) { - var c = chr.charCodeAt(0); - var e = void 0; - if (c < 16) e = "%0" + c.toString(16).toUpperCase();else if (c < 128) e = "%" + c.toString(16).toUpperCase();else if (c < 2048) e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();else e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase(); - return e; -} -function pctDecChars(str) { - var newStr = ""; - var i = 0; - var il = str.length; - while (i < il) { - var c = parseInt(str.substr(i + 1, 2), 16); - if (c < 128) { - newStr += String.fromCharCode(c); - i += 3; - } else if (c >= 194 && c < 224) { - if (il - i >= 6) { - var c2 = parseInt(str.substr(i + 4, 2), 16); - newStr += String.fromCharCode((c & 31) << 6 | c2 & 63); - } else { - newStr += str.substr(i, 6); - } - i += 6; - } else if (c >= 224) { - if (il - i >= 9) { - var _c = parseInt(str.substr(i + 4, 2), 16); - var c3 = parseInt(str.substr(i + 7, 2), 16); - newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63); - } else { - newStr += str.substr(i, 9); - } - i += 9; - } else { - newStr += str.substr(i, 3); - i += 3; - } - } - return newStr; -} -function _normalizeComponentEncoding(components, protocol) { - function decodeUnreserved(str) { - var decStr = pctDecChars(str); - return !decStr.match(protocol.UNRESERVED) ? str : decStr; - } - if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, ""); - if (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - if (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - if (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - if (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - if (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - return components; -} - -function _stripLeadingZeros(str) { - return str.replace(/^0*(.*)/, "$1") || "0"; -} -function _normalizeIPv4(host, protocol) { - var matches = host.match(protocol.IPV4ADDRESS) || []; - - var _matches = slicedToArray(matches, 2), - address = _matches[1]; - - if (address) { - return address.split(".").map(_stripLeadingZeros).join("."); - } else { - return host; - } -} -function _normalizeIPv6(host, protocol) { - var matches = host.match(protocol.IPV6ADDRESS) || []; - - var _matches2 = slicedToArray(matches, 3), - address = _matches2[1], - zone = _matches2[2]; - - if (address) { - var _address$toLowerCase$ = address.toLowerCase().split('::').reverse(), - _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2), - last = _address$toLowerCase$2[0], - first = _address$toLowerCase$2[1]; - - var firstFields = first ? first.split(":").map(_stripLeadingZeros) : []; - var lastFields = last.split(":").map(_stripLeadingZeros); - var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]); - var fieldCount = isLastFieldIPv4Address ? 7 : 8; - var lastFieldsStart = lastFields.length - fieldCount; - var fields = Array(fieldCount); - for (var x = 0; x < fieldCount; ++x) { - fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || ''; - } - if (isLastFieldIPv4Address) { - fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol); - } - var allZeroFields = fields.reduce(function (acc, field, index) { - if (!field || field === "0") { - var lastLongest = acc[acc.length - 1]; - if (lastLongest && lastLongest.index + lastLongest.length === index) { - lastLongest.length++; - } else { - acc.push({ index: index, length: 1 }); - } - } - return acc; - }, []); - var longestZeroFields = allZeroFields.sort(function (a, b) { - return b.length - a.length; - })[0]; - var newHost = void 0; - if (longestZeroFields && longestZeroFields.length > 1) { - var newFirst = fields.slice(0, longestZeroFields.index); - var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length); - newHost = newFirst.join(":") + "::" + newLast.join(":"); - } else { - newHost = fields.join(":"); - } - if (zone) { - newHost += "%" + zone; - } - return newHost; - } else { - return host; - } -} -var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i; -var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === undefined; -function parse(uriString) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - var components = {}; - var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; - if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString; - var matches = uriString.match(URI_PARSE); - if (matches) { - if (NO_MATCH_IS_UNDEFINED) { - //store each component - components.scheme = matches[1]; - components.userinfo = matches[3]; - components.host = matches[4]; - components.port = parseInt(matches[5], 10); - components.path = matches[6] || ""; - components.query = matches[7]; - components.fragment = matches[8]; - //fix port number - if (isNaN(components.port)) { - components.port = matches[5]; - } - } else { - //IE FIX for improper RegExp matching - //store each component - components.scheme = matches[1] || undefined; - components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : undefined; - components.host = uriString.indexOf("//") !== -1 ? matches[4] : undefined; - components.port = parseInt(matches[5], 10); - components.path = matches[6] || ""; - components.query = uriString.indexOf("?") !== -1 ? matches[7] : undefined; - components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : undefined; - //fix port number - if (isNaN(components.port)) { - components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined; - } - } - if (components.host) { - //normalize IP hosts - components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol); - } - //determine reference type - if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) { - components.reference = "same-document"; - } else if (components.scheme === undefined) { - components.reference = "relative"; - } else if (components.fragment === undefined) { - components.reference = "absolute"; - } else { - components.reference = "uri"; - } - //check for reference errors - if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) { - components.error = components.error || "URI is not a " + options.reference + " reference."; - } - //find scheme handler - var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; - //check if scheme can't handle IRIs - if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { - //if host component is a domain name - if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) { - //convert Unicode IDN -> ASCII IDN - try { - components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()); - } catch (e) { - components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e; - } - } - //convert IRI -> URI - _normalizeComponentEncoding(components, URI_PROTOCOL); - } else { - //normalize encodings - _normalizeComponentEncoding(components, protocol); - } - //perform scheme specific parsing - if (schemeHandler && schemeHandler.parse) { - schemeHandler.parse(components, options); - } - } else { - components.error = components.error || "URI can not be parsed."; - } - return components; -} - -function _recomposeAuthority(components, options) { - var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; - var uriTokens = []; - if (components.userinfo !== undefined) { - uriTokens.push(components.userinfo); - uriTokens.push("@"); - } - if (components.host !== undefined) { - //normalize IP hosts, add brackets and escape zone separator for IPv6 - uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function (_, $1, $2) { - return "[" + $1 + ($2 ? "%25" + $2 : "") + "]"; - })); - } - if (typeof components.port === "number" || typeof components.port === "string") { - uriTokens.push(":"); - uriTokens.push(String(components.port)); - } - return uriTokens.length ? uriTokens.join("") : undefined; -} - -var RDS1 = /^\.\.?\//; -var RDS2 = /^\/\.(\/|$)/; -var RDS3 = /^\/\.\.(\/|$)/; -var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/; -function removeDotSegments(input) { - var output = []; - while (input.length) { - if (input.match(RDS1)) { - input = input.replace(RDS1, ""); - } else if (input.match(RDS2)) { - input = input.replace(RDS2, "/"); - } else if (input.match(RDS3)) { - input = input.replace(RDS3, "/"); - output.pop(); - } else if (input === "." || input === "..") { - input = ""; - } else { - var im = input.match(RDS5); - if (im) { - var s = im[0]; - input = input.slice(s.length); - output.push(s); - } else { - throw new Error("Unexpected dot segment condition"); - } - } - } - return output.join(""); -} - -function serialize(components) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL; - var uriTokens = []; - //find scheme handler - var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; - //perform scheme specific serialization - if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options); - if (components.host) { - //if host component is an IPv6 address - if (protocol.IPV6ADDRESS.test(components.host)) {} - //TODO: normalize IPv6 address as per RFC 5952 - - //if host component is a domain name - else if (options.domainHost || schemeHandler && schemeHandler.domainHost) { - //convert IDN via punycode - try { - components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host); - } catch (e) { - components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; - } - } - } - //normalize encoding - _normalizeComponentEncoding(components, protocol); - if (options.reference !== "suffix" && components.scheme) { - uriTokens.push(components.scheme); - uriTokens.push(":"); - } - var authority = _recomposeAuthority(components, options); - if (authority !== undefined) { - if (options.reference !== "suffix") { - uriTokens.push("//"); - } - uriTokens.push(authority); - if (components.path && components.path.charAt(0) !== "/") { - uriTokens.push("/"); - } - } - if (components.path !== undefined) { - var s = components.path; - if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { - s = removeDotSegments(s); - } - if (authority === undefined) { - s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//" - } - uriTokens.push(s); - } - if (components.query !== undefined) { - uriTokens.push("?"); - uriTokens.push(components.query); - } - if (components.fragment !== undefined) { - uriTokens.push("#"); - uriTokens.push(components.fragment); - } - return uriTokens.join(""); //merge tokens into a string -} - -function resolveComponents(base, relative) { - var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - var skipNormalization = arguments[3]; - - var target = {}; - if (!skipNormalization) { - base = parse(serialize(base, options), options); //normalize base components - relative = parse(serialize(relative, options), options); //normalize relative components - } - options = options || {}; - if (!options.tolerant && relative.scheme) { - target.scheme = relative.scheme; - //target.authority = relative.authority; - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) { - //target.authority = relative.authority; - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (!relative.path) { - target.path = base.path; - if (relative.query !== undefined) { - target.query = relative.query; - } else { - target.query = base.query; - } - } else { - if (relative.path.charAt(0) === "/") { - target.path = removeDotSegments(relative.path); - } else { - if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) { - target.path = "/" + relative.path; - } else if (!base.path) { - target.path = relative.path; - } else { - target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; - } - target.path = removeDotSegments(target.path); - } - target.query = relative.query; - } - //target.authority = base.authority; - target.userinfo = base.userinfo; - target.host = base.host; - target.port = base.port; - } - target.scheme = base.scheme; - } - target.fragment = relative.fragment; - return target; -} - -function resolve(baseURI, relativeURI, options) { - var schemelessOptions = assign({ scheme: 'null' }, options); - return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions); -} - -function normalize(uri, options) { - if (typeof uri === "string") { - uri = serialize(parse(uri, options), options); - } else if (typeOf(uri) === "object") { - uri = parse(serialize(uri, options), options); - } - return uri; -} - -function equal(uriA, uriB, options) { - if (typeof uriA === "string") { - uriA = serialize(parse(uriA, options), options); - } else if (typeOf(uriA) === "object") { - uriA = serialize(uriA, options); - } - if (typeof uriB === "string") { - uriB = serialize(parse(uriB, options), options); - } else if (typeOf(uriB) === "object") { - uriB = serialize(uriB, options); - } - return uriA === uriB; -} - -function escapeComponent(str, options) { - return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar); -} - -function unescapeComponent(str, options) { - return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars); -} - -var handler = { - scheme: "http", - domainHost: true, - parse: function parse(components, options) { - //report missing host - if (!components.host) { - components.error = components.error || "HTTP URIs must have a host."; - } - return components; - }, - serialize: function serialize(components, options) { - var secure = String(components.scheme).toLowerCase() === "https"; - //normalize the default port - if (components.port === (secure ? 443 : 80) || components.port === "") { - components.port = undefined; - } - //normalize the empty path - if (!components.path) { - components.path = "/"; - } - //NOTE: We do not parse query strings for HTTP URIs - //as WWW Form Url Encoded query strings are part of the HTML4+ spec, - //and not the HTTP spec. - return components; - } -}; - -var handler$1 = { - scheme: "https", - domainHost: handler.domainHost, - parse: handler.parse, - serialize: handler.serialize -}; - -function isSecure(wsComponents) { - return typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss"; -} -//RFC 6455 -var handler$2 = { - scheme: "ws", - domainHost: true, - parse: function parse(components, options) { - var wsComponents = components; - //indicate if the secure flag is set - wsComponents.secure = isSecure(wsComponents); - //construct resouce name - wsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : ''); - wsComponents.path = undefined; - wsComponents.query = undefined; - return wsComponents; - }, - serialize: function serialize(wsComponents, options) { - //normalize the default port - if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") { - wsComponents.port = undefined; - } - //ensure scheme matches secure flag - if (typeof wsComponents.secure === 'boolean') { - wsComponents.scheme = wsComponents.secure ? 'wss' : 'ws'; - wsComponents.secure = undefined; - } - //reconstruct path from resource name - if (wsComponents.resourceName) { - var _wsComponents$resourc = wsComponents.resourceName.split('?'), - _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2), - path = _wsComponents$resourc2[0], - query = _wsComponents$resourc2[1]; - - wsComponents.path = path && path !== '/' ? path : undefined; - wsComponents.query = query; - wsComponents.resourceName = undefined; - } - //forbid fragment component - wsComponents.fragment = undefined; - return wsComponents; - } -}; - -var handler$3 = { - scheme: "wss", - domainHost: handler$2.domainHost, - parse: handler$2.parse, - serialize: handler$2.serialize -}; - -var O = {}; -var isIRI = true; -//RFC 3986 -var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]"; -var HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive -var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded -//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; = -//const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]"; -//const WSP$$ = "[\\x20\\x09]"; -//const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]"; //(%d1-8 / %d11-12 / %d14-31 / %d127) -//const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext -//const VCHAR$$ = "[\\x21-\\x7E]"; -//const WSP$$ = "[\\x20\\x09]"; -//const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext -//const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+"); -//const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$); -//const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"'); -var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]"; -var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]"; -var VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]"); -var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"; -var UNRESERVED = new RegExp(UNRESERVED$$, "g"); -var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g"); -var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g"); -var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g"); -var NOT_HFVALUE = NOT_HFNAME; -function decodeUnreserved(str) { - var decStr = pctDecChars(str); - return !decStr.match(UNRESERVED) ? str : decStr; -} -var handler$4 = { - scheme: "mailto", - parse: function parse$$1(components, options) { - var mailtoComponents = components; - var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : []; - mailtoComponents.path = undefined; - if (mailtoComponents.query) { - var unknownHeaders = false; - var headers = {}; - var hfields = mailtoComponents.query.split("&"); - for (var x = 0, xl = hfields.length; x < xl; ++x) { - var hfield = hfields[x].split("="); - switch (hfield[0]) { - case "to": - var toAddrs = hfield[1].split(","); - for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) { - to.push(toAddrs[_x]); - } - break; - case "subject": - mailtoComponents.subject = unescapeComponent(hfield[1], options); - break; - case "body": - mailtoComponents.body = unescapeComponent(hfield[1], options); - break; - default: - unknownHeaders = true; - headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options); - break; - } - } - if (unknownHeaders) mailtoComponents.headers = headers; - } - mailtoComponents.query = undefined; - for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) { - var addr = to[_x2].split("@"); - addr[0] = unescapeComponent(addr[0]); - if (!options.unicodeSupport) { - //convert Unicode IDN -> ASCII IDN - try { - addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase()); - } catch (e) { - mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e; - } - } else { - addr[1] = unescapeComponent(addr[1], options).toLowerCase(); - } - to[_x2] = addr.join("@"); - } - return mailtoComponents; - }, - serialize: function serialize$$1(mailtoComponents, options) { - var components = mailtoComponents; - var to = toArray(mailtoComponents.to); - if (to) { - for (var x = 0, xl = to.length; x < xl; ++x) { - var toAddr = String(to[x]); - var atIdx = toAddr.lastIndexOf("@"); - var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar); - var domain = toAddr.slice(atIdx + 1); - //convert IDN via punycode - try { - domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain); - } catch (e) { - components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; - } - to[x] = localPart + "@" + domain; - } - components.path = to.join(","); - } - var headers = mailtoComponents.headers = mailtoComponents.headers || {}; - if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject; - if (mailtoComponents.body) headers["body"] = mailtoComponents.body; - var fields = []; - for (var name in headers) { - if (headers[name] !== O[name]) { - fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)); - } - } - if (fields.length) { - components.query = fields.join("&"); - } - return components; - } -}; - -var URN_PARSE = /^([^\:]+)\:(.*)/; -//RFC 2141 -var handler$5 = { - scheme: "urn", - parse: function parse$$1(components, options) { - var matches = components.path && components.path.match(URN_PARSE); - var urnComponents = components; - if (matches) { - var scheme = options.scheme || urnComponents.scheme || "urn"; - var nid = matches[1].toLowerCase(); - var nss = matches[2]; - var urnScheme = scheme + ":" + (options.nid || nid); - var schemeHandler = SCHEMES[urnScheme]; - urnComponents.nid = nid; - urnComponents.nss = nss; - urnComponents.path = undefined; - if (schemeHandler) { - urnComponents = schemeHandler.parse(urnComponents, options); - } - } else { - urnComponents.error = urnComponents.error || "URN can not be parsed."; - } - return urnComponents; - }, - serialize: function serialize$$1(urnComponents, options) { - var scheme = options.scheme || urnComponents.scheme || "urn"; - var nid = urnComponents.nid; - var urnScheme = scheme + ":" + (options.nid || nid); - var schemeHandler = SCHEMES[urnScheme]; - if (schemeHandler) { - urnComponents = schemeHandler.serialize(urnComponents, options); - } - var uriComponents = urnComponents; - var nss = urnComponents.nss; - uriComponents.path = (nid || options.nid) + ":" + nss; - return uriComponents; - } -}; - -var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/; -//RFC 4122 -var handler$6 = { - scheme: "urn:uuid", - parse: function parse(urnComponents, options) { - var uuidComponents = urnComponents; - uuidComponents.uuid = uuidComponents.nss; - uuidComponents.nss = undefined; - if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) { - uuidComponents.error = uuidComponents.error || "UUID is not valid."; - } - return uuidComponents; - }, - serialize: function serialize(uuidComponents, options) { - var urnComponents = uuidComponents; - //normalize UUID - urnComponents.nss = (uuidComponents.uuid || "").toLowerCase(); - return urnComponents; - } -}; - -SCHEMES[handler.scheme] = handler; -SCHEMES[handler$1.scheme] = handler$1; -SCHEMES[handler$2.scheme] = handler$2; -SCHEMES[handler$3.scheme] = handler$3; -SCHEMES[handler$4.scheme] = handler$4; -SCHEMES[handler$5.scheme] = handler$5; -SCHEMES[handler$6.scheme] = handler$6; - -exports.SCHEMES = SCHEMES; -exports.pctEncChar = pctEncChar; -exports.pctDecChars = pctDecChars; -exports.parse = parse; -exports.removeDotSegments = removeDotSegments; -exports.serialize = serialize; -exports.resolveComponents = resolveComponents; -exports.resolve = resolve; -exports.normalize = normalize; -exports.equal = equal; -exports.escapeComponent = escapeComponent; -exports.unescapeComponent = unescapeComponent; - -Object.defineProperty(exports, '__esModule', { value: true }); - -}))); -//# sourceMappingURL=uri.all.js.map - - /***/ }), /***/ 94643: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/* provided dependency */ var console = __webpack_require__(96763); /** * Module exports. @@ -108792,8 +104677,6 @@ exports.isAnyArrayBuffer = isAnyArrayBuffer; /***/ 40537: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { -/* provided dependency */ var process = __webpack_require__(65606); -/* provided dependency */ var console = __webpack_require__(96763); // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -109669,1908 +105552,8827 @@ exports.createContext = Script.createContext = function (context) { /***/ }), -/***/ 14400: +/***/ 25767: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/* - Copyright 2019 0KIMS association. - - This file is part of wasmbuilder - - wasmbuilder is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmbuilder is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmbuilder. If not, see . -*/ - -module.exports.ModuleBuilder = __webpack_require__(80442); -/* unused reexport */ __webpack_require__(38269); -/* unused reexport */ __webpack_require__(77831); +"use strict"; -/***/ }), +var forEach = __webpack_require__(82682); +var availableTypedArrays = __webpack_require__(39209); +var callBind = __webpack_require__(10487); +var callBound = __webpack_require__(38075); +var gOPD = __webpack_require__(75795); -/***/ 65705: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/** @type {(O: object) => string} */ +var $toString = callBound('Object.prototype.toString'); +var hasToStringTag = __webpack_require__(49092)(); -/* - Copyright 2019 0KIMS association. +var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; +var typedArrays = availableTypedArrays(); - This file is part of wasmbuilder +var $slice = callBound('String.prototype.slice'); +var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); - wasmbuilder is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. +/** @type {(array: readonly T[], value: unknown) => number} */ +var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) { + for (var i = 0; i < array.length; i += 1) { + if (array[i] === value) { + return i; + } + } + return -1; +}; - wasmbuilder is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmbuilder. If not, see . -*/ - -const utils = __webpack_require__(60484); - -class CodeBuilder { - constructor(func) { - this.func = func; - this.functionName = func.functionName; - this.module = func.module; - } - - setLocal(localName, valCode) { - const idx = this.func.localIdxByName[localName]; - if (idx === undefined) - throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); - return [...valCode, 0x21, ...utils.varuint32( idx )]; - } - - teeLocal(localName, valCode) { - const idx = this.func.localIdxByName[localName]; - if (idx === undefined) - throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); - return [...valCode, 0x22, ...utils.varuint32( idx )]; - } - - getLocal(localName) { - const idx = this.func.localIdxByName[localName]; - if (idx === undefined) - throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); - return [0x20, ...utils.varuint32( idx )]; - } - - i64_load8_s(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 0 : _align; // 8 bits alignment by default - return [...idxCode, 0x30, align, ...utils.varuint32(offset)]; - } - - i64_load8_u(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 0 : _align; // 8 bits alignment by default - return [...idxCode, 0x31, align, ...utils.varuint32(offset)]; - } - - i64_load16_s(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 1 : _align; // 16 bits alignment by default - return [...idxCode, 0x32, align, ...utils.varuint32(offset)]; - } - - i64_load16_u(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 1 : _align; // 16 bits alignment by default - return [...idxCode, 0x33, align, ...utils.varuint32(offset)]; - } - - i64_load32_s(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default - return [...idxCode, 0x34, align, ...utils.varuint32(offset)]; - } - - i64_load32_u(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default - return [...idxCode, 0x35, align, ...utils.varuint32(offset)]; - } - - i64_load(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 3 : _align; // 64 bits alignment by default - return [...idxCode, 0x29, align, ...utils.varuint32(offset)]; - } - - - i64_store(idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (Array.isArray(_offset)) { - offset = 0; - align = 3; - codeVal = _offset; - } else if (Array.isArray(_align)) { - offset = _offset; - align = 3; - codeVal = _align; - } else if (Array.isArray(_codeVal)) { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - return [...idxCode, ...codeVal, 0x37, align, ...utils.varuint32(offset)]; - } - - i64_store32(idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (Array.isArray(_offset)) { - offset = 0; - align = 2; - codeVal = _offset; - } else if (Array.isArray(_align)) { - offset = _offset; - align = 2; - codeVal = _align; - } else if (Array.isArray(_codeVal)) { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - return [...idxCode, ...codeVal, 0x3e, align, ...utils.varuint32(offset)]; - } - - - i64_store16(idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (Array.isArray(_offset)) { - offset = 0; - align = 1; - codeVal = _offset; - } else if (Array.isArray(_align)) { - offset = _offset; - align = 1; - codeVal = _align; - } else if (Array.isArray(_codeVal)) { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - return [...idxCode, ...codeVal, 0x3d, align, ...utils.varuint32(offset)]; - } - - - i64_store8(idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (Array.isArray(_offset)) { - offset = 0; - align = 0; - codeVal = _offset; - } else if (Array.isArray(_align)) { - offset = _offset; - align = 0; - codeVal = _align; - } else if (Array.isArray(_codeVal)) { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - return [...idxCode, ...codeVal, 0x3c, align, ...utils.varuint32(offset)]; - } - - i32_load8_s(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default - return [...idxCode, 0x2c, align, ...utils.varuint32(offset)]; - } - - i32_load8_u(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default - return [...idxCode, 0x2d, align, ...utils.varuint32(offset)]; - } - - i32_load16_s(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default - return [...idxCode, 0x2e, align, ...utils.varuint32(offset)]; - } - - i32_load16_u(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default - return [...idxCode, 0x2f, align, ...utils.varuint32(offset)]; - } - - i32_load(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default - return [...idxCode, 0x28, align, ...utils.varuint32(offset)]; - } - - i32_store(idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (Array.isArray(_offset)) { - offset = 0; - align = 2; - codeVal = _offset; - } else if (Array.isArray(_align)) { - offset = _offset; - align = 2; - codeVal = _align; - } else if (Array.isArray(_codeVal)) { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - return [...idxCode, ...codeVal, 0x36, align, ...utils.varuint32(offset)]; - } - - - i32_store16(idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (Array.isArray(_offset)) { - offset = 0; - align = 1; - codeVal = _offset; - } else if (Array.isArray(_align)) { - offset = _offset; - align = 1; - codeVal = _align; - } else if (Array.isArray(_codeVal)) { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - return [...idxCode, ...codeVal, 0x3b, align, ...utils.varuint32(offset)]; - } - - i32_store8(idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (Array.isArray(_offset)) { - offset = 0; - align = 0; - codeVal = _offset; - } else if (Array.isArray(_align)) { - offset = _offset; - align = 0; - codeVal = _align; - } else if (Array.isArray(_codeVal)) { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - return [...idxCode, ...codeVal, 0x3a, align, ...utils.varuint32(offset)]; - } - - call(fnName, ...args) { - const idx = this.module.functionIdxByName[fnName]; - if (idx === undefined) - throw new Error(`Function not defined: Function: ${fnName}`); - return [...[].concat(...args), 0x10, ...utils.varuint32(idx)]; - } - - call_indirect(fnIdx, ...args) { - return [...[].concat(...args), ...fnIdx, 0x11, 0, 0]; - } - - if(condCode, thenCode, elseCode) { - if (elseCode) { - return [...condCode, 0x04, 0x40, ...thenCode, 0x05, ...elseCode, 0x0b]; - } else { - return [...condCode, 0x04, 0x40, ...thenCode, 0x0b]; - } - } - - block(bCode) { return [0x02, 0x40, ...bCode, 0x0b]; } - loop(...args) { - return [0x03, 0x40, ...[].concat(...[...args]), 0x0b]; - } - br_if(relPath, condCode) { return [...condCode, 0x0d, ...utils.varuint32(relPath)]; } - br(relPath) { return [0x0c, ...utils.varuint32(relPath)]; } - ret(rCode) { return [...rCode, 0x0f]; } - drop(dCode) { return [...dCode, 0x1a]; } - - i64_const(num) { return [0x42, ...utils.varint64(num)]; } - i32_const(num) { return [0x41, ...utils.varint32(num)]; } - - - i64_eqz(opcode) { return [...opcode, 0x50]; } - i64_eq(op1code, op2code) { return [...op1code, ...op2code, 0x51]; } - i64_ne(op1code, op2code) { return [...op1code, ...op2code, 0x52]; } - i64_lt_s(op1code, op2code) { return [...op1code, ...op2code, 0x53]; } - i64_lt_u(op1code, op2code) { return [...op1code, ...op2code, 0x54]; } - i64_gt_s(op1code, op2code) { return [...op1code, ...op2code, 0x55]; } - i64_gt_u(op1code, op2code) { return [...op1code, ...op2code, 0x56]; } - i64_le_s(op1code, op2code) { return [...op1code, ...op2code, 0x57]; } - i64_le_u(op1code, op2code) { return [...op1code, ...op2code, 0x58]; } - i64_ge_s(op1code, op2code) { return [...op1code, ...op2code, 0x59]; } - i64_ge_u(op1code, op2code) { return [...op1code, ...op2code, 0x5a]; } - i64_add(op1code, op2code) { return [...op1code, ...op2code, 0x7c]; } - i64_sub(op1code, op2code) { return [...op1code, ...op2code, 0x7d]; } - i64_mul(op1code, op2code) { return [...op1code, ...op2code, 0x7e]; } - i64_div_s(op1code, op2code) { return [...op1code, ...op2code, 0x7f]; } - i64_div_u(op1code, op2code) { return [...op1code, ...op2code, 0x80]; } - i64_rem_s(op1code, op2code) { return [...op1code, ...op2code, 0x81]; } - i64_rem_u(op1code, op2code) { return [...op1code, ...op2code, 0x82]; } - i64_and(op1code, op2code) { return [...op1code, ...op2code, 0x83]; } - i64_or(op1code, op2code) { return [...op1code, ...op2code, 0x84]; } - i64_xor(op1code, op2code) { return [...op1code, ...op2code, 0x85]; } - i64_shl(op1code, op2code) { return [...op1code, ...op2code, 0x86]; } - i64_shr_s(op1code, op2code) { return [...op1code, ...op2code, 0x87]; } - i64_shr_u(op1code, op2code) { return [...op1code, ...op2code, 0x88]; } - i64_extend_i32_s(op1code) { return [...op1code, 0xac]; } - i64_extend_i32_u(op1code) { return [...op1code, 0xad]; } - i64_clz(op1code) { return [...op1code, 0x79]; } - i64_ctz(op1code) { return [...op1code, 0x7a]; } - - i32_eqz(op1code) { return [...op1code, 0x45]; } - i32_eq(op1code, op2code) { return [...op1code, ...op2code, 0x46]; } - i32_ne(op1code, op2code) { return [...op1code, ...op2code, 0x47]; } - i32_lt_s(op1code, op2code) { return [...op1code, ...op2code, 0x48]; } - i32_lt_u(op1code, op2code) { return [...op1code, ...op2code, 0x49]; } - i32_gt_s(op1code, op2code) { return [...op1code, ...op2code, 0x4a]; } - i32_gt_u(op1code, op2code) { return [...op1code, ...op2code, 0x4b]; } - i32_le_s(op1code, op2code) { return [...op1code, ...op2code, 0x4c]; } - i32_le_u(op1code, op2code) { return [...op1code, ...op2code, 0x4d]; } - i32_ge_s(op1code, op2code) { return [...op1code, ...op2code, 0x4e]; } - i32_ge_u(op1code, op2code) { return [...op1code, ...op2code, 0x4f]; } - i32_add(op1code, op2code) { return [...op1code, ...op2code, 0x6a]; } - i32_sub(op1code, op2code) { return [...op1code, ...op2code, 0x6b]; } - i32_mul(op1code, op2code) { return [...op1code, ...op2code, 0x6c]; } - i32_div_s(op1code, op2code) { return [...op1code, ...op2code, 0x6d]; } - i32_div_u(op1code, op2code) { return [...op1code, ...op2code, 0x6e]; } - i32_rem_s(op1code, op2code) { return [...op1code, ...op2code, 0x6f]; } - i32_rem_u(op1code, op2code) { return [...op1code, ...op2code, 0x70]; } - i32_and(op1code, op2code) { return [...op1code, ...op2code, 0x71]; } - i32_or(op1code, op2code) { return [...op1code, ...op2code, 0x72]; } - i32_xor(op1code, op2code) { return [...op1code, ...op2code, 0x73]; } - i32_shl(op1code, op2code) { return [...op1code, ...op2code, 0x74]; } - i32_shr_s(op1code, op2code) { return [...op1code, ...op2code, 0x75]; } - i32_shr_u(op1code, op2code) { return [...op1code, ...op2code, 0x76]; } - i32_rotl(op1code, op2code) { return [...op1code, ...op2code, 0x77]; } - i32_rotr(op1code, op2code) { return [...op1code, ...op2code, 0x78]; } - i32_wrap_i64(op1code) { return [...op1code, 0xa7]; } - i32_clz(op1code) { return [...op1code, 0x67]; } - i32_ctz(op1code) { return [...op1code, 0x68]; } - - unreachable() { return [ 0x0 ]; } - - current_memory() { return [ 0x3f, 0]; } - - comment() { return []; } +/** @typedef {(receiver: import('.').TypedArray) => string | typeof Uint8Array.prototype.slice.call | typeof Uint8Array.prototype.set.call} Getter */ +/** @type {{ [k in `\$${import('.').TypedArrayName}`]?: Getter } & { __proto__: null }} */ +var cache = { __proto__: null }; +if (hasToStringTag && gOPD && getPrototypeOf) { + forEach(typedArrays, function (typedArray) { + var arr = new g[typedArray](); + if (Symbol.toStringTag in arr) { + var proto = getPrototypeOf(arr); + // @ts-expect-error TS won't narrow inside a closure + var descriptor = gOPD(proto, Symbol.toStringTag); + if (!descriptor) { + var superProto = getPrototypeOf(proto); + // @ts-expect-error TS won't narrow inside a closure + descriptor = gOPD(superProto, Symbol.toStringTag); + } + // @ts-expect-error TODO: fix + cache['$' + typedArray] = callBind(descriptor.get); + } + }); +} else { + forEach(typedArrays, function (typedArray) { + var arr = new g[typedArray](); + var fn = arr.slice || arr.set; + if (fn) { + // @ts-expect-error TODO: fix + cache['$' + typedArray] = callBind(fn); + } + }); } -module.exports = CodeBuilder; +/** @type {(value: object) => false | import('.').TypedArrayName} */ +var tryTypedArrays = function tryAllTypedArrays(value) { + /** @type {ReturnType} */ var found = false; + forEach( + // eslint-disable-next-line no-extra-parens + /** @type {Record<`\$${TypedArrayName}`, Getter>} */ /** @type {any} */ (cache), + /** @type {(getter: Getter, name: `\$${import('.').TypedArrayName}`) => void} */ + function (getter, typedArray) { + if (!found) { + try { + // @ts-expect-error TODO: fix + if ('$' + getter(value) === typedArray) { + found = $slice(typedArray, 1); + } + } catch (e) { /**/ } + } + } + ); + return found; +}; +/** @type {(value: object) => false | import('.').TypedArrayName} */ +var trySlices = function tryAllSlices(value) { + /** @type {ReturnType} */ var found = false; + forEach( + // eslint-disable-next-line no-extra-parens + /** @type {Record<`\$${TypedArrayName}`, Getter>} */ /** @type {any} */ (cache), + /** @type {(getter: typeof cache, name: `\$${import('.').TypedArrayName}`) => void} */ function (getter, name) { + if (!found) { + try { + // @ts-expect-error TODO: fix + getter(value); + found = $slice(name, 1); + } catch (e) { /**/ } + } + } + ); + return found; +}; -/***/ }), - -/***/ 24010: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmbuilder - - wasmbuilder is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmbuilder is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmbuilder. If not, see . -*/ - -const utils = __webpack_require__(60484); - -class CodeBuilderWat { - constructor(func) { - this.func = func; - this.functionName = func.functionName; - this.module = func.module; - } - - setLocal(localName, valCode) { - const idx = this.func.localIdxByName[localName]; - if (idx === undefined) - throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); - return [valCode, `set_local $${localName}`]; - } - - teeLocal(localName, valCode) { - const idx = this.func.localIdxByName[localName]; - if (idx === undefined) - throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); - return [valCode, `tee_local $${localName}`]; - } - - getLocal(localName) { - const idx = this.func.localIdxByName[localName]; - if (idx === undefined) - throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); - return `get_local $${localName}`; - } - - genLoad(inst, def_align, idxCode, _offset, _align) { - let S = inst; - const offset = _offset || 0; - if (offset>0) S += ` offset=${offset}`; - const align = (_align === undefined) ? def_align : _align; // 8 bits alignment by default - if (align!=def_align) S += ` align=${1 << align}`; - return [idxCode, S]; - } - - - genStore(inst, def_align, idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (typeof _align === "undefined") { - offset = 0; - align = def_align; - codeVal = _offset; - } else if (typeof _codeVal === "undefined") { - offset = _offset; - align = def_align; - codeVal = _align; - } else { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - let S = inst; - if (offset>0) S += ` offset=${offset}`; - if (align!=def_align) S += ` align=${1 << align}`; - return [idxCode, codeVal, S]; - } - - i64_load8_s(idxCode, _offset, _align) { - return this.genLoad("i64.load8_s", 0, idxCode, _offset, _align); - } - - i64_load8_u(idxCode, _offset, _align) { - return this.genLoad("i64.load8_u", 0, idxCode, _offset, _align); - } - - i64_load16_s(idxCode, _offset, _align) { - return this.genLoad("i64.load16_s", 1,idxCode, _offset, _align); - } - - i64_load16_u(idxCode, _offset, _align) { - return this.genLoad("i64.load16_u", 1, idxCode, _offset, _align); - } - - i64_load32_s(idxCode, _offset, _align) { - return this.genLoad("i64.load32_s", 2, idxCode, _offset, _align); - } - - i64_load32_u(idxCode, _offset, _align) { - return this.genLoad("i64.load32_u", 2, idxCode, _offset, _align); - } - - i64_load(idxCode, _offset, _align) { - return this.genLoad("i64.load", 3, idxCode, _offset, _align); - } - - - i64_store(idxCode, _offset, _align, _codeVal) { - return this.genStore("i64.store", 3, idxCode, _offset, _align, _codeVal); - } - - i64_store32(idxCode, _offset, _align, _codeVal) { - return this.genStore("i64.store32", 2, idxCode, _offset, _align, _codeVal); - } - - i64_store16(idxCode, _offset, _align, _codeVal) { - return this.genStore("i64.store16", 1, idxCode, _offset, _align, _codeVal); - } - - i64_store8(idxCode, _offset, _align, _codeVal) { - return this.genStore("i64.store8", 0, idxCode, _offset, _align, _codeVal); - } - - i32_load8_s(idxCode, _offset, _align) { - return this.genLoad("i32.load8_s", 0, idxCode, _offset, _align); - } - - i32_load8_u(idxCode, _offset, _align) { - return this.genLoad("i32.load8_u", 0, idxCode, _offset, _align); - } - - i32_load16_s(idxCode, _offset, _align) { - return this.genLoad("i32.load16_s", 1, idxCode, _offset, _align); - } - - i32_load16_u(idxCode, _offset, _align) { - return this.genLoad("i32.load16_u", 1, idxCode, _offset, _align); - } - - i32_load(idxCode, _offset, _align) { - return this.genLoad("i32.load", 2, idxCode, _offset, _align); - } - - i32_store(idxCode, _offset, _align, _codeVal) { - return this.genStore("i32.store", 2, idxCode, _offset, _align, _codeVal); - } - - i32_store16(idxCode, _offset, _align, _codeVal) { - return this.genStore("i32.store16", 1, idxCode, _offset, _align, _codeVal); - } - - i32_store8(idxCode, _offset, _align, _codeVal) { - return this.genStore("i32.store8", 0, idxCode, _offset, _align, _codeVal); - } - - call(fnName, ...args) { - const idx = this.module.functionIdxByName[fnName]; - if (idx === undefined) - throw new Error(`Function not defined: Function: ${fnName}`); - return [args, `call $${fnName}`]; - } - - call_indirect(fnIdx, ...args) { - return [args, fnIdx, "call_indirect (type 0)"]; - } - - if(condCode, thenCode, elseCode) { - if (elseCode) { - return [condCode, "if", utils.ident(thenCode), "else", utils.ident(elseCode), "end"]; - } else { - return [condCode, "if", utils.ident(thenCode), "end"]; - } - } - - block(bCode) { return ["block", utils.ident(bCode), "end"]; } - loop(...args) { return ["loop", utils.ident(args), "end"]; } - br_if(relPath, condCode) { return [condCode, `br_if ${relPath}`]; } - br(relPath) { return `br ${relPath}`; } - ret(rCode) { return [rCode, "return"]; } - drop(dCode) { return [dCode, "drop"]; } - - i64_const(num) { return `i64.const ${num}`; } - i32_const(num) { return `i32.const ${num}`; } - - i64_eqz(opcode) { return [opcode, "i64.eqz"]; } - i64_eq(op1code, op2code) { return [op1code, op2code, "i64.eq"]; } - i64_ne(op1code, op2code) { return [op1code, op2code, "i64.ne"]; } - i64_lt_s(op1code, op2code) { return [op1code, op2code, "i64.lt_s"]; } - i64_lt_u(op1code, op2code) { return [op1code, op2code, "i64.lt_u"]; } - i64_gt_s(op1code, op2code) { return [op1code, op2code, "i64.gt_s"]; } - i64_gt_u(op1code, op2code) { return [op1code, op2code, "i64.gt_u"]; } - i64_le_s(op1code, op2code) { return [op1code, op2code, "i64.le_s"]; } - i64_le_u(op1code, op2code) { return [op1code, op2code, "i64.le_u"]; } - i64_ge_s(op1code, op2code) { return [op1code, op2code, "i64.ge_s"]; } - i64_ge_u(op1code, op2code) { return [op1code, op2code, "i64.ge_u"]; } - i64_add(op1code, op2code) { return [op1code, op2code, "i64.add"]; } - i64_sub(op1code, op2code) { return [op1code, op2code, "i64.sub"]; } - i64_mul(op1code, op2code) { return [op1code, op2code, "i64.mul"]; } - i64_div_s(op1code, op2code) { return [op1code, op2code, "i64.div_s"]; } - i64_div_u(op1code, op2code) { return [op1code, op2code, "i64.div_u"]; } - i64_rem_s(op1code, op2code) { return [op1code, op2code, "i64.rem_s"]; } - i64_rem_u(op1code, op2code) { return [op1code, op2code, "i64.rem_u"]; } - i64_and(op1code, op2code) { return [op1code, op2code, "i64.and"]; } - i64_or(op1code, op2code) { return [op1code, op2code, "i64.or"]; } - i64_xor(op1code, op2code) { return [op1code, op2code, "i64.xor"]; } - i64_shl(op1code, op2code) { return [op1code, op2code, "i64.shl"]; } - i64_shr_s(op1code, op2code) { return [op1code, op2code, "i64.shr_s"]; } - i64_shr_u(op1code, op2code) { return [op1code, op2code, "i64.shr_u"]; } - i64_extend_i32_s(op1code) { return [op1code, "i64.extend_s/i32"]; } - i64_extend_i32_u(op1code) { return [op1code, "i64.extend_u/i32"]; } - - - i32_eqz(op1code) { return [op1code, "i32.eqz"]; } - i32_eq(op1code, op2code) { return [op1code, op2code, "i32.eq"]; } - i32_ne(op1code, op2code) { return [op1code, op2code, "i32.ne"]; } - i32_lt_s(op1code, op2code) { return [op1code, op2code, "i32.lt_s"]; } - i32_lt_u(op1code, op2code) { return [op1code, op2code, "i32.lt_u"]; } - i32_gt_s(op1code, op2code) { return [op1code, op2code, "i32.gt_s"]; } - i32_gt_u(op1code, op2code) { return [op1code, op2code, "i32.gt_u"]; } - i32_le_s(op1code, op2code) { return [op1code, op2code, "i32.le_s"]; } - i32_le_u(op1code, op2code) { return [op1code, op2code, "i32.le_u"]; } - i32_ge_s(op1code, op2code) { return [op1code, op2code, "i32.ge_s"]; } - i32_ge_u(op1code, op2code) { return [op1code, op2code, "i32.ge_u"]; } - i32_add(op1code, op2code) { return [op1code, op2code, "i32.add"]; } - i32_sub(op1code, op2code) { return [op1code, op2code, "i32.sub"]; } - i32_mul(op1code, op2code) { return [op1code, op2code, "i32.mul"]; } - i32_div_s(op1code, op2code) { return [op1code, op2code, "i32.div_s"]; } - i32_div_u(op1code, op2code) { return [op1code, op2code, "i32.div_u"]; } - i32_rem_s(op1code, op2code) { return [op1code, op2code, "i32.rem_s"]; } - i32_rem_u(op1code, op2code) { return [op1code, op2code, "i32.rem_u"]; } - i32_and(op1code, op2code) { return [op1code, op2code, "i32.and"]; } - i32_or(op1code, op2code) { return [op1code, op2code, "i32.or"]; } - i32_xor(op1code, op2code) { return [op1code, op2code, "i32.xor"]; } - i32_shl(op1code, op2code) { return [op1code, op2code, "i32.shl"]; } - i32_shr_s(op1code, op2code) { return [op1code, op2code, "i32.shr_s"]; } - i32_shr_u(op1code, op2code) { return [op1code, op2code, "i32.shr_u"]; } - i32_rotl(op1code, op2code) { return [op1code, op2code, "i32.rotl"]; } - i32_rotr(op1code, op2code) { return [op1code, op2code, "i32.rotr"]; } - i32_wrap_i64(op1code) { return [op1code, "i32.wrap/i64"]; } - - ureachable() { return "unreachable"; } - - current_memory() { return "current_memory"; } - - comment(c) { return ";; " + c; } - -} - -module.exports = CodeBuilderWat; - - -/***/ }), - -/***/ 55986: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmbuilder - - wasmbuilder is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmbuilder is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmbuilder. If not, see . -*/ - -const CodeBuilder = __webpack_require__(65705); -const utils = __webpack_require__(60484); - -const typeCodes = { - "i32": 0x7f, - "i64": 0x7e, - "f32": 0x7d, - "f64": 0x7c, - "anyfunc": 0x70, - "func": 0x60, - "emptyblock": 0x40 +/** @type {import('.')} */ +module.exports = function whichTypedArray(value) { + if (!value || typeof value !== 'object') { return false; } + if (!hasToStringTag) { + /** @type {string} */ + var tag = $slice($toString(value), 8, -1); + if ($indexOf(typedArrays, tag) > -1) { + return tag; + } + if (tag !== 'Object') { + return false; + } + // node < 0.6 hits here on real Typed Arrays + return trySlices(value); + } + if (!gOPD) { return null; } // unknown engine + return tryTypedArrays(value); }; -class FunctionBuilder { +/***/ }), - constructor (module, fnName, fnType, moduleName, fieldName) { - if (fnType == "import") { - this.fnType = "import"; - this.moduleName = moduleName; - this.fieldName = fieldName; - } else if (fnType == "internal") { - this.fnType = "internal"; - } else { - throw new Error("Invalid function fnType: " + fnType); +/***/ 57510: +/***/ ((module) => { + +module.exports = extend + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function extend() { + var target = {} + + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key] + } } - this.module = module; - this.fnName = fnName; - this.params = []; - this.locals = []; - this.localIdxByName = {}; - this.code = []; - this.returnType = null; - this.nextLocal =0; } - addParam(paramName, paramType) { - if (this.localIdxByName[paramName]) - throw new Error(`param already exists. Function: ${this.fnName}, Param: ${paramName} `); - const idx = this.nextLocal++; - this.localIdxByName[paramName] = idx; - this.params.push({ - type: paramType - }); - } - - addLocal(localName, localType, _length) { - const length = _length || 1; - if (this.localIdxByName[localName]) - throw new Error(`local already exists. Function: ${this.fnName}, Param: ${localName} `); - const idx = this.nextLocal++; - this.localIdxByName[localName] = idx; - this.locals.push({ - type: localType, - length: length - }); - } - - setReturnType(returnType) { - if (this.returnType) - throw new Error(`returnType already defined. Function: ${this.fnName}`); - this.returnType = returnType; - } - - getSignature() { - const params = [...utils.varuint32(this.params.length), ...this.params.map((p) => typeCodes[p.type])]; - const returns = this.returnType ? [0x01, typeCodes[this.returnType]] : [0]; - return [0x60, ...params, ...returns]; - } - - getBody() { - const locals = this.locals.map((l) => [ - ...utils.varuint32(l.length), - typeCodes[l.type] - ]); - - const body = [ - ...utils.varuint32(this.locals.length), - ...[].concat(...locals), - ...this.code, - 0x0b - ]; - return [ - ...utils.varuint32(body.length), - ...body - ]; - } - - addCode(...code) { - this.code.push(...[].concat(...[...code])); - } - - getCodeBuilder() { - return new CodeBuilder(this); - } + return target } -module.exports = FunctionBuilder; - /***/ }), -/***/ 42341: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmbuilder - - wasmbuilder is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmbuilder is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmbuilder. If not, see . -*/ - -const CodeBuilderWat = __webpack_require__(24010); -const utils = __webpack_require__(60484); - -class FunctionBuilderWat { - - constructor (module, fnName, fnType, moduleName, fieldName) { - if (fnType == "import") { - this.fnType = "import"; - this.moduleName = moduleName; - this.fieldName = fieldName; - } else if (fnType == "internal") { - this.fnType = "internal"; - this.comment = moduleName; - } else { - throw new Error("Invalid function fnType: " + fnType); - } - this.module = module; - this.fnName = fnName; - this.params = []; - this.locals = []; - this.localIdxByName = {}; - this.code = []; - this.returnType = null; - this.nextLocal =0; - } - - addParam(paramName, paramType) { - if (this.localIdxByName[paramName]) - throw new Error(`param already exists. Function: ${this.fnName}, Param: ${paramName} `); - const idx = this.nextLocal++; - this.localIdxByName[paramName] = idx; - this.params.push({ - type: paramType, - name: paramName - }); - } - - addLocal(localName, localType, _length) { - if ((typeof _length != "undefined") && (_length != 1)) { - throw new Error("Locals greater than 1 not implemented"); - } - if (this.localIdxByName[localName]) - throw new Error(`local already exists. Function: ${this.fnName}, Param: ${localName} `); - const idx = this.nextLocal++; - this.localIdxByName[localName] = idx; - this.locals.push({ - type: localType, - name: localName, - }); - } - - setReturnType(returnType) { - if (this.returnType) - throw new Error(`returnType already defined. Function: ${this.fnName}`); - this.returnType = returnType; - } - - getSignature() { - let p = ""; - for (let i=0; i { +/* (ignored) */ /***/ }), -/***/ 80442: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmbuilder - - wasmbuilder is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmbuilder is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmbuilder. If not, see . -*/ - - -const FunctionBuilder = __webpack_require__(55986); -const utils = __webpack_require__(60484); - -class ModuleBuilder { - - constructor() { - this.functions = []; - this.functionIdxByName = {}; - this.nImportFunctions = 0; - this.nInternalFunctions =0; - this.memory = { - pagesSize: 1, - moduleName: "env", - fieldName: "memory" - }; - this.free = 8; - this.datas = []; - this.modules = {}; - this.exports = []; - this.functionsTable = []; - } - - build() { - this._setSignatures(); - return new Uint8Array([ - ...utils.u32(0x6d736100), - ...utils.u32(1), - ...this._buildType(), - ...this._buildImport(), - ...this._buildFunctionDeclarations(), - ...this._buildFunctionsTable(), - ...this._buildExports(), - ...this._buildElements(), - ...this._buildCode(), - ...this._buildData() - ]); - } - - addFunction(fnName) { - if (typeof(this.functionIdxByName[fnName]) !== "undefined") - throw new Error(`Function already defined: ${fnName}`); - - const idx = this.functions.length; - this.functionIdxByName[fnName] = idx; - - this.functions.push(new FunctionBuilder(this, fnName, "internal")); - - this.nInternalFunctions++; - return this.functions[idx]; - } - - addIimportFunction(fnName, moduleName, _fieldName) { - if (typeof(this.functionIdxByName[fnName]) !== "undefined") - throw new Error(`Function already defined: ${fnName}`); - - if ( (this.functions.length>0) - &&(this.functions[this.functions.length-1].type == "internal")) - throw new Error(`Import functions must be declared before internal: ${fnName}`); - - let fieldName = _fieldName || fnName; - - const idx = this.functions.length; - this.functionIdxByName[fnName] = idx; - - this.functions.push(new FunctionBuilder(this, fnName, "import", moduleName, fieldName)); - - this.nImportFunctions ++; - return this.functions[idx]; - } - - setMemory(pagesSize, moduleName, fieldName) { - this.memory = { - pagesSize: pagesSize, - moduleName: moduleName || "env", - fieldName: fieldName || "memory" - }; - } - - exportFunction(fnName, _exportName) { - const exportName = _exportName || fnName; - if (typeof(this.functionIdxByName[fnName]) === "undefined") - throw new Error(`Function not defined: ${fnName}`); - const idx = this.functionIdxByName[fnName]; - if (exportName != fnName) { - this.functionIdxByName[exportName] = idx; - } - this.exports.push({ - exportName: exportName, - idx: idx - }); - } - - addFunctionToTable(fnName) { - const idx = this.functionIdxByName[fnName]; - this.functionsTable.push(idx); - } - - addData(offset, bytes) { - this.datas.push({ - offset: offset, - bytes: bytes - }); - } - - alloc(a, b) { - let size; - let bytes; - if ((Array.isArray(a) || ArrayBuffer.isView(a)) && (typeof(b) === "undefined")) { - size = a.length; - bytes = a; - } else { - size = a; - bytes = b; - } - size = (((size-1)>>3) +1)<<3; // Align to 64 bits. - const p = this.free; - this.free += size; - if (bytes) { - this.addData(p, bytes); - } - return p; - } - - allocString(s) { - const encoder = new globalThis.TextEncoder(); - const uint8array = encoder.encode(s); - return this.alloc([...uint8array, 0]); - } - - _setSignatures() { - this.signatures = []; - const signatureIdxByName = {}; - if (this.functionsTable.length>0) { - const signature = this.functions[this.functionsTable[0]].getSignature(); - const signatureName = "s_"+utils.toHexString(signature); - signatureIdxByName[signatureName] = 0; - this.signatures.push(signature); - } - for (let i=0; i { +/* (ignored) */ /***/ }), -/***/ 38269: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ 47790: +/***/ (() => { -/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; -/* - Copyright 2019 0KIMS association. +/* (ignored) */ - This file is part of wasmbuilder +/***/ }), - wasmbuilder is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. +/***/ 73776: +/***/ (() => { - wasmbuilder is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. +/* (ignored) */ - You should have received a copy of the GNU General Public License - along with wasmbuilder. If not, see . -*/ +/***/ }), +/***/ 21638: +/***/ (() => { -const FunctionBuilderWat = __webpack_require__(42341); -const utils = __webpack_require__(60484); +/* (ignored) */ -class ModuleBuilderWat { +/***/ }), - constructor() { - this.functions = []; - this.functionIdxByName = {}; - this.nImportFunctions = 0; - this.nInternalFunctions =0; - this.memory = { - pagesSize: 1, - moduleName: "env", - fieldName: "memory" - }; - this.free = 8; - this.datas = []; - this.modules = {}; - this.exports = []; - this.functionsTable = []; - } +/***/ 92668: +/***/ (() => { - build() { - const src = []; - this._setSignatures(); - src.push(this._buildType()); - src.push(this._buildImport()); - if (this.functionsTable.length>0) { - src.push(this._buildFunctionsTable()); +/* (ignored) */ + +/***/ }), + +/***/ 77965: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 66089: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 79368: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 23276: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 59676: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 64688: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 51069: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 15340: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 79838: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 59817: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 71281: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 60513: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 2378: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 60290: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 47882: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 27754: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/** + * A `StructFailure` represents a single specific failure in validation. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.StructError = void 0; +/** + * `StructError` objects are thrown (or returned) when validation fails. + * + * Validation logic is design to exit early for maximum performance. The error + * represents the first error encountered during validation. For more detail, + * the `error.failures` property is a generator function that can be run to + * continue validation and receive all the failures in the data. + */ +class StructError extends TypeError { + constructor(failure, failures) { + let cached; + const { message, explanation, ...rest } = failure; + const { path } = failure; + const cause = path.length === 0 ? message : `At path: ${path.join('.')} -- ${message}`; + super(explanation ?? cause); + if (explanation !== null && explanation !== undefined) { + this.cause = cause; } - if (this.exports.length > 0) { - src.push(this._buildExports()); - } - if (this.functionsTable.length>0) { - src.push(this._buildElements()); - } - if (this.nInternalFunctions>0) { - src.push(this._buildFunctions()); - } - src.push(this._buildData()); - return [ - "(module", - utils.ident(src), - ")" - ]; - } - - addFunction(fnName, comment) { - if (typeof(this.functionIdxByName[fnName]) !== "undefined") - throw new Error(`Function already defined: ${fnName}`); - - const idx = this.functions.length; - this.functionIdxByName[fnName] = idx; - - this.functions.push(new FunctionBuilderWat(this, fnName, "internal", comment)); - - this.nInternalFunctions++; - return this.functions[idx]; - } - - addIimportFunction(fnName, moduleName, _fieldName) { - if (typeof(this.functionIdxByName[fnName]) !== "undefined") - throw new Error(`Function already defined: ${fnName}`); - - if ( (this.functions.length>0) - &&(this.functions[this.functions.length-1].type == "internal")) - throw new Error(`Import functions must be declared before internal: ${fnName}`); - - let fieldName = _fieldName || fnName; - - const idx = this.functions.length; - this.functionIdxByName[fnName] = idx; - - this.functions.push(new FunctionBuilderWat(this, fnName, "import", moduleName, fieldName)); - - this.nImportFunctions ++; - return this.functions[idx]; - } - - setMemory(pagesSize, moduleName, fieldName) { - this.memory = { - pagesSize: pagesSize, - moduleName: moduleName || "env", - fieldName: fieldName || "memory" + Object.assign(this, rest); + this.name = this.constructor.name; + this.failures = () => { + return (cached ?? (cached = [failure, ...failures()])); }; } +} +exports.StructError = StructError; +//# sourceMappingURL=error.cjs.map - exportFunction(fnName, _exportName) { - const exportName = _exportName || fnName; - if (typeof(this.functionIdxByName[fnName]) === "undefined") - throw new Error(`Function not defined: ${fnName}`); - const idx = this.functionIdxByName[fnName]; - if (exportName != fnName) { - this.functionIdxByName[exportName] = idx; +/***/ }), + +/***/ 35620: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +__exportStar(__webpack_require__(27754), exports); +__exportStar(__webpack_require__(99067), exports); +__exportStar(__webpack_require__(91704), exports); +__exportStar(__webpack_require__(50401), exports); +__exportStar(__webpack_require__(67792), exports); +__exportStar(__webpack_require__(65991), exports); +//# sourceMappingURL=index.cjs.map + +/***/ }), + +/***/ 99067: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.validate = exports.is = exports.mask = exports.create = exports.assert = exports.Struct = void 0; +const error_js_1 = __webpack_require__(27754); +const utils_js_1 = __webpack_require__(70639); +/** + * `Struct` objects encapsulate the validation logic for a specific type of + * values. Once constructed, you use the `assert`, `is` or `validate` helpers to + * validate unknown input data against the struct. + */ +class Struct { + constructor(props) { + const { type, schema, validator, refiner, coercer = (value) => value, entries = function* () { + /* noop */ + }, } = props; + this.type = type; + this.schema = schema; + this.entries = entries; + this.coercer = coercer; + if (validator) { + this.validator = (value, context) => { + const result = validator(value, context); + return (0, utils_js_1.toFailures)(result, context, this, value); + }; } - this.exports.push({ - exportName: exportName, - idx: idx - }); - } - - addFunctionToTable(fnName) { - const idx = this.functionIdxByName[fnName]; - this.functionsTable.push(idx); - } - - addData(offset, bytes) { - this.datas.push({ - offset: offset, - bytes: bytes - }); - } - - alloc(a, b) { - let size; - let bytes; - if ((Array.isArray(a) || ArrayBuffer.isView(a)) && (typeof(b) === "undefined")) { - size = a.length; - bytes = a; - } else { - size = a; - bytes = b; + else { + this.validator = () => []; } - size = (((size-1)>>3) +1)<<3; // Align to 64 bits. - const p = this.free; - this.free += size; - if (bytes) { - this.addData(p, bytes); + if (refiner) { + this.refiner = (value, context) => { + const result = refiner(value, context); + return (0, utils_js_1.toFailures)(result, context, this, value); + }; } - return p; - } - - allocString(s) { - const encoder = new TextEncoder(); - const uint8array = encoder.encode(s); - return this.alloc([...uint8array, 0]); - } - - _setSignatures() { - this.signatures = []; - const signatureIdxByName = {}; - if (this.functionsTable.length>0) { - const signature = this.functions[this.functionsTable[0]].getSignature(); - const signatureName = this.functions[this.functionsTable[0]].getSignatureName(); - signatureIdxByName[signatureName] = 0; - this.signatures.push(signature); + else { + this.refiner = () => []; } - for (let i=0; i126 || b[i] == 34 || b[i]==92) { - let h=b[i].toString(16); - while (h.length<2) h = "0"+h; - S += "\\" + h; - } else { - S += String.fromCharCode(b[i]); +} +exports.assert = assert; +/** + * Create a value with the coercion logic of struct and validate it. + * + * @param value - The value to coerce and validate. + * @param struct - The struct to validate against. + * @param message - An optional message to include in the error. + * @returns The coerced and validated value. + */ +function create(value, struct, message) { + const result = validate(value, struct, { coerce: true, message }); + if (result[0]) { + throw result[0]; + } + else { + return result[1]; + } +} +exports.create = create; +/** + * Mask a value, returning only the subset of properties defined by a struct. + * + * @param value - The value to mask. + * @param struct - The struct to mask against. + * @param message - An optional message to include in the error. + * @returns The masked value. + */ +function mask(value, struct, message) { + const result = validate(value, struct, { coerce: true, mask: true, message }); + if (result[0]) { + throw result[0]; + } + else { + return result[1]; + } +} +exports.mask = mask; +/** + * Check if a value passes a struct. + * + * @param value - The value to validate. + * @param struct - The struct to validate against. + * @returns `true` if the value passes the struct, `false` otherwise. + */ +function is(value, struct) { + const result = validate(value, struct); + return !result[0]; +} +exports.is = is; +/** + * Validate a value against a struct, returning an error if invalid, or the + * value (with potential coercion) if valid. + * + * @param value - The value to validate. + * @param struct - The struct to validate against. + * @param options - Optional settings. + * @param options.coerce - Whether to coerce the value before validating it. + * @param options.mask - Whether to mask the value before validating it. + * @param options.message - An optional message to include in the error. + * @returns A tuple containing the error (if invalid) and the validated value. + */ +function validate(value, struct, options = {}) { + const tuples = (0, utils_js_1.run)(value, struct, options); + const tuple = (0, utils_js_1.shiftIterator)(tuples); + if (tuple[0]) { + const error = new error_js_1.StructError(tuple[0], function* () { + for (const innerTuple of tuples) { + if (innerTuple[0]) { + yield innerTuple[0]; } } - S += "\""; - return S; + }); + return [error, undefined]; + } + const validatedValue = tuple[1]; + return [undefined, validatedValue]; +} +exports.validate = validate; +//# sourceMappingURL=struct.cjs.map + +/***/ }), + +/***/ 91704: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.trimmed = exports.defaulted = exports.coerce = void 0; +const struct_js_1 = __webpack_require__(99067); +const utils_js_1 = __webpack_require__(70639); +const types_js_1 = __webpack_require__(67792); +/** + * Augment a `Struct` to add an additional coercion step to its input. + * + * This allows you to transform input data before validating it, to increase the + * likelihood that it passes validation—for example for default values, parsing + * different formats, etc. + * + * Note: You must use `create(value, Struct)` on the value to have the coercion + * take effect! Using simply `assert()` or `is()` will not use coercion. + * + * @param struct - The struct to augment. + * @param condition - A struct that the input must pass to be coerced. + * @param coercer - A function that takes the input and returns the coerced + * value. + * @returns A new struct that will coerce its input before validating it. + */ +function coerce(struct, condition, coercer) { + return new struct_js_1.Struct({ + ...struct, + coercer: (value, ctx) => { + return (0, struct_js_1.is)(value, condition) + ? struct.coercer(coercer(value, ctx), ctx) + : struct.coercer(value, ctx); + }, + }); +} +exports.coerce = coerce; +/** + * Augment a struct to replace `undefined` values with a default. + * + * Note: You must use `create(value, Struct)` on the value to have the coercion + * take effect! Using simply `assert()` or `is()` will not use coercion. + * + * @param struct - The struct to augment. + * @param fallback - The value to use when the input is `undefined`. + * @param options - An optional options object. + * @param options.strict - When `true`, the fallback will only be used when the + * input is `undefined`. When `false`, the fallback will be used when the input + * is `undefined` or when the input is a plain object and the fallback is a + * plain object, and any keys in the fallback are missing from the input. + * @returns A new struct that will replace `undefined` inputs with a default. + */ +function defaulted(struct, fallback, options = {}) { + return coerce(struct, (0, types_js_1.unknown)(), (value) => { + const result = typeof fallback === 'function' ? fallback() : fallback; + if (value === undefined) { + return result; + } + if (!options.strict && (0, utils_js_1.isPlainObject)(value) && (0, utils_js_1.isPlainObject)(result)) { + const ret = { ...value }; + let changed = false; + for (const key in result) { + if (ret[key] === undefined) { + ret[key] = result[key]; + changed = true; + } + } + if (changed) { + return ret; + } + } + return value; + }); +} +exports.defaulted = defaulted; +/** + * Augment a struct to trim string inputs. + * + * Note: You must use `create(value, Struct)` on the value to have the coercion + * take effect! Using simply `assert()` or `is()` will not use coercion. + * + * @param struct - The struct to augment. + * @returns A new struct that will trim string inputs before validating them. + */ +function trimmed(struct) { + return coerce(struct, (0, types_js_1.string)(), (value) => value.trim()); +} +exports.trimmed = trimmed; +//# sourceMappingURL=coercions.cjs.map + +/***/ }), + +/***/ 50401: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.refine = exports.size = exports.pattern = exports.nonempty = exports.min = exports.max = exports.empty = void 0; +const struct_js_1 = __webpack_require__(99067); +const utils_js_1 = __webpack_require__(70639); +/** + * Ensure that a string, array, map, or set is empty. + * + * @param struct - The struct to augment. + * @returns A new struct that will only accept empty values. + */ +function empty(struct) { + return refine(struct, 'empty', (value) => { + // eslint-disable-next-line @typescript-eslint/no-shadow + const size = getSize(value); + return (size === 0 || + `Expected an empty ${struct.type} but received one with a size of \`${size}\``); + }); +} +exports.empty = empty; +/** + * Get the size of a string, array, map, or set. + * + * @param value - The value to measure. + * @returns The size of the value. + */ +function getSize(value) { + if (value instanceof Map || value instanceof Set) { + return value.size; + } + return value.length; +} +/** + * Ensure that a number or date is below a threshold. + * + * @param struct - The struct to augment. + * @param threshold - The maximum value that the input can be. + * @param options - An optional options object. + * @param options.exclusive - When `true`, the input must be strictly less than + * the threshold. When `false`, the input must be less than or equal to the + * threshold. + * @returns A new struct that will only accept values below the threshold. + */ +function max(struct, threshold, options = {}) { + const { exclusive } = options; + return refine(struct, 'max', (value) => { + return exclusive + ? value < threshold + : value <= threshold || + `Expected a ${struct.type} less than ${exclusive ? '' : 'or equal to ' + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + }${threshold} but received \`${value}\``; + }); +} +exports.max = max; +/** + * Ensure that a number or date is above a threshold. + * + * @param struct - The struct to augment. + * @param threshold - The minimum value that the input can be. + * @param options - An optional options object. + * @param options.exclusive - When `true`, the input must be strictly greater + * than the threshold. When `false`, the input must be greater than or equal to + * the threshold. + * @returns A new struct that will only accept values above the threshold. + */ +function min(struct, threshold, options = {}) { + const { exclusive } = options; + return refine(struct, 'min', (value) => { + return exclusive + ? value > threshold + : value >= threshold || + `Expected a ${struct.type} greater than ${exclusive ? '' : 'or equal to ' + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + }${threshold} but received \`${value}\``; + }); +} +exports.min = min; +/** + * Ensure that a string, array, map or set is not empty. + * + * @param struct - The struct to augment. + * @returns A new struct that will only accept non-empty values. + */ +function nonempty(struct) { + return refine(struct, 'nonempty', (value) => { + // eslint-disable-next-line @typescript-eslint/no-shadow + const size = getSize(value); + return (size > 0 || `Expected a nonempty ${struct.type} but received an empty one`); + }); +} +exports.nonempty = nonempty; +/** + * Ensure that a string matches a regular expression. + * + * @param struct - The struct to augment. + * @param regexp - The regular expression to match against. + * @returns A new struct that will only accept strings matching the regular + * expression. + */ +function pattern(struct, regexp) { + return refine(struct, 'pattern', (value) => { + return (regexp.test(value) || + `Expected a ${struct.type} matching \`/${regexp.source}/\` but received "${value}"`); + }); +} +exports.pattern = pattern; +/** + * Ensure that a string, array, number, date, map, or set has a size (or length, + * or time) between `min` and `max`. + * + * @param struct - The struct to augment. + * @param minimum - The minimum size that the input can be. + * @param maximum - The maximum size that the input can be. + * @returns A new struct that will only accept values within the given size + * range. + */ +function size(struct, minimum, maximum = minimum) { + const expected = `Expected a ${struct.type}`; + const of = minimum === maximum + ? `of \`${minimum}\`` + : `between \`${minimum}\` and \`${maximum}\``; + return refine(struct, 'size', (value) => { + if (typeof value === 'number' || value instanceof Date) { + return ((minimum <= value && value <= maximum) || + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + `${expected} ${of} but received \`${value}\``); + } + else if (value instanceof Map || value instanceof Set) { + // eslint-disable-next-line @typescript-eslint/no-shadow + const { size } = value; + return ((minimum <= size && size <= maximum) || + `${expected} with a size ${of} but received one with a size of \`${size}\``); + } + const { length } = value; + return ((minimum <= length && length <= maximum) || + `${expected} with a length ${of} but received one with a length of \`${length}\``); + }); +} +exports.size = size; +/** + * Augment a `Struct` to add an additional refinement to the validation. + * + * The refiner function is guaranteed to receive a value of the struct's type, + * because the struct's existing validation will already have passed. This + * allows you to layer additional validation on top of existing structs. + * + * @param struct - The struct to augment. + * @param name - The name of the refinement. + * @param refiner - The refiner function. + * @returns A new struct that will run the refiner function after the existing + * validation. + */ +function refine(struct, name, refiner) { + return new struct_js_1.Struct({ + ...struct, + *refiner(value, ctx) { + yield* struct.refiner(value, ctx); + const result = refiner(value, ctx); + const failures = (0, utils_js_1.toFailures)(result, ctx, struct, value); + for (const failure of failures) { + yield { ...failure, refinement: name }; + } + }, + }); +} +exports.refine = refine; +//# sourceMappingURL=refinements.cjs.map + +/***/ }), + +/***/ 67792: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.unknown = exports.union = exports.type = exports.tuple = exports.string = exports.set = exports.regexp = exports.record = exports.optional = exports.object = exports.number = exports.nullable = exports.never = exports.map = exports.literal = exports.intersection = exports.integer = exports.instance = exports.func = exports.enums = exports.date = exports.boolean = exports.bigint = exports.array = exports.any = void 0; +const struct_js_1 = __webpack_require__(99067); +const utils_js_1 = __webpack_require__(70639); +const utilities_js_1 = __webpack_require__(65991); +/** + * Ensure that any value passes validation. + * + * @returns A struct that will always pass validation. + */ +function any() { + return (0, utilities_js_1.define)('any', () => true); +} +exports.any = any; +/** + * Ensure that a value is an array and that its elements are of a specific type. + * + * Note: If you omit the element struct, the arrays elements will not be + * iterated at all. This can be helpful for cases where performance is critical, + * and it is preferred to using `array(any())`. + * + * @param Element - The struct to validate each element in the array against. + * @returns A new struct that will only accept arrays of the given type. + */ +function array(Element) { + return new struct_js_1.Struct({ + type: 'array', + schema: Element, + *entries(value) { + if (Element && Array.isArray(value)) { + for (const [index, arrayValue] of value.entries()) { + yield [index, arrayValue, Element]; + } + } + }, + coercer(value) { + return Array.isArray(value) ? value.slice() : value; + }, + validator(value) { + return (Array.isArray(value) || + `Expected an array value, but received: ${(0, utils_js_1.print)(value)}`); + }, + }); +} +exports.array = array; +/** + * Ensure that a value is a bigint. + * + * @returns A new struct that will only accept bigints. + */ +function bigint() { + return (0, utilities_js_1.define)('bigint', (value) => { + return typeof value === 'bigint'; + }); +} +exports.bigint = bigint; +/** + * Ensure that a value is a boolean. + * + * @returns A new struct that will only accept booleans. + */ +function boolean() { + return (0, utilities_js_1.define)('boolean', (value) => { + return typeof value === 'boolean'; + }); +} +exports.boolean = boolean; +/** + * Ensure that a value is a valid `Date`. + * + * Note: this also ensures that the value is *not* an invalid `Date` object, + * which can occur when parsing a date fails but still returns a `Date`. + * + * @returns A new struct that will only accept valid `Date` objects. + */ +function date() { + return (0, utilities_js_1.define)('date', (value) => { + return ((value instanceof Date && !isNaN(value.getTime())) || + `Expected a valid \`Date\` object, but received: ${(0, utils_js_1.print)(value)}`); + }); +} +exports.date = date; +/** + * Ensure that a value is one of a set of potential values. + * + * Note: after creating the struct, you can access the definition of the + * potential values as `struct.schema`. + * + * @param values - The potential values that the input can be. + * @returns A new struct that will only accept the given values. + */ +function enums(values) { + const schema = {}; + const description = values.map((value) => (0, utils_js_1.print)(value)).join(); + for (const key of values) { + schema[key] = key; + } + return new struct_js_1.Struct({ + type: 'enums', + schema, + validator(value) { + return (values.includes(value) || + `Expected one of \`${description}\`, but received: ${(0, utils_js_1.print)(value)}`); + }, + }); +} +exports.enums = enums; +/** + * Ensure that a value is a function. + * + * @returns A new struct that will only accept functions. + */ +// eslint-disable-next-line @typescript-eslint/ban-types +function func() { + return (0, utilities_js_1.define)('func', (value) => { + return (typeof value === 'function' || + `Expected a function, but received: ${(0, utils_js_1.print)(value)}`); + }); +} +exports.func = func; +/** + * Ensure that a value is an instance of a specific class. + * + * @param Class - The class that the value must be an instance of. + * @returns A new struct that will only accept instances of the given class. + */ +function instance(Class) { + return (0, utilities_js_1.define)('instance', (value) => { + return (value instanceof Class || + `Expected a \`${Class.name}\` instance, but received: ${(0, utils_js_1.print)(value)}`); + }); +} +exports.instance = instance; +/** + * Ensure that a value is an integer. + * + * @returns A new struct that will only accept integers. + */ +function integer() { + return (0, utilities_js_1.define)('integer', (value) => { + return ((typeof value === 'number' && !isNaN(value) && Number.isInteger(value)) || + `Expected an integer, but received: ${(0, utils_js_1.print)(value)}`); + }); +} +exports.integer = integer; +/** + * Ensure that a value matches all of a set of types. + * + * @param Structs - The set of structs that the value must match. + * @returns A new struct that will only accept values that match all of the + * given structs. + */ +function intersection(Structs) { + return new struct_js_1.Struct({ + type: 'intersection', + schema: null, + *entries(value, context) { + for (const { entries } of Structs) { + yield* entries(value, context); + } + }, + *validator(value, context) { + for (const { validator } of Structs) { + yield* validator(value, context); + } + }, + *refiner(value, context) { + for (const { refiner } of Structs) { + yield* refiner(value, context); + } + }, + }); +} +exports.intersection = intersection; +/** + * Ensure that a value is an exact value, using `===` for comparison. + * + * @param constant - The exact value that the input must be. + * @returns A new struct that will only accept the exact given value. + */ +function literal(constant) { + const description = (0, utils_js_1.print)(constant); + const valueType = typeof constant; + return new struct_js_1.Struct({ + type: 'literal', + schema: valueType === 'string' || + valueType === 'number' || + valueType === 'boolean' + ? constant + : null, + validator(value) { + return (value === constant || + `Expected the literal \`${description}\`, but received: ${(0, utils_js_1.print)(value)}`); + }, + }); +} +exports.literal = literal; +/** + * Ensure that a value is a `Map` object, and that its keys and values are of + * specific types. + * + * @param Key - The struct to validate each key in the map against. + * @param Value - The struct to validate each value in the map against. + * @returns A new struct that will only accept `Map` objects. + */ +function map(Key, Value) { + return new struct_js_1.Struct({ + type: 'map', + schema: null, + *entries(value) { + if (Key && Value && value instanceof Map) { + for (const [mapKey, mapValue] of value.entries()) { + yield [mapKey, mapKey, Key]; + yield [mapKey, mapValue, Value]; + } + } + }, + coercer(value) { + return value instanceof Map ? new Map(value) : value; + }, + validator(value) { + return (value instanceof Map || + `Expected a \`Map\` object, but received: ${(0, utils_js_1.print)(value)}`); + }, + }); +} +exports.map = map; +/** + * Ensure that no value ever passes validation. + * + * @returns A new struct that will never pass validation. + */ +function never() { + return (0, utilities_js_1.define)('never', () => false); +} +exports.never = never; +/** + * Augment an existing struct to allow `null` values. + * + * @param struct - The struct to augment. + * @returns A new struct that will accept `null` values. + */ +function nullable(struct) { + return new struct_js_1.Struct({ + ...struct, + validator: (value, ctx) => value === null || struct.validator(value, ctx), + refiner: (value, ctx) => value === null || struct.refiner(value, ctx), + }); +} +exports.nullable = nullable; +/** + * Ensure that a value is a number. + * + * @returns A new struct that will only accept numbers. + */ +function number() { + return (0, utilities_js_1.define)('number', (value) => { + return ((typeof value === 'number' && !isNaN(value)) || + `Expected a number, but received: ${(0, utils_js_1.print)(value)}`); + }); +} +exports.number = number; +/** + * Ensure that a value is an object, that it has a known set of properties, + * and that its properties are of specific types. + * + * Note: Unrecognized properties will fail validation. + * + * @param schema - An object that defines the structure of the object. + * @returns A new struct that will only accept objects. + */ +function object(schema) { + const knowns = schema ? Object.keys(schema) : []; + const Never = never(); + return new struct_js_1.Struct({ + type: 'object', + schema: schema ?? null, + *entries(value) { + if (schema && (0, utils_js_1.isObject)(value)) { + const unknowns = new Set(Object.keys(value)); + for (const key of knowns) { + unknowns.delete(key); + yield [key, value[key], schema[key]]; + } + for (const key of unknowns) { + yield [key, value[key], Never]; + } + } + }, + validator(value) { + return ((0, utils_js_1.isObject)(value) || `Expected an object, but received: ${(0, utils_js_1.print)(value)}`); + }, + coercer(value) { + return (0, utils_js_1.isObject)(value) ? { ...value } : value; + }, + }); +} +exports.object = object; +/** + * Augment a struct to allow `undefined` values. + * + * @param struct - The struct to augment. + * @returns A new struct that will accept `undefined` values. + */ +function optional(struct) { + return new struct_js_1.Struct({ + ...struct, + validator: (value, ctx) => value === undefined || struct.validator(value, ctx), + refiner: (value, ctx) => value === undefined || struct.refiner(value, ctx), + }); +} +exports.optional = optional; +/** + * Ensure that a value is an object with keys and values of specific types, but + * without ensuring any specific shape of properties. + * + * Like TypeScript's `Record` utility. + */ +/** + * Ensure that a value is an object with keys and values of specific types, but + * without ensuring any specific shape of properties. + * + * @param Key - The struct to validate each key in the record against. + * @param Value - The struct to validate each value in the record against. + * @returns A new struct that will only accept objects. + */ +function record(Key, Value) { + return new struct_js_1.Struct({ + type: 'record', + schema: null, + *entries(value) { + if ((0, utils_js_1.isObject)(value)) { + // eslint-disable-next-line guard-for-in + for (const objectKey in value) { + const objectValue = value[objectKey]; + yield [objectKey, objectKey, Key]; + yield [objectKey, objectValue, Value]; + } + } + }, + validator(value) { + return ((0, utils_js_1.isObject)(value) || `Expected an object, but received: ${(0, utils_js_1.print)(value)}`); + }, + }); +} +exports.record = record; +/** + * Ensure that a value is a `RegExp`. + * + * Note: this does not test the value against the regular expression! For that + * you need to use the `pattern()` refinement. + * + * @returns A new struct that will only accept `RegExp` objects. + */ +function regexp() { + return (0, utilities_js_1.define)('regexp', (value) => { + return value instanceof RegExp; + }); +} +exports.regexp = regexp; +/** + * Ensure that a value is a `Set` object, and that its elements are of a + * specific type. + * + * @param Element - The struct to validate each element in the set against. + * @returns A new struct that will only accept `Set` objects. + */ +function set(Element) { + return new struct_js_1.Struct({ + type: 'set', + schema: null, + *entries(value) { + if (Element && value instanceof Set) { + for (const setValue of value) { + yield [setValue, setValue, Element]; + } + } + }, + coercer(value) { + return value instanceof Set ? new Set(value) : value; + }, + validator(value) { + return (value instanceof Set || + `Expected a \`Set\` object, but received: ${(0, utils_js_1.print)(value)}`); + }, + }); +} +exports.set = set; +/** + * Ensure that a value is a string. + * + * @returns A new struct that will only accept strings. + */ +function string() { + return (0, utilities_js_1.define)('string', (value) => { + return (typeof value === 'string' || + `Expected a string, but received: ${(0, utils_js_1.print)(value)}`); + }); +} +exports.string = string; +/** + * Ensure that a value is a tuple of a specific length, and that each of its + * elements is of a specific type. + * + * @param Structs - The set of structs that the value must match. + * @returns A new struct that will only accept tuples of the given types. + */ +function tuple(Structs) { + const Never = never(); + return new struct_js_1.Struct({ + type: 'tuple', + schema: null, + *entries(value) { + if (Array.isArray(value)) { + const length = Math.max(Structs.length, value.length); + for (let i = 0; i < length; i++) { + yield [i, value[i], Structs[i] || Never]; + } + } + }, + validator(value) { + return (Array.isArray(value) || + `Expected an array, but received: ${(0, utils_js_1.print)(value)}`); + }, + }); +} +exports.tuple = tuple; +/** + * Ensure that a value has a set of known properties of specific types. + * + * Note: Unrecognized properties are allowed and untouched. This is similar to + * how TypeScript's structural typing works. + * + * @param schema - An object that defines the structure of the object. + * @returns A new struct that will only accept objects. + */ +function type(schema) { + const keys = Object.keys(schema); + return new struct_js_1.Struct({ + type: 'type', + schema, + *entries(value) { + if ((0, utils_js_1.isObject)(value)) { + for (const k of keys) { + yield [k, value[k], schema[k]]; + } + } + }, + validator(value) { + return ((0, utils_js_1.isObject)(value) || `Expected an object, but received: ${(0, utils_js_1.print)(value)}`); + }, + coercer(value) { + return (0, utils_js_1.isObject)(value) ? { ...value } : value; + }, + }); +} +exports.type = type; +/** + * Ensure that a value matches one of a set of types. + * + * @param Structs - The set of structs that the value must match. + * @returns A new struct that will only accept values that match one of the + * given structs. + */ +function union(Structs) { + const description = Structs.map((struct) => struct.type).join(' | '); + return new struct_js_1.Struct({ + type: 'union', + schema: null, + coercer(value) { + for (const InnerStruct of Structs) { + const [error, coerced] = InnerStruct.validate(value, { coerce: true }); + if (!error) { + return coerced; + } + } + return value; + }, + validator(value, ctx) { + const failures = []; + for (const InnerStruct of Structs) { + const [...tuples] = (0, utils_js_1.run)(value, InnerStruct, ctx); + const [first] = tuples; + if (!first?.[0]) { + return []; + } + for (const [failure] of tuples) { + if (failure) { + failures.push(failure); + } + } + } + return [ + `Expected the value to satisfy a union of \`${description}\`, but received: ${(0, utils_js_1.print)(value)}`, + ...failures, + ]; + }, + }); +} +exports.union = union; +/** + * Ensure that any value passes validation, without widening its type to `any`. + * + * @returns A struct that will always pass validation. + */ +function unknown() { + return (0, utilities_js_1.define)('unknown', () => true); +} +exports.unknown = unknown; +//# sourceMappingURL=types.cjs.map + +/***/ }), + +/***/ 65991: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.pick = exports.partial = exports.omit = exports.lazy = exports.dynamic = exports.deprecated = exports.define = exports.assign = void 0; +const struct_js_1 = __webpack_require__(99067); +const types_js_1 = __webpack_require__(67792); +/** + * Create a new struct that combines the properties from multiple object or type + * structs. Its return type will match the first parameter's type. + * + * @param Structs - The structs to combine. + * @returns A new struct that combines the properties of the input structs. + */ +function assign(...Structs) { + const isType = Structs[0]?.type === 'type'; + const schemas = Structs.map(({ schema }) => schema); + const schema = Object.assign({}, ...schemas); + return isType ? (0, types_js_1.type)(schema) : (0, types_js_1.object)(schema); +} +exports.assign = assign; +/** + * Define a new struct type with a custom validation function. + * + * @param name - The name of the struct type. + * @param validator - The validation function. + * @returns A new struct type. + */ +function define(name, validator) { + return new struct_js_1.Struct({ type: name, schema: null, validator }); +} +exports.define = define; +/** + * Create a new struct based on an existing struct, but the value is allowed to + * be `undefined`. `log` will be called if the value is not `undefined`. + * + * @param struct - The struct to augment. + * @param log - The function to call when the value is not `undefined`. + * @returns A new struct that will only accept `undefined` or values that pass + * the input struct. + */ +function deprecated(struct, log) { + return new struct_js_1.Struct({ + ...struct, + refiner: (value, ctx) => value === undefined || struct.refiner(value, ctx), + validator(value, ctx) { + if (value === undefined) { + return true; + } + log(value, ctx); + return struct.validator(value, ctx); + }, + }); +} +exports.deprecated = deprecated; +/** + * Create a struct with dynamic validation logic. + * + * The callback will receive the value currently being validated, and must + * return a struct object to validate it with. This can be useful to model + * validation logic that changes based on its input. + * + * @param fn - The callback to create the struct. + * @returns A new struct with dynamic validation logic. + */ +function dynamic(fn) { + return new struct_js_1.Struct({ + type: 'dynamic', + schema: null, + *entries(value, ctx) { + const struct = fn(value, ctx); + yield* struct.entries(value, ctx); + }, + validator(value, ctx) { + const struct = fn(value, ctx); + return struct.validator(value, ctx); + }, + coercer(value, ctx) { + const struct = fn(value, ctx); + return struct.coercer(value, ctx); + }, + refiner(value, ctx) { + const struct = fn(value, ctx); + return struct.refiner(value, ctx); + }, + }); +} +exports.dynamic = dynamic; +/** + * Create a struct with lazily evaluated validation logic. + * + * The first time validation is run with the struct, the callback will be called + * and must return a struct object to use. This is useful for cases where you + * want to have self-referential structs for nested data structures to avoid a + * circular definition problem. + * + * @param fn - The callback to create the struct. + * @returns A new struct with lazily evaluated validation logic. + */ +function lazy(fn) { + let struct; + return new struct_js_1.Struct({ + type: 'lazy', + schema: null, + *entries(value, ctx) { + struct ?? (struct = fn()); + yield* struct.entries(value, ctx); + }, + validator(value, ctx) { + struct ?? (struct = fn()); + return struct.validator(value, ctx); + }, + coercer(value, ctx) { + struct ?? (struct = fn()); + return struct.coercer(value, ctx); + }, + refiner(value, ctx) { + struct ?? (struct = fn()); + return struct.refiner(value, ctx); + }, + }); +} +exports.lazy = lazy; +/** + * Create a new struct based on an existing object struct, but excluding + * specific properties. + * + * Like TypeScript's `Omit` utility. + * + * @param struct - The struct to augment. + * @param keys - The keys to omit. + * @returns A new struct that will not accept the input keys. + */ +function omit(struct, keys) { + const { schema } = struct; + const subschema = { ...schema }; + for (const key of keys) { + delete subschema[key]; + } + switch (struct.type) { + case 'type': + return (0, types_js_1.type)(subschema); + default: + return (0, types_js_1.object)(subschema); + } +} +exports.omit = omit; +/** + * Create a new struct based on an existing object struct, but with all of its + * properties allowed to be `undefined`. + * + * Like TypeScript's `Partial` utility. + * + * @param struct - The struct to augment. + * @returns A new struct that will accept the input keys as `undefined`. + */ +function partial(struct) { + const isStruct = struct instanceof struct_js_1.Struct; + const schema = isStruct ? { ...struct.schema } : { ...struct }; + // eslint-disable-next-line guard-for-in + for (const key in schema) { + schema[key] = (0, types_js_1.optional)(schema[key]); + } + if (isStruct && struct.type === 'type') { + return (0, types_js_1.type)(schema); + } + return (0, types_js_1.object)(schema); +} +exports.partial = partial; +/** + * Create a new struct based on an existing object struct, but only including + * specific properties. + * + * Like TypeScript's `Pick` utility. + * + * @param struct - The struct to augment. + * @param keys - The keys to pick. + * @returns A new struct that will only accept the input keys. + */ +function pick(struct, keys) { + const { schema } = struct; + const subschema = {}; + for (const key of keys) { + subschema[key] = schema[key]; + } + switch (struct.type) { + case 'type': + return (0, types_js_1.type)(subschema); + default: + return (0, types_js_1.object)(subschema); + } +} +exports.pick = pick; +//# sourceMappingURL=utilities.cjs.map + +/***/ }), + +/***/ 70639: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.run = exports.toFailures = exports.toFailure = exports.shiftIterator = exports.print = exports.isPlainObject = exports.isObject = void 0; +/** + * Check if a value is an iterator. + * + * @param value - The value to check. + * @returns Whether the value is an iterator. + */ +function isIterable(value) { + return isObject(value) && typeof value[Symbol.iterator] === 'function'; +} +/** + * Check if a value is a plain object. + * + * @param value - The value to check. + * @returns Whether the value is a plain object. + */ +function isObject(value) { + return typeof value === 'object' && value !== null; +} +exports.isObject = isObject; +/** + * Check if a value is a plain object. + * + * @param value - The value to check. + * @returns Whether the value is a plain object. + */ +function isPlainObject(value) { + if (Object.prototype.toString.call(value) !== '[object Object]') { + return false; + } + const prototype = Object.getPrototypeOf(value); + return prototype === null || prototype === Object.prototype; +} +exports.isPlainObject = isPlainObject; +/** + * Return a value as a printable string. + * + * @param value - The value to print. + * @returns The value as a string. + */ +function print(value) { + if (typeof value === 'symbol') { + return value.toString(); + } + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + return typeof value === 'string' ? JSON.stringify(value) : `${value}`; +} +exports.print = print; +/** + * Shift (remove and return) the first value from the `input` iterator. + * Like `Array.prototype.shift()` but for an `Iterator`. + * + * @param input - The iterator to shift. + * @returns The first value of the iterator, or `undefined` if the iterator is + * empty. + */ +function shiftIterator(input) { + const { done, value } = input.next(); + return done ? undefined : value; +} +exports.shiftIterator = shiftIterator; +/** + * Convert a single validation result to a failure. + * + * @param result - The result to convert. + * @param context - The context of the validation. + * @param struct - The struct being validated. + * @param value - The value being validated. + * @returns A failure if the result is a failure, or `undefined` if the result + * is a success. + */ +function toFailure(result, context, struct, value) { + if (result === true) { + return undefined; + } + else if (result === false) { + // eslint-disable-next-line no-param-reassign + result = {}; + } + else if (typeof result === 'string') { + // eslint-disable-next-line no-param-reassign + result = { message: result }; + } + const { path, branch } = context; + const { type } = struct; + const { refinement, message = `Expected a value of type \`${type}\`${refinement ? ` with refinement \`${refinement}\`` : ''}, but received: \`${print(value)}\``, } = result; + return { + value, + type, + refinement, + key: path[path.length - 1], + path, + branch, + ...result, + message, + }; +} +exports.toFailure = toFailure; +/** + * Convert a validation result to an iterable of failures. + * + * @param result - The result to convert. + * @param context - The context of the validation. + * @param struct - The struct being validated. + * @param value - The value being validated. + * @yields The failures. + * @returns An iterable of failures. + */ +function* toFailures(result, context, struct, value) { + if (!isIterable(result)) { + // eslint-disable-next-line no-param-reassign + result = [result]; + } + for (const validationResult of result) { + const failure = toFailure(validationResult, context, struct, value); + if (failure) { + yield failure; + } + } +} +exports.toFailures = toFailures; +/** + * Check a value against a struct, traversing deeply into nested values, and + * returning an iterator of failures or success. + * + * @param value - The value to check. + * @param struct - The struct to check against. + * @param options - Optional settings. + * @param options.path - The path to the value in the input data. + * @param options.branch - The branch of the value in the input data. + * @param options.coerce - Whether to coerce the value before validating it. + * @param options.mask - Whether to mask the value before validating it. + * @param options.message - An optional message to include in the error. + * @yields An iterator of failures or success. + * @returns An iterator of failures or success. + */ +function* run(value, struct, options = {}) { + const { path = [], branch = [value], coerce = false, mask = false } = options; + const context = { path, branch }; + if (coerce) { + // eslint-disable-next-line no-param-reassign + value = struct.coercer(value, context); + if (mask && + struct.type !== 'type' && + isObject(struct.schema) && + isObject(value) && + !Array.isArray(value)) { + for (const key in value) { + if (struct.schema[key] === undefined) { + delete value[key]; + } + } + } + } + let status = 'valid'; + for (const failure of struct.validator(value, context)) { + failure.explanation = options.message; + status = 'not_valid'; + yield [failure, undefined]; + } + // eslint-disable-next-line prefer-const + for (let [innerKey, innerValue, innerStruct] of struct.entries(value, context)) { + const iterable = run(innerValue, innerStruct, { + path: innerKey === undefined ? path : [...path, innerKey], + branch: innerKey === undefined ? branch : [...branch, innerValue], + coerce, + mask, + message: options.message, + }); + for (const result of iterable) { + if (result[0]) { + status = + result[0].refinement === null || result[0].refinement === undefined + ? 'not_valid' + : 'not_refined'; + yield [result[0], undefined]; + } + else if (coerce) { + innerValue = result[1]; + if (innerKey === undefined) { + // eslint-disable-next-line no-param-reassign + value = innerValue; + } + else if (value instanceof Map) { + value.set(innerKey, innerValue); + } + else if (value instanceof Set) { + value.add(innerValue); + } + else if (isObject(value)) { + if (innerValue !== undefined || innerKey in value) { + value[innerKey] = innerValue; + } + } + } + } + } + if (status !== 'not_valid') { + for (const failure of struct.refiner(value, context)) { + failure.explanation = options.message; + status = 'not_refined'; + yield [failure, undefined]; + } + } + if (status === 'valid') { + yield [undefined, value]; + } +} +exports.run = run; +//# sourceMappingURL=utils.cjs.map + +/***/ }), + +/***/ 22011: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.assertExhaustive = exports.assertStruct = exports.assert = exports.AssertionError = void 0; +const superstruct_1 = __webpack_require__(35620); +const errors_1 = __webpack_require__(75940); +/** + * Check if a value is a constructor, i.e., a function that can be called with + * the `new` keyword. + * + * @param fn - The value to check. + * @returns `true` if the value is a constructor, or `false` otherwise. + */ +function isConstructable(fn) { + /* istanbul ignore next */ + return Boolean(typeof fn?.prototype?.constructor?.name === 'string'); +} +/** + * Attempts to obtain the message from a possible error object. If it is + * possible to do so, any trailing period will be removed from the message; + * otherwise an empty string is returned. + * + * @param error - The error object to get the message from. + * @returns The message without any trailing period if `error` is an object + * with a `message` property; the string version of `error` without any trailing + * period if it is not `undefined` or `null`; otherwise an empty string. + */ +function getErrorMessageWithoutTrailingPeriod(error) { + // We'll add our own period. + return (0, errors_1.getErrorMessage)(error).replace(/\.$/u, ''); +} +/** + * Initialise an {@link AssertionErrorConstructor} error. + * + * @param ErrorWrapper - The error class to use. + * @param message - The error message. + * @returns The error object. + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +function getError(ErrorWrapper, message) { + if (isConstructable(ErrorWrapper)) { + return new ErrorWrapper({ + message, + }); + } + return ErrorWrapper({ + message, + }); +} +/** + * The default error class that is thrown if an assertion fails. + */ +class AssertionError extends Error { + constructor(options) { + super(options.message); + this.code = 'ERR_ASSERTION'; + } +} +exports.AssertionError = AssertionError; +/** + * Same as Node.js assert. + * If the value is falsy, throws an error, does nothing otherwise. + * + * @throws {@link AssertionError} If value is falsy. + * @param value - The test that should be truthy to pass. + * @param message - Message to be passed to {@link AssertionError} or an + * {@link Error} instance to throw. + * @param ErrorWrapper - The error class to throw if the assertion fails. + * Defaults to {@link AssertionError}. If a custom error class is provided for + * the `message` argument, this argument is ignored. + */ +function assert(value, message = 'Assertion failed.', +// eslint-disable-next-line @typescript-eslint/naming-convention +ErrorWrapper = AssertionError) { + if (!value) { + if (message instanceof Error) { + throw message; + } + throw getError(ErrorWrapper, message); + } +} +exports.assert = assert; +/** + * Assert a value against a Superstruct struct. + * + * @param value - The value to validate. + * @param struct - The struct to validate against. + * @param errorPrefix - A prefix to add to the error message. Defaults to + * "Assertion failed". + * @param ErrorWrapper - The error class to throw if the assertion fails. + * Defaults to {@link AssertionError}. + * @throws If the value is not valid. + */ +function assertStruct(value, struct, errorPrefix = 'Assertion failed', +// eslint-disable-next-line @typescript-eslint/naming-convention +ErrorWrapper = AssertionError) { + try { + (0, superstruct_1.assert)(value, struct); + } + catch (error) { + throw getError(ErrorWrapper, `${errorPrefix}: ${getErrorMessageWithoutTrailingPeriod(error)}.`); + } +} +exports.assertStruct = assertStruct; +/** + * Use in the default case of a switch that you want to be fully exhaustive. + * Using this function forces the compiler to enforce exhaustivity during + * compile-time. + * + * @example + * ``` + * const number = 1; + * switch (number) { + * case 0: + * ... + * case 1: + * ... + * default: + * assertExhaustive(snapPrefix); + * } + * ``` + * @param _object - The object on which the switch is being operated. + */ +function assertExhaustive(_object) { + throw new Error('Invalid branch reached. Should be detected during compilation.'); +} +exports.assertExhaustive = assertExhaustive; +//# sourceMappingURL=assert.cjs.map + +/***/ }), + +/***/ 20472: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.base64 = void 0; +const superstruct_1 = __webpack_require__(35620); +const assert_1 = __webpack_require__(22011); +/** + * Ensure that a provided string-based struct is valid base64. + * + * @param struct - The string based struct. + * @param options - Optional options to specialize base64 validation. See {@link Base64Options} documentation. + * @returns A superstruct validating base64. + */ +const base64 = (struct, options = {}) => { + const paddingRequired = options.paddingRequired ?? false; + const characterSet = options.characterSet ?? 'base64'; + let letters; + if (characterSet === 'base64') { + letters = String.raw `[A-Za-z0-9+\/]`; + } + else { + (0, assert_1.assert)(characterSet === 'base64url'); + letters = String.raw `[-_A-Za-z0-9]`; + } + let re; + if (paddingRequired) { + re = new RegExp(`^(?:${letters}{4})*(?:${letters}{3}=|${letters}{2}==)?$`, 'u'); + } + else { + re = new RegExp(`^(?:${letters}{4})*(?:${letters}{2,3}|${letters}{3}=|${letters}{2}==)?$`, 'u'); + } + return (0, superstruct_1.pattern)(struct, re); +}; +exports.base64 = base64; +//# sourceMappingURL=base64.cjs.map + +/***/ }), + +/***/ 77862: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createDataView = exports.concatBytes = exports.valueToBytes = exports.base64ToBytes = exports.stringToBytes = exports.numberToBytes = exports.signedBigIntToBytes = exports.bigIntToBytes = exports.hexToBytes = exports.bytesToBase64 = exports.bytesToString = exports.bytesToNumber = exports.bytesToSignedBigInt = exports.bytesToBigInt = exports.bytesToHex = exports.assertIsBytes = exports.isBytes = void 0; +const base_1 = __webpack_require__(63203); +const assert_1 = __webpack_require__(22011); +const hex_1 = __webpack_require__(93976); +// '0'.charCodeAt(0) === 48 +const HEX_MINIMUM_NUMBER_CHARACTER = 48; +// '9'.charCodeAt(0) === 57 +const HEX_MAXIMUM_NUMBER_CHARACTER = 58; +const HEX_CHARACTER_OFFSET = 87; +/** + * Memoized function that returns an array to be used as a lookup table for + * converting bytes to hexadecimal values. + * + * The array is created lazily and then cached for future use. The benefit of + * this approach is that the performance of converting bytes to hex is much + * better than if we were to call `toString(16)` on each byte. + * + * The downside is that the array is created once and then never garbage + * collected. This is not a problem in practice because the array is only 256 + * elements long. + * + * @returns A function that returns the lookup table. + */ +function getPrecomputedHexValuesBuilder() { + // To avoid issues with tree shaking, we need to use a function to return the + // array. This is because the array is only used in the `bytesToHex` function + // and if we were to use a global variable, the array might be removed by the + // tree shaker. + const lookupTable = []; + return () => { + if (lookupTable.length === 0) { + for (let i = 0; i < 256; i++) { + lookupTable.push(i.toString(16).padStart(2, '0')); + } + } + return lookupTable; + }; +} +/** + * Function implementation of the {@link getPrecomputedHexValuesBuilder} + * function. + */ +const getPrecomputedHexValues = getPrecomputedHexValuesBuilder(); +/** + * Check if a value is a `Uint8Array`. + * + * @param value - The value to check. + * @returns Whether the value is a `Uint8Array`. + */ +function isBytes(value) { + return value instanceof Uint8Array; +} +exports.isBytes = isBytes; +/** + * Assert that a value is a `Uint8Array`. + * + * @param value - The value to check. + * @throws If the value is not a `Uint8Array`. + */ +function assertIsBytes(value) { + (0, assert_1.assert)(isBytes(value), 'Value must be a Uint8Array.'); +} +exports.assertIsBytes = assertIsBytes; +/** + * Convert a `Uint8Array` to a hexadecimal string. + * + * @param bytes - The bytes to convert to a hexadecimal string. + * @returns The hexadecimal string. + */ +function bytesToHex(bytes) { + assertIsBytes(bytes); + if (bytes.length === 0) { + return '0x'; + } + const lookupTable = getPrecomputedHexValues(); + const hexadecimal = new Array(bytes.length); + for (let i = 0; i < bytes.length; i++) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + hexadecimal[i] = lookupTable[bytes[i]]; + } + return (0, hex_1.add0x)(hexadecimal.join('')); +} +exports.bytesToHex = bytesToHex; +/** + * Convert a `Uint8Array` to a `bigint`. + * + * To convert a `Uint8Array` to a `number` instead, use {@link bytesToNumber}. + * To convert a two's complement encoded `Uint8Array` to a `bigint`, use + * {@link bytesToSignedBigInt}. + * + * @param bytes - The bytes to convert to a `bigint`. + * @returns The `bigint`. + */ +function bytesToBigInt(bytes) { + assertIsBytes(bytes); + const hexadecimal = bytesToHex(bytes); + return BigInt(hexadecimal); +} +exports.bytesToBigInt = bytesToBigInt; +/** + * Convert a `Uint8Array` to a signed `bigint`. This assumes that the bytes are + * encoded in two's complement. + * + * To convert a `Uint8Array` to an unsigned `bigint` instead, use + * {@link bytesToBigInt}. + * + * @see https://en.wikipedia.org/wiki/Two%27s_complement + * @param bytes - The bytes to convert to a signed `bigint`. + * @returns The signed `bigint`. + */ +function bytesToSignedBigInt(bytes) { + assertIsBytes(bytes); + let value = BigInt(0); + for (const byte of bytes) { + // eslint-disable-next-line no-bitwise + value = (value << BigInt(8)) + BigInt(byte); + } + return BigInt.asIntN(bytes.length * 8, value); +} +exports.bytesToSignedBigInt = bytesToSignedBigInt; +/** + * Convert a `Uint8Array` to a `number`. + * + * To convert a `Uint8Array` to a `bigint` instead, use {@link bytesToBigInt}. + * + * @param bytes - The bytes to convert to a number. + * @returns The number. + * @throws If the resulting number is not a safe integer. + */ +function bytesToNumber(bytes) { + assertIsBytes(bytes); + const bigint = bytesToBigInt(bytes); + (0, assert_1.assert)(bigint <= BigInt(Number.MAX_SAFE_INTEGER), 'Number is not a safe integer. Use `bytesToBigInt` instead.'); + return Number(bigint); +} +exports.bytesToNumber = bytesToNumber; +/** + * Convert a UTF-8 encoded `Uint8Array` to a `string`. + * + * @param bytes - The bytes to convert to a string. + * @returns The string. + */ +function bytesToString(bytes) { + assertIsBytes(bytes); + return new TextDecoder().decode(bytes); +} +exports.bytesToString = bytesToString; +/** + * Convert a `Uint8Array` to a base64 encoded string. + * + * @param bytes - The bytes to convert to a base64 encoded string. + * @returns The base64 encoded string. + */ +function bytesToBase64(bytes) { + assertIsBytes(bytes); + return base_1.base64.encode(bytes); +} +exports.bytesToBase64 = bytesToBase64; +/** + * Convert a hexadecimal string to a `Uint8Array`. The string can optionally be + * prefixed with `0x`. It accepts even and odd length strings. + * + * If the value is "0x", an empty `Uint8Array` is returned. + * + * @param value - The hexadecimal string to convert to bytes. + * @returns The bytes as `Uint8Array`. + */ +function hexToBytes(value) { + // "0x" is often used as empty byte array. + if (value?.toLowerCase?.() === '0x') { + return new Uint8Array(); + } + (0, hex_1.assertIsHexString)(value); + // Remove the `0x` prefix if it exists, and pad the string to have an even + // number of characters. + const strippedValue = (0, hex_1.remove0x)(value).toLowerCase(); + const normalizedValue = strippedValue.length % 2 === 0 ? strippedValue : `0${strippedValue}`; + const bytes = new Uint8Array(normalizedValue.length / 2); + for (let i = 0; i < bytes.length; i++) { + // While this is not the prettiest way to convert a hexadecimal string to a + // `Uint8Array`, it is a lot faster than using `parseInt` to convert each + // character. + const c1 = normalizedValue.charCodeAt(i * 2); + const c2 = normalizedValue.charCodeAt(i * 2 + 1); + const n1 = c1 - + (c1 < HEX_MAXIMUM_NUMBER_CHARACTER + ? HEX_MINIMUM_NUMBER_CHARACTER + : HEX_CHARACTER_OFFSET); + const n2 = c2 - + (c2 < HEX_MAXIMUM_NUMBER_CHARACTER + ? HEX_MINIMUM_NUMBER_CHARACTER + : HEX_CHARACTER_OFFSET); + bytes[i] = n1 * 16 + n2; + } + return bytes; +} +exports.hexToBytes = hexToBytes; +/** + * Convert a `bigint` to a `Uint8Array`. + * + * This assumes that the `bigint` is an unsigned integer. To convert a signed + * `bigint` instead, use {@link signedBigIntToBytes}. + * + * @param value - The bigint to convert to bytes. + * @returns The bytes as `Uint8Array`. + */ +function bigIntToBytes(value) { + (0, assert_1.assert)(typeof value === 'bigint', 'Value must be a bigint.'); + (0, assert_1.assert)(value >= BigInt(0), 'Value must be a non-negative bigint.'); + const hexadecimal = value.toString(16); + return hexToBytes(hexadecimal); +} +exports.bigIntToBytes = bigIntToBytes; +/** + * Check if a `bigint` fits in a certain number of bytes. + * + * @param value - The `bigint` to check. + * @param bytes - The number of bytes. + * @returns Whether the `bigint` fits in the number of bytes. + */ +function bigIntFits(value, bytes) { + (0, assert_1.assert)(bytes > 0); + /* eslint-disable no-bitwise */ + const mask = value >> BigInt(31); + return !(((~value & mask) + (value & ~mask)) >> BigInt(bytes * 8 + ~0)); + /* eslint-enable no-bitwise */ +} +/** + * Convert a signed `bigint` to a `Uint8Array`. This uses two's complement + * encoding to represent negative numbers. + * + * To convert an unsigned `bigint` to a `Uint8Array` instead, use + * {@link bigIntToBytes}. + * + * @see https://en.wikipedia.org/wiki/Two%27s_complement + * @param value - The number to convert to bytes. + * @param byteLength - The length of the resulting `Uint8Array`. If the number + * is larger than the maximum value that can be represented by the given length, + * an error is thrown. + * @returns The bytes as `Uint8Array`. + */ +function signedBigIntToBytes(value, byteLength) { + (0, assert_1.assert)(typeof value === 'bigint', 'Value must be a bigint.'); + (0, assert_1.assert)(typeof byteLength === 'number', 'Byte length must be a number.'); + (0, assert_1.assert)(byteLength > 0, 'Byte length must be greater than 0.'); + (0, assert_1.assert)(bigIntFits(value, byteLength), 'Byte length is too small to represent the given value.'); + // ESLint doesn't like mutating function parameters, so to avoid having to + // disable the rule, we create a new variable. + let numberValue = value; + const bytes = new Uint8Array(byteLength); + for (let i = 0; i < bytes.length; i++) { + bytes[i] = Number(BigInt.asUintN(8, numberValue)); + // eslint-disable-next-line no-bitwise + numberValue >>= BigInt(8); + } + return bytes.reverse(); +} +exports.signedBigIntToBytes = signedBigIntToBytes; +/** + * Convert a `number` to a `Uint8Array`. + * + * @param value - The number to convert to bytes. + * @returns The bytes as `Uint8Array`. + * @throws If the number is not a safe integer. + */ +function numberToBytes(value) { + (0, assert_1.assert)(typeof value === 'number', 'Value must be a number.'); + (0, assert_1.assert)(value >= 0, 'Value must be a non-negative number.'); + (0, assert_1.assert)(Number.isSafeInteger(value), 'Value is not a safe integer. Use `bigIntToBytes` instead.'); + const hexadecimal = value.toString(16); + return hexToBytes(hexadecimal); +} +exports.numberToBytes = numberToBytes; +/** + * Convert a `string` to a UTF-8 encoded `Uint8Array`. + * + * @param value - The string to convert to bytes. + * @returns The bytes as `Uint8Array`. + */ +function stringToBytes(value) { + (0, assert_1.assert)(typeof value === 'string', 'Value must be a string.'); + return new TextEncoder().encode(value); +} +exports.stringToBytes = stringToBytes; +/** + * Convert a base64 encoded string to a `Uint8Array`. + * + * @param value - The base64 encoded string to convert to bytes. + * @returns The bytes as `Uint8Array`. + */ +function base64ToBytes(value) { + (0, assert_1.assert)(typeof value === 'string', 'Value must be a string.'); + return base_1.base64.decode(value); +} +exports.base64ToBytes = base64ToBytes; +/** + * Convert a byte-like value to a `Uint8Array`. The value can be a `Uint8Array`, + * a `bigint`, a `number`, or a `string`. + * + * This will attempt to guess the type of the value based on its type and + * contents. For more control over the conversion, use the more specific + * conversion functions, such as {@link hexToBytes} or {@link stringToBytes}. + * + * If the value is a `string`, and it is prefixed with `0x`, it will be + * interpreted as a hexadecimal string. Otherwise, it will be interpreted as a + * UTF-8 string. To convert a hexadecimal string to bytes without interpreting + * it as a UTF-8 string, use {@link hexToBytes} instead. + * + * If the value is a `bigint`, it is assumed to be unsigned. To convert a signed + * `bigint` to bytes, use {@link signedBigIntToBytes} instead. + * + * If the value is a `Uint8Array`, it will be returned as-is. + * + * @param value - The value to convert to bytes. + * @returns The bytes as `Uint8Array`. + */ +function valueToBytes(value) { + if (typeof value === 'bigint') { + return bigIntToBytes(value); + } + if (typeof value === 'number') { + return numberToBytes(value); + } + if (typeof value === 'string') { + if (value.startsWith('0x')) { + return hexToBytes(value); + } + return stringToBytes(value); + } + if (isBytes(value)) { + return value; + } + throw new TypeError(`Unsupported value type: "${typeof value}".`); +} +exports.valueToBytes = valueToBytes; +/** + * Concatenate multiple byte-like values into a single `Uint8Array`. The values + * can be `Uint8Array`, `bigint`, `number`, or `string`. This uses + * {@link valueToBytes} under the hood to convert each value to bytes. Refer to + * the documentation of that function for more information. + * + * @param values - The values to concatenate. + * @returns The concatenated bytes as `Uint8Array`. + */ +function concatBytes(values) { + const normalizedValues = new Array(values.length); + let byteLength = 0; + for (let i = 0; i < values.length; i++) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const value = valueToBytes(values[i]); + normalizedValues[i] = value; + byteLength += value.length; + } + const bytes = new Uint8Array(byteLength); + for (let i = 0, offset = 0; i < normalizedValues.length; i++) { + // While we could simply spread the values into an array and use + // `Uint8Array.from`, that is a lot slower than using `Uint8Array.set`. + bytes.set(normalizedValues[i], offset); + offset += normalizedValues[i].length; + } + return bytes; +} +exports.concatBytes = concatBytes; +/** + * Create a {@link DataView} from a {@link Uint8Array}. This is a convenience + * function that avoids having to create a {@link DataView} manually, which + * requires passing the `byteOffset` and `byteLength` parameters every time. + * + * Not passing the `byteOffset` and `byteLength` parameters can result in + * unexpected behavior when the {@link Uint8Array} is a view of a larger + * {@link ArrayBuffer}, e.g., when using {@link Uint8Array.subarray}. + * + * This function also supports Node.js {@link Buffer}s. + * + * @example + * ```typescript + * const bytes = new Uint8Array([1, 2, 3]); + * + * // This is equivalent to: + * // const dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + * const dataView = createDataView(bytes); + * ``` + * @param bytes - The bytes to create the {@link DataView} from. + * @returns The {@link DataView}. + */ +function createDataView(bytes) { + // To maintain compatibility with Node.js, we need to check if the bytes are + // a Buffer. If so, we need to slice the buffer to get the underlying + // ArrayBuffer. + // eslint-disable-next-line no-restricted-globals + if (typeof Buffer !== 'undefined' && bytes instanceof Buffer) { + const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength); + return new DataView(buffer); + } + return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); +} +exports.createDataView = createDataView; +//# sourceMappingURL=bytes.cjs.map + +/***/ }), + +/***/ 87690: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toCaipChainId = exports.parseCaipAccountId = exports.parseCaipChainId = exports.isCaipAccountAddress = exports.isCaipAccountId = exports.isCaipReference = exports.isCaipNamespace = exports.isCaipChainId = exports.KnownCaipNamespace = exports.CaipAccountAddressStruct = exports.CaipAccountIdStruct = exports.CaipReferenceStruct = exports.CaipNamespaceStruct = exports.CaipChainIdStruct = exports.CAIP_ACCOUNT_ADDRESS_REGEX = exports.CAIP_ACCOUNT_ID_REGEX = exports.CAIP_REFERENCE_REGEX = exports.CAIP_NAMESPACE_REGEX = exports.CAIP_CHAIN_ID_REGEX = void 0; +const superstruct_1 = __webpack_require__(35620); +exports.CAIP_CHAIN_ID_REGEX = /^(?[-a-z0-9]{3,8}):(?[-_a-zA-Z0-9]{1,32})$/u; +exports.CAIP_NAMESPACE_REGEX = /^[-a-z0-9]{3,8}$/u; +exports.CAIP_REFERENCE_REGEX = /^[-_a-zA-Z0-9]{1,32}$/u; +exports.CAIP_ACCOUNT_ID_REGEX = /^(?(?[-a-z0-9]{3,8}):(?[-_a-zA-Z0-9]{1,32})):(?[-.%a-zA-Z0-9]{1,128})$/u; +exports.CAIP_ACCOUNT_ADDRESS_REGEX = /^[-.%a-zA-Z0-9]{1,128}$/u; +/** + * A CAIP-2 chain ID, i.e., a human-readable namespace and reference. + */ +exports.CaipChainIdStruct = (0, superstruct_1.pattern)((0, superstruct_1.string)(), exports.CAIP_CHAIN_ID_REGEX); +/** + * A CAIP-2 namespace, i.e., the first part of a CAIP chain ID. + */ +exports.CaipNamespaceStruct = (0, superstruct_1.pattern)((0, superstruct_1.string)(), exports.CAIP_NAMESPACE_REGEX); +/** + * A CAIP-2 reference, i.e., the second part of a CAIP chain ID. + */ +exports.CaipReferenceStruct = (0, superstruct_1.pattern)((0, superstruct_1.string)(), exports.CAIP_REFERENCE_REGEX); +/** + * A CAIP-10 account ID, i.e., a human-readable namespace, reference, and account address. + */ +exports.CaipAccountIdStruct = (0, superstruct_1.pattern)((0, superstruct_1.string)(), exports.CAIP_ACCOUNT_ID_REGEX); +/** + * A CAIP-10 account address, i.e., the third part of the CAIP account ID. + */ +exports.CaipAccountAddressStruct = (0, superstruct_1.pattern)((0, superstruct_1.string)(), exports.CAIP_ACCOUNT_ADDRESS_REGEX); +/** Known CAIP namespaces. */ +var KnownCaipNamespace; +(function (KnownCaipNamespace) { + /** EIP-155 compatible chains. */ + KnownCaipNamespace["Eip155"] = "eip155"; + KnownCaipNamespace["Wallet"] = "wallet"; +})(KnownCaipNamespace = exports.KnownCaipNamespace || (exports.KnownCaipNamespace = {})); +/** + * Check if the given value is a {@link CaipChainId}. + * + * @param value - The value to check. + * @returns Whether the value is a {@link CaipChainId}. + */ +function isCaipChainId(value) { + return (0, superstruct_1.is)(value, exports.CaipChainIdStruct); +} +exports.isCaipChainId = isCaipChainId; +/** + * Check if the given value is a {@link CaipNamespace}. + * + * @param value - The value to check. + * @returns Whether the value is a {@link CaipNamespace}. + */ +function isCaipNamespace(value) { + return (0, superstruct_1.is)(value, exports.CaipNamespaceStruct); +} +exports.isCaipNamespace = isCaipNamespace; +/** + * Check if the given value is a {@link CaipReference}. + * + * @param value - The value to check. + * @returns Whether the value is a {@link CaipReference}. + */ +function isCaipReference(value) { + return (0, superstruct_1.is)(value, exports.CaipReferenceStruct); +} +exports.isCaipReference = isCaipReference; +/** + * Check if the given value is a {@link CaipAccountId}. + * + * @param value - The value to check. + * @returns Whether the value is a {@link CaipAccountId}. + */ +function isCaipAccountId(value) { + return (0, superstruct_1.is)(value, exports.CaipAccountIdStruct); +} +exports.isCaipAccountId = isCaipAccountId; +/** + * Check if a value is a {@link CaipAccountAddress}. + * + * @param value - The value to validate. + * @returns True if the value is a valid {@link CaipAccountAddress}. + */ +function isCaipAccountAddress(value) { + return (0, superstruct_1.is)(value, exports.CaipAccountAddressStruct); +} +exports.isCaipAccountAddress = isCaipAccountAddress; +/** + * Parse a CAIP-2 chain ID to an object containing the namespace and reference. + * This validates the CAIP-2 chain ID before parsing it. + * + * @param caipChainId - The CAIP-2 chain ID to validate and parse. + * @returns The parsed CAIP-2 chain ID. + */ +function parseCaipChainId(caipChainId) { + const match = exports.CAIP_CHAIN_ID_REGEX.exec(caipChainId); + if (!match?.groups) { + throw new Error('Invalid CAIP chain ID.'); + } + return { + namespace: match.groups.namespace, + reference: match.groups.reference, + }; +} +exports.parseCaipChainId = parseCaipChainId; +/** + * Parse an CAIP-10 account ID to an object containing the chain ID, parsed chain ID, and account address. + * This validates the CAIP-10 account ID before parsing it. + * + * @param caipAccountId - The CAIP-10 account ID to validate and parse. + * @returns The parsed CAIP-10 account ID. + */ +function parseCaipAccountId(caipAccountId) { + const match = exports.CAIP_ACCOUNT_ID_REGEX.exec(caipAccountId); + if (!match?.groups) { + throw new Error('Invalid CAIP account ID.'); + } + return { + address: match.groups.accountAddress, + chainId: match.groups.chainId, + chain: { + namespace: match.groups.namespace, + reference: match.groups.reference, + }, + }; +} +exports.parseCaipAccountId = parseCaipAccountId; +/** + * Chain ID as defined per the CAIP-2 + * {@link https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-2.md}. + * + * It defines a way to uniquely identify any blockchain in a human-readable + * way. + * + * @param namespace - The standard (ecosystem) of similar blockchains. + * @param reference - Identify of a blockchain within a given namespace. + * @throws {@link Error} + * This exception is thrown if the inputs does not comply with the CAIP-2 + * syntax specification + * {@link https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-2.md#syntax}. + * @returns A CAIP chain ID. + */ +function toCaipChainId(namespace, reference) { + if (!isCaipNamespace(namespace)) { + throw new Error(`Invalid "namespace", must match: ${exports.CAIP_NAMESPACE_REGEX.toString()}`); + } + if (!isCaipReference(reference)) { + throw new Error(`Invalid "reference", must match: ${exports.CAIP_REFERENCE_REGEX.toString()}`); + } + return `${namespace}:${reference}`; +} +exports.toCaipChainId = toCaipChainId; +//# sourceMappingURL=caip-types.cjs.map + +/***/ }), + +/***/ 98860: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ChecksumStruct = void 0; +const superstruct_1 = __webpack_require__(35620); +const base64_1 = __webpack_require__(20472); +exports.ChecksumStruct = (0, superstruct_1.size)((0, base64_1.base64)((0, superstruct_1.string)(), { paddingRequired: true }), 44, 44); +//# sourceMappingURL=checksum.cjs.map + +/***/ }), + +/***/ 65211: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createHex = exports.createBytes = exports.createBigInt = exports.createNumber = void 0; +const superstruct_1 = __webpack_require__(35620); +const assert_1 = __webpack_require__(22011); +const bytes_1 = __webpack_require__(77862); +const hex_1 = __webpack_require__(93976); +const NumberLikeStruct = (0, superstruct_1.union)([(0, superstruct_1.number)(), (0, superstruct_1.bigint)(), (0, superstruct_1.string)(), hex_1.StrictHexStruct]); +const NumberCoercer = (0, superstruct_1.coerce)((0, superstruct_1.number)(), NumberLikeStruct, Number); +const BigIntCoercer = (0, superstruct_1.coerce)((0, superstruct_1.bigint)(), NumberLikeStruct, BigInt); +const BytesLikeStruct = (0, superstruct_1.union)([hex_1.StrictHexStruct, (0, superstruct_1.instance)(Uint8Array)]); +const BytesCoercer = (0, superstruct_1.coerce)((0, superstruct_1.instance)(Uint8Array), (0, superstruct_1.union)([hex_1.StrictHexStruct]), bytes_1.hexToBytes); +const HexCoercer = (0, superstruct_1.coerce)(hex_1.StrictHexStruct, (0, superstruct_1.instance)(Uint8Array), bytes_1.bytesToHex); +/** + * Create a number from a number-like value. + * + * - If the value is a number, it is returned as-is. + * - If the value is a `bigint`, it is converted to a number. + * - If the value is a string, it is interpreted as a decimal number. + * - If the value is a hex string (i.e., it starts with "0x"), it is + * interpreted as a hexadecimal number. + * + * This validates that the value is a number-like value, and that the resulting + * number is not `NaN` or `Infinity`. + * + * @example + * ```typescript + * const value = createNumber('0x010203'); + * console.log(value); // 66051 + * + * const otherValue = createNumber(123n); + * console.log(otherValue); // 123 + * ``` + * @param value - The value to create the number from. + * @returns The created number. + * @throws If the value is not a number-like value, or if the resulting number + * is `NaN` or `Infinity`. + */ +function createNumber(value) { + try { + const result = (0, superstruct_1.create)(value, NumberCoercer); + (0, assert_1.assert)(Number.isFinite(result), `Expected a number-like value, got "${value}".`); + return result; + } + catch (error) { + if (error instanceof superstruct_1.StructError) { + throw new Error(`Expected a number-like value, got "${value}".`); + } + /* istanbul ignore next */ + throw error; + } +} +exports.createNumber = createNumber; +/** + * Create a `bigint` from a number-like value. + * + * - If the value is a number, it is converted to a `bigint`. + * - If the value is a `bigint`, it is returned as-is. + * - If the value is a string, it is interpreted as a decimal number and + * converted to a `bigint`. + * - If the value is a hex string (i.e., it starts with "0x"), it is + * interpreted as a hexadecimal number and converted to a `bigint`. + * + * @example + * ```typescript + * const value = createBigInt('0x010203'); + * console.log(value); // 16909060n + * + * const otherValue = createBigInt(123); + * console.log(otherValue); // 123n + * ``` + * @param value - The value to create the bigint from. + * @returns The created bigint. + * @throws If the value is not a number-like value. + */ +function createBigInt(value) { + try { + // The `BigInt` constructor throws if the value is not a number-like value. + // There is no need to validate the value manually. + return (0, superstruct_1.create)(value, BigIntCoercer); + } + catch (error) { + if (error instanceof superstruct_1.StructError) { + throw new Error(`Expected a number-like value, got "${String(error.value)}".`); + } + /* istanbul ignore next */ + throw error; + } +} +exports.createBigInt = createBigInt; +/** + * Create a byte array from a bytes-like value. + * + * - If the value is a byte array, it is returned as-is. + * - If the value is a hex string (i.e., it starts with "0x"), it is interpreted + * as a hexadecimal number and converted to a byte array. + * + * @example + * ```typescript + * const value = createBytes('0x010203'); + * console.log(value); // Uint8Array [ 1, 2, 3 ] + * + * const otherValue = createBytes('0x010203'); + * console.log(otherValue); // Uint8Array [ 1, 2, 3 ] + * ``` + * @param value - The value to create the byte array from. + * @returns The created byte array. + * @throws If the value is not a bytes-like value. + */ +function createBytes(value) { + if (typeof value === 'string' && value.toLowerCase() === '0x') { + return new Uint8Array(); + } + try { + return (0, superstruct_1.create)(value, BytesCoercer); + } + catch (error) { + if (error instanceof superstruct_1.StructError) { + throw new Error(`Expected a bytes-like value, got "${String(error.value)}".`); + } + /* istanbul ignore next */ + throw error; + } +} +exports.createBytes = createBytes; +/** + * Create a hexadecimal string from a bytes-like value. + * + * - If the value is a hex string (i.e., it starts with "0x"), it is returned + * as-is. + * - If the value is a `Uint8Array`, it is converted to a hex string. + * + * @example + * ```typescript + * const value = createHex(new Uint8Array([1, 2, 3])); + * console.log(value); // '0x010203' + * + * const otherValue = createHex('0x010203'); + * console.log(otherValue); // '0x010203' + * ``` + * @param value - The value to create the hex string from. + * @returns The created hex string. + * @throws If the value is not a bytes-like value. + */ +function createHex(value) { + if ((value instanceof Uint8Array && value.length === 0) || + (typeof value === 'string' && value.toLowerCase() === '0x')) { + return '0x'; + } + try { + return (0, superstruct_1.create)(value, HexCoercer); + } + catch (error) { + if (error instanceof superstruct_1.StructError) { + throw new Error(`Expected a bytes-like value, got "${String(error.value)}".`); + } + /* istanbul ignore next */ + throw error; + } +} +exports.createHex = createHex; +//# sourceMappingURL=coercers.cjs.map + +/***/ }), + +/***/ 44180: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; + +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var _FrozenMap_map, _FrozenSet_set; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FrozenSet = exports.FrozenMap = void 0; +/** + * A {@link ReadonlyMap} that cannot be modified after instantiation. + * The implementation uses an inner map hidden via a private field, and the + * immutability guarantee relies on it being impossible to get a reference + * to this map. + */ +class FrozenMap { + get size() { + return __classPrivateFieldGet(this, _FrozenMap_map, "f").size; + } + [(_FrozenMap_map = new WeakMap(), Symbol.iterator)]() { + return __classPrivateFieldGet(this, _FrozenMap_map, "f")[Symbol.iterator](); + } + constructor(entries) { + _FrozenMap_map.set(this, void 0); + __classPrivateFieldSet(this, _FrozenMap_map, new Map(entries), "f"); + Object.freeze(this); + } + entries() { + return __classPrivateFieldGet(this, _FrozenMap_map, "f").entries(); + } + forEach(callbackfn, thisArg) { + // We have to wrap the specified callback in order to prevent it from + // receiving a reference to the inner map. + return __classPrivateFieldGet(this, _FrozenMap_map, "f").forEach((value, key, _map) => callbackfn.call(thisArg, value, key, this)); + } + get(key) { + return __classPrivateFieldGet(this, _FrozenMap_map, "f").get(key); + } + has(key) { + return __classPrivateFieldGet(this, _FrozenMap_map, "f").has(key); + } + keys() { + return __classPrivateFieldGet(this, _FrozenMap_map, "f").keys(); + } + values() { + return __classPrivateFieldGet(this, _FrozenMap_map, "f").values(); + } + toString() { + return `FrozenMap(${this.size}) {${this.size > 0 + ? ` ${[...this.entries()] + .map(([key, value]) => `${String(key)} => ${String(value)}`) + .join(', ')} ` + : ''}}`; + } +} +exports.FrozenMap = FrozenMap; +/** + * A {@link ReadonlySet} that cannot be modified after instantiation. + * The implementation uses an inner set hidden via a private field, and the + * immutability guarantee relies on it being impossible to get a reference + * to this set. + */ +class FrozenSet { + get size() { + return __classPrivateFieldGet(this, _FrozenSet_set, "f").size; + } + [(_FrozenSet_set = new WeakMap(), Symbol.iterator)]() { + return __classPrivateFieldGet(this, _FrozenSet_set, "f")[Symbol.iterator](); + } + constructor(values) { + _FrozenSet_set.set(this, void 0); + __classPrivateFieldSet(this, _FrozenSet_set, new Set(values), "f"); + Object.freeze(this); + } + entries() { + return __classPrivateFieldGet(this, _FrozenSet_set, "f").entries(); + } + forEach(callbackfn, thisArg) { + // We have to wrap the specified callback in order to prevent it from + // receiving a reference to the inner set. + return __classPrivateFieldGet(this, _FrozenSet_set, "f").forEach((value, value2, _set) => callbackfn.call(thisArg, value, value2, this)); + } + has(value) { + return __classPrivateFieldGet(this, _FrozenSet_set, "f").has(value); + } + keys() { + return __classPrivateFieldGet(this, _FrozenSet_set, "f").keys(); + } + values() { + return __classPrivateFieldGet(this, _FrozenSet_set, "f").values(); + } + toString() { + return `FrozenSet(${this.size}) {${this.size > 0 + ? ` ${[...this.values()].map((member) => String(member)).join(', ')} ` + : ''}}`; + } +} +exports.FrozenSet = FrozenSet; +Object.freeze(FrozenMap); +Object.freeze(FrozenMap.prototype); +Object.freeze(FrozenSet); +Object.freeze(FrozenSet.prototype); +//# sourceMappingURL=collections.cjs.map + +/***/ }), + +/***/ 91630: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=encryption-types.cjs.map + +/***/ }), + +/***/ 75940: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.wrapError = exports.getErrorMessage = exports.isErrorWithStack = exports.isErrorWithMessage = exports.isErrorWithCode = void 0; +const pony_cause_1 = __webpack_require__(71843); +const misc_1 = __webpack_require__(33745); +/** + * Type guard for determining whether the given value is an instance of Error. + * For errors generated via `fs.promises`, `error instanceof Error` won't work, + * so we have to come up with another way of testing. + * + * @param error - The object to check. + * @returns A boolean. + */ +function isError(error) { + return (error instanceof Error || + ((0, misc_1.isObject)(error) && error.constructor.name === 'Error')); +} +/** + * Type guard for determining whether the given value is an error object with a + * `code` property such as the type of error that Node throws for filesystem + * operations, etc. + * + * @param error - The object to check. + * @returns A boolean. + */ +function isErrorWithCode(error) { + return typeof error === 'object' && error !== null && 'code' in error; +} +exports.isErrorWithCode = isErrorWithCode; +/** + * Type guard for determining whether the given value is an error object with a + * `message` property, such as an instance of Error. + * + * @param error - The object to check. + * @returns A boolean. + */ +function isErrorWithMessage(error) { + return typeof error === 'object' && error !== null && 'message' in error; +} +exports.isErrorWithMessage = isErrorWithMessage; +/** + * Type guard for determining whether the given value is an error object with a + * `stack` property, such as an instance of Error. + * + * @param error - The object to check. + * @returns A boolean. + */ +function isErrorWithStack(error) { + return typeof error === 'object' && error !== null && 'stack' in error; +} +exports.isErrorWithStack = isErrorWithStack; +/** + * Attempts to obtain the message from a possible error object, defaulting to an + * empty string if it is impossible to do so. + * + * @param error - The possible error to get the message from. + * @returns The message if `error` is an object with a `message` property; + * the string version of `error` if it is not `undefined` or `null`; otherwise + * an empty string. + */ +function getErrorMessage(error) { + if (isErrorWithMessage(error) && typeof error.message === 'string') { + return error.message; + } + if ((0, misc_1.isNullOrUndefined)(error)) { + return ''; + } + return String(error); +} +exports.getErrorMessage = getErrorMessage; +/** + * Builds a new error object, linking it to the original error via the `cause` + * property if it is an Error. + * + * This function is useful to reframe error messages in general, but is + * _critical_ when interacting with any of Node's filesystem functions as + * provided via `fs.promises`, because these do not produce stack traces in the + * case of an I/O error (see ). + * + * @param originalError - The error to be wrapped (something throwable). + * @param message - The desired message of the new error. + * @returns A new error object. + */ +function wrapError(originalError, message) { + if (isError(originalError)) { + let error; + if (Error.length === 2) { + // for some reason `tsserver` is not complaining that the + // Error constructor doesn't support a second argument in the editor, + // but `tsc` does. Error causes are not supported by our current tsc target (ES2020, we need ES2022 to make this work) + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + error = new Error(message, { cause: originalError }); + } + else { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + error = new pony_cause_1.ErrorWithCause(message, { cause: originalError }); + } + if (isErrorWithCode(originalError)) { + error.code = originalError.code; + } + return error; + } + if (message.length > 0) { + return new Error(`${String(originalError)}: ${message}`); + } + return new Error(String(originalError)); +} +exports.wrapError = wrapError; +//# sourceMappingURL=errors.cjs.map + +/***/ }), + +/***/ 93976: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.remove0x = exports.add0x = exports.isValidChecksumAddress = exports.getChecksumAddress = exports.isValidHexAddress = exports.assertIsStrictHexString = exports.assertIsHexString = exports.isStrictHexString = exports.isHexString = exports.HexChecksumAddressStruct = exports.HexAddressStruct = exports.StrictHexStruct = exports.HexStruct = void 0; +const superstruct_1 = __webpack_require__(35620); +const sha3_1 = __webpack_require__(2214); +const assert_1 = __webpack_require__(22011); +const bytes_1 = __webpack_require__(77862); +exports.HexStruct = (0, superstruct_1.pattern)((0, superstruct_1.string)(), /^(?:0x)?[0-9a-f]+$/iu); +exports.StrictHexStruct = (0, superstruct_1.pattern)((0, superstruct_1.string)(), /^0x[0-9a-f]+$/iu); +exports.HexAddressStruct = (0, superstruct_1.pattern)((0, superstruct_1.string)(), /^0x[0-9a-f]{40}$/u); +exports.HexChecksumAddressStruct = (0, superstruct_1.pattern)((0, superstruct_1.string)(), /^0x[0-9a-fA-F]{40}$/u); +/** + * Check if a string is a valid hex string. + * + * @param value - The value to check. + * @returns Whether the value is a valid hex string. + */ +function isHexString(value) { + return (0, superstruct_1.is)(value, exports.HexStruct); +} +exports.isHexString = isHexString; +/** + * Strictly check if a string is a valid hex string. A valid hex string must + * start with the "0x"-prefix. + * + * @param value - The value to check. + * @returns Whether the value is a valid hex string. + */ +function isStrictHexString(value) { + return (0, superstruct_1.is)(value, exports.StrictHexStruct); +} +exports.isStrictHexString = isStrictHexString; +/** + * Assert that a value is a valid hex string. + * + * @param value - The value to check. + * @throws If the value is not a valid hex string. + */ +function assertIsHexString(value) { + (0, assert_1.assert)(isHexString(value), 'Value must be a hexadecimal string.'); +} +exports.assertIsHexString = assertIsHexString; +/** + * Assert that a value is a valid hex string. A valid hex string must start with + * the "0x"-prefix. + * + * @param value - The value to check. + * @throws If the value is not a valid hex string. + */ +function assertIsStrictHexString(value) { + (0, assert_1.assert)(isStrictHexString(value), 'Value must be a hexadecimal string, starting with "0x".'); +} +exports.assertIsStrictHexString = assertIsStrictHexString; +/** + * Validate that the passed prefixed hex string is an all-lowercase + * hex address, or a valid mixed-case checksum address. + * + * @param possibleAddress - Input parameter to check against. + * @returns Whether or not the input is a valid hex address. + */ +function isValidHexAddress(possibleAddress) { + return ((0, superstruct_1.is)(possibleAddress, exports.HexAddressStruct) || + isValidChecksumAddress(possibleAddress)); +} +exports.isValidHexAddress = isValidHexAddress; +/** + * Encode a passed hex string as an ERC-55 mixed-case checksum address. + * + * @param address - The hex address to encode. + * @returns The address encoded according to ERC-55. + * @see https://eips.ethereum.org/EIPS/eip-55 + */ +function getChecksumAddress(address) { + (0, assert_1.assert)((0, superstruct_1.is)(address, exports.HexChecksumAddressStruct), 'Invalid hex address.'); + const unPrefixed = remove0x(address.toLowerCase()); + const unPrefixedHash = remove0x((0, bytes_1.bytesToHex)((0, sha3_1.keccak_256)(unPrefixed))); + return `0x${unPrefixed + .split('') + .map((character, nibbleIndex) => { + const hashCharacter = unPrefixedHash[nibbleIndex]; + (0, assert_1.assert)((0, superstruct_1.is)(hashCharacter, (0, superstruct_1.string)()), 'Hash shorter than address.'); + return parseInt(hashCharacter, 16) > 7 + ? character.toUpperCase() + : character; + }) + .join('')}`; +} +exports.getChecksumAddress = getChecksumAddress; +/** + * Validate that the passed hex string is a valid ERC-55 mixed-case + * checksum address. + * + * @param possibleChecksum - The hex address to check. + * @returns True if the address is a checksum address. + */ +function isValidChecksumAddress(possibleChecksum) { + if (!(0, superstruct_1.is)(possibleChecksum, exports.HexChecksumAddressStruct)) { + return false; + } + return getChecksumAddress(possibleChecksum) === possibleChecksum; +} +exports.isValidChecksumAddress = isValidChecksumAddress; +/** + * Add the `0x`-prefix to a hexadecimal string. If the string already has the + * prefix, it is returned as-is. + * + * @param hexadecimal - The hexadecimal string to add the prefix to. + * @returns The prefixed hexadecimal string. + */ +function add0x(hexadecimal) { + if (hexadecimal.startsWith('0x')) { + return hexadecimal; + } + if (hexadecimal.startsWith('0X')) { + return `0x${hexadecimal.substring(2)}`; + } + return `0x${hexadecimal}`; +} +exports.add0x = add0x; +/** + * Remove the `0x`-prefix from a hexadecimal string. If the string doesn't have + * the prefix, it is returned as-is. + * + * @param hexadecimal - The hexadecimal string to remove the prefix from. + * @returns The un-prefixed hexadecimal string. + */ +function remove0x(hexadecimal) { + if (hexadecimal.startsWith('0x') || hexadecimal.startsWith('0X')) { + return hexadecimal.substring(2); + } + return hexadecimal; +} +exports.remove0x = remove0x; +//# sourceMappingURL=hex.cjs.map + +/***/ }), + +/***/ 52367: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +__exportStar(__webpack_require__(22011), exports); +__exportStar(__webpack_require__(20472), exports); +__exportStar(__webpack_require__(77862), exports); +__exportStar(__webpack_require__(87690), exports); +__exportStar(__webpack_require__(98860), exports); +__exportStar(__webpack_require__(65211), exports); +__exportStar(__webpack_require__(44180), exports); +__exportStar(__webpack_require__(91630), exports); +__exportStar(__webpack_require__(75940), exports); +__exportStar(__webpack_require__(93976), exports); +__exportStar(__webpack_require__(60087), exports); +__exportStar(__webpack_require__(24956), exports); +__exportStar(__webpack_require__(98912), exports); +__exportStar(__webpack_require__(33745), exports); +__exportStar(__webpack_require__(5770), exports); +__exportStar(__webpack_require__(3028), exports); +__exportStar(__webpack_require__(2812), exports); +__exportStar(__webpack_require__(32954), exports); +__exportStar(__webpack_require__(16871), exports); +__exportStar(__webpack_require__(49266), exports); +//# sourceMappingURL=index.cjs.map + +/***/ }), + +/***/ 60087: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getJsonRpcIdValidator = exports.assertIsJsonRpcError = exports.isJsonRpcError = exports.assertIsJsonRpcFailure = exports.isJsonRpcFailure = exports.assertIsJsonRpcSuccess = exports.isJsonRpcSuccess = exports.assertIsJsonRpcResponse = exports.isJsonRpcResponse = exports.assertIsPendingJsonRpcResponse = exports.isPendingJsonRpcResponse = exports.JsonRpcResponseStruct = exports.JsonRpcFailureStruct = exports.JsonRpcSuccessStruct = exports.PendingJsonRpcResponseStruct = exports.assertIsJsonRpcRequest = exports.isJsonRpcRequest = exports.assertIsJsonRpcNotification = exports.isJsonRpcNotification = exports.JsonRpcNotificationStruct = exports.JsonRpcRequestStruct = exports.JsonRpcParamsStruct = exports.JsonRpcErrorStruct = exports.JsonRpcIdStruct = exports.JsonRpcVersionStruct = exports.jsonrpc2 = exports.getJsonSize = exports.getSafeJson = exports.isValidJson = exports.JsonStruct = exports.UnsafeJsonStruct = exports.exactOptional = exports.object = void 0; +const superstruct_1 = __webpack_require__(35620); +const assert_1 = __webpack_require__(22011); +const misc_1 = __webpack_require__(33745); +/** + * A struct to check if the given value is a valid object, with support for + * {@link exactOptional} types. + * + * @param schema - The schema of the object. + * @returns A struct to check if the given value is an object. + */ +const object = (schema) => +// The type is slightly different from a regular object struct, because we +// want to make properties with `undefined` in their type optional, but not +// `undefined` itself. This means that we need a type cast. +(0, superstruct_1.object)(schema); +exports.object = object; +/** + * Check the last field of a path is present. + * + * @param context - The context to check. + * @param context.path - The path to check. + * @param context.branch - The branch to check. + * @returns Whether the last field of a path is present. + */ +function hasOptional({ path, branch }) { + const field = path[path.length - 1]; + return (0, misc_1.hasProperty)(branch[branch.length - 2], field); +} +/** + * A struct which allows the property of an object to be absent, or to be present + * as long as it's valid and not set to `undefined`. + * + * This struct should be used in conjunction with the {@link object} from this + * library, to get proper type inference. + * + * @param struct - The struct to check the value against, if present. + * @returns A struct to check if the given value is valid, or not present. + * @example + * ```ts + * const struct = object({ + * foo: exactOptional(string()), + * bar: exactOptional(number()), + * baz: optional(boolean()), + * qux: unknown(), + * }); + * + * type Type = Infer; + * // Type is equivalent to: + * // { + * // foo?: string; + * // bar?: number; + * // baz?: boolean | undefined; + * // qux: unknown; + * // } + * ``` + */ +function exactOptional(struct) { + return new superstruct_1.Struct({ + ...struct, + type: `optional ${struct.type}`, + validator: (value, context) => !hasOptional(context) || struct.validator(value, context), + refiner: (value, context) => !hasOptional(context) || struct.refiner(value, context), + }); +} +exports.exactOptional = exactOptional; +/** + * A struct to check if the given value is finite number. Superstruct's + * `number()` struct does not check if the value is finite. + * + * @returns A struct to check if the given value is finite number. + */ +const finiteNumber = () => (0, superstruct_1.define)('finite number', (value) => { + return (0, superstruct_1.is)(value, (0, superstruct_1.number)()) && Number.isFinite(value); +}); +/** + * A struct to check if the given value is a valid JSON-serializable value. + * + * Note that this struct is unsafe. For safe validation, use {@link JsonStruct}. + */ +// We cannot infer the type of the struct, because it is recursive. +exports.UnsafeJsonStruct = (0, superstruct_1.union)([ + (0, superstruct_1.literal)(null), + (0, superstruct_1.boolean)(), + finiteNumber(), + (0, superstruct_1.string)(), + (0, superstruct_1.array)((0, superstruct_1.lazy)(() => exports.UnsafeJsonStruct)), + (0, superstruct_1.record)((0, superstruct_1.string)(), (0, superstruct_1.lazy)(() => exports.UnsafeJsonStruct)), +]); +/** + * A struct to check if the given value is a valid JSON-serializable value. + * + * This struct sanitizes the value before validating it, so that it is safe to + * use with untrusted input. + */ +exports.JsonStruct = (0, superstruct_1.coerce)(exports.UnsafeJsonStruct, (0, superstruct_1.any)(), (value) => { + (0, assert_1.assertStruct)(value, exports.UnsafeJsonStruct); + return JSON.parse(JSON.stringify(value, (propKey, propValue) => { + // Strip __proto__ and constructor properties to prevent prototype pollution. + if (propKey === '__proto__' || propKey === 'constructor') { + return undefined; + } + return propValue; + })); +}); +/** + * Check if the given value is a valid {@link Json} value, i.e., a value that is + * serializable to JSON. + * + * @param value - The value to check. + * @returns Whether the value is a valid {@link Json} value. + */ +function isValidJson(value) { + try { + getSafeJson(value); + return true; + } + catch { + return false; + } +} +exports.isValidJson = isValidJson; +/** + * Validate and return sanitized JSON. + * + * Note: + * This function uses sanitized JsonStruct for validation + * that applies stringify and then parse of a value provided + * to ensure that there are no getters which can have side effects + * that can cause security issues. + * + * @param value - JSON structure to be processed. + * @returns Sanitized JSON structure. + */ +function getSafeJson(value) { + return (0, superstruct_1.create)(value, exports.JsonStruct); +} +exports.getSafeJson = getSafeJson; +/** + * Get the size of a JSON value in bytes. This also validates the value. + * + * @param value - The JSON value to get the size of. + * @returns The size of the JSON value in bytes. + */ +function getJsonSize(value) { + (0, assert_1.assertStruct)(value, exports.JsonStruct, 'Invalid JSON value'); + const json = JSON.stringify(value); + return new TextEncoder().encode(json).byteLength; +} +exports.getJsonSize = getJsonSize; +/** + * The string '2.0'. + */ +exports.jsonrpc2 = '2.0'; +exports.JsonRpcVersionStruct = (0, superstruct_1.literal)(exports.jsonrpc2); +exports.JsonRpcIdStruct = (0, superstruct_1.nullable)((0, superstruct_1.union)([(0, superstruct_1.number)(), (0, superstruct_1.string)()])); +exports.JsonRpcErrorStruct = (0, exports.object)({ + code: (0, superstruct_1.integer)(), + message: (0, superstruct_1.string)(), + data: exactOptional(exports.JsonStruct), + stack: exactOptional((0, superstruct_1.string)()), +}); +exports.JsonRpcParamsStruct = (0, superstruct_1.union)([(0, superstruct_1.record)((0, superstruct_1.string)(), exports.JsonStruct), (0, superstruct_1.array)(exports.JsonStruct)]); +exports.JsonRpcRequestStruct = (0, exports.object)({ + id: exports.JsonRpcIdStruct, + jsonrpc: exports.JsonRpcVersionStruct, + method: (0, superstruct_1.string)(), + params: exactOptional(exports.JsonRpcParamsStruct), +}); +exports.JsonRpcNotificationStruct = (0, exports.object)({ + jsonrpc: exports.JsonRpcVersionStruct, + method: (0, superstruct_1.string)(), + params: exactOptional(exports.JsonRpcParamsStruct), +}); +/** + * Check if the given value is a valid {@link JsonRpcNotification} object. + * + * @param value - The value to check. + * @returns Whether the given value is a valid {@link JsonRpcNotification} + * object. + */ +function isJsonRpcNotification(value) { + return (0, superstruct_1.is)(value, exports.JsonRpcNotificationStruct); +} +exports.isJsonRpcNotification = isJsonRpcNotification; +/** + * Assert that the given value is a valid {@link JsonRpcNotification} object. + * + * @param value - The value to check. + * @param ErrorWrapper - The error class to throw if the assertion fails. + * Defaults to {@link AssertionError}. + * @throws If the given value is not a valid {@link JsonRpcNotification} object. + */ +function assertIsJsonRpcNotification(value, +// eslint-disable-next-line @typescript-eslint/naming-convention +ErrorWrapper) { + (0, assert_1.assertStruct)(value, exports.JsonRpcNotificationStruct, 'Invalid JSON-RPC notification', ErrorWrapper); +} +exports.assertIsJsonRpcNotification = assertIsJsonRpcNotification; +/** + * Check if the given value is a valid {@link JsonRpcRequest} object. + * + * @param value - The value to check. + * @returns Whether the given value is a valid {@link JsonRpcRequest} object. + */ +function isJsonRpcRequest(value) { + return (0, superstruct_1.is)(value, exports.JsonRpcRequestStruct); +} +exports.isJsonRpcRequest = isJsonRpcRequest; +/** + * Assert that the given value is a valid {@link JsonRpcRequest} object. + * + * @param value - The JSON-RPC request or notification to check. + * @param ErrorWrapper - The error class to throw if the assertion fails. + * Defaults to {@link AssertionError}. + * @throws If the given value is not a valid {@link JsonRpcRequest} object. + */ +function assertIsJsonRpcRequest(value, +// eslint-disable-next-line @typescript-eslint/naming-convention +ErrorWrapper) { + (0, assert_1.assertStruct)(value, exports.JsonRpcRequestStruct, 'Invalid JSON-RPC request', ErrorWrapper); +} +exports.assertIsJsonRpcRequest = assertIsJsonRpcRequest; +exports.PendingJsonRpcResponseStruct = (0, superstruct_1.object)({ + id: exports.JsonRpcIdStruct, + jsonrpc: exports.JsonRpcVersionStruct, + result: (0, superstruct_1.optional)((0, superstruct_1.unknown)()), + error: (0, superstruct_1.optional)(exports.JsonRpcErrorStruct), +}); +exports.JsonRpcSuccessStruct = (0, exports.object)({ + id: exports.JsonRpcIdStruct, + jsonrpc: exports.JsonRpcVersionStruct, + result: exports.JsonStruct, +}); +exports.JsonRpcFailureStruct = (0, exports.object)({ + id: exports.JsonRpcIdStruct, + jsonrpc: exports.JsonRpcVersionStruct, + error: exports.JsonRpcErrorStruct, +}); +exports.JsonRpcResponseStruct = (0, superstruct_1.union)([ + exports.JsonRpcSuccessStruct, + exports.JsonRpcFailureStruct, +]); +/** + * Type guard to check whether specified JSON-RPC response is a + * {@link PendingJsonRpcResponse}. + * + * @param response - The JSON-RPC response to check. + * @returns Whether the specified JSON-RPC response is pending. + */ +function isPendingJsonRpcResponse(response) { + return (0, superstruct_1.is)(response, exports.PendingJsonRpcResponseStruct); +} +exports.isPendingJsonRpcResponse = isPendingJsonRpcResponse; +/** + * Assert that the given value is a valid {@link PendingJsonRpcResponse} object. + * + * @param response - The JSON-RPC response to check. + * @param ErrorWrapper - The error class to throw if the assertion fails. + * Defaults to {@link AssertionError}. + * @throws If the given value is not a valid {@link PendingJsonRpcResponse} + * object. + */ +function assertIsPendingJsonRpcResponse(response, +// eslint-disable-next-line @typescript-eslint/naming-convention +ErrorWrapper) { + (0, assert_1.assertStruct)(response, exports.PendingJsonRpcResponseStruct, 'Invalid pending JSON-RPC response', ErrorWrapper); +} +exports.assertIsPendingJsonRpcResponse = assertIsPendingJsonRpcResponse; +/** + * Type guard to check if a value is a {@link JsonRpcResponse}. + * + * @param response - The object to check. + * @returns Whether the object is a JsonRpcResponse. + */ +function isJsonRpcResponse(response) { + return (0, superstruct_1.is)(response, exports.JsonRpcResponseStruct); +} +exports.isJsonRpcResponse = isJsonRpcResponse; +/** + * Assert that the given value is a valid {@link JsonRpcResponse} object. + * + * @param value - The value to check. + * @param ErrorWrapper - The error class to throw if the assertion fails. + * Defaults to {@link AssertionError}. + * @throws If the given value is not a valid {@link JsonRpcResponse} object. + */ +function assertIsJsonRpcResponse(value, +// eslint-disable-next-line @typescript-eslint/naming-convention +ErrorWrapper) { + (0, assert_1.assertStruct)(value, exports.JsonRpcResponseStruct, 'Invalid JSON-RPC response', ErrorWrapper); +} +exports.assertIsJsonRpcResponse = assertIsJsonRpcResponse; +/** + * Check if the given value is a valid {@link JsonRpcSuccess} object. + * + * @param value - The value to check. + * @returns Whether the given value is a valid {@link JsonRpcSuccess} object. + */ +function isJsonRpcSuccess(value) { + return (0, superstruct_1.is)(value, exports.JsonRpcSuccessStruct); +} +exports.isJsonRpcSuccess = isJsonRpcSuccess; +/** + * Assert that the given value is a valid {@link JsonRpcSuccess} object. + * + * @param value - The value to check. + * @param ErrorWrapper - The error class to throw if the assertion fails. + * Defaults to {@link AssertionError}. + * @throws If the given value is not a valid {@link JsonRpcSuccess} object. + */ +function assertIsJsonRpcSuccess(value, +// eslint-disable-next-line @typescript-eslint/naming-convention +ErrorWrapper) { + (0, assert_1.assertStruct)(value, exports.JsonRpcSuccessStruct, 'Invalid JSON-RPC success response', ErrorWrapper); +} +exports.assertIsJsonRpcSuccess = assertIsJsonRpcSuccess; +/** + * Check if the given value is a valid {@link JsonRpcFailure} object. + * + * @param value - The value to check. + * @returns Whether the given value is a valid {@link JsonRpcFailure} object. + */ +function isJsonRpcFailure(value) { + return (0, superstruct_1.is)(value, exports.JsonRpcFailureStruct); +} +exports.isJsonRpcFailure = isJsonRpcFailure; +/** + * Assert that the given value is a valid {@link JsonRpcFailure} object. + * + * @param value - The value to check. + * @param ErrorWrapper - The error class to throw if the assertion fails. + * Defaults to {@link AssertionError}. + * @throws If the given value is not a valid {@link JsonRpcFailure} object. + */ +function assertIsJsonRpcFailure(value, +// eslint-disable-next-line @typescript-eslint/naming-convention +ErrorWrapper) { + (0, assert_1.assertStruct)(value, exports.JsonRpcFailureStruct, 'Invalid JSON-RPC failure response', ErrorWrapper); +} +exports.assertIsJsonRpcFailure = assertIsJsonRpcFailure; +/** + * Check if the given value is a valid {@link JsonRpcError} object. + * + * @param value - The value to check. + * @returns Whether the given value is a valid {@link JsonRpcError} object. + */ +function isJsonRpcError(value) { + return (0, superstruct_1.is)(value, exports.JsonRpcErrorStruct); +} +exports.isJsonRpcError = isJsonRpcError; +/** + * Assert that the given value is a valid {@link JsonRpcError} object. + * + * @param value - The value to check. + * @param ErrorWrapper - The error class to throw if the assertion fails. + * Defaults to {@link AssertionError}. + * @throws If the given value is not a valid {@link JsonRpcError} object. + */ +function assertIsJsonRpcError(value, +// eslint-disable-next-line @typescript-eslint/naming-convention +ErrorWrapper) { + (0, assert_1.assertStruct)(value, exports.JsonRpcErrorStruct, 'Invalid JSON-RPC error', ErrorWrapper); +} +exports.assertIsJsonRpcError = assertIsJsonRpcError; +/** + * Gets a function for validating JSON-RPC request / response `id` values. + * + * By manipulating the options of this factory, you can control the behavior + * of the resulting validator for some edge cases. This is useful because e.g. + * `null` should sometimes but not always be permitted. + * + * Note that the empty string (`''`) is always permitted by the JSON-RPC + * specification, but that kind of sucks and you may want to forbid it in some + * instances anyway. + * + * For more details, see the + * [JSON-RPC Specification](https://www.jsonrpc.org/specification). + * + * @param options - An options object. + * @param options.permitEmptyString - Whether the empty string (i.e. `''`) + * should be treated as a valid ID. Default: `true` + * @param options.permitFractions - Whether fractional numbers (e.g. `1.2`) + * should be treated as valid IDs. Default: `false` + * @param options.permitNull - Whether `null` should be treated as a valid ID. + * Default: `true` + * @returns The JSON-RPC ID validator function. + */ +function getJsonRpcIdValidator(options) { + const { permitEmptyString, permitFractions, permitNull } = { + permitEmptyString: true, + permitFractions: false, + permitNull: true, + ...options, + }; + /** + * Type guard for {@link JsonRpcId}. + * + * @param id - The JSON-RPC ID value to check. + * @returns Whether the given ID is valid per the options given to the + * factory. + */ + const isValidJsonRpcId = (id) => { + return Boolean((typeof id === 'number' && (permitFractions || Number.isInteger(id))) || + (typeof id === 'string' && (permitEmptyString || id.length > 0)) || + (permitNull && id === null)); + }; + return isValidJsonRpcId; +} +exports.getJsonRpcIdValidator = getJsonRpcIdValidator; +//# sourceMappingURL=json.cjs.map + +/***/ }), + +/***/ 24956: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=keyring.cjs.map + +/***/ }), + +/***/ 98912: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createModuleLogger = exports.createProjectLogger = void 0; +const debug_1 = __importDefault(__webpack_require__(17833)); +const globalLogger = (0, debug_1.default)('metamask'); +/** + * Creates a logger via the `debug` library whose log messages will be tagged + * using the name of your project. By default, such messages will be + * suppressed, but you can reveal them by setting the `DEBUG` environment + * variable to `metamask:`. You can also set this variable to + * `metamask:*` if you want to see log messages from all MetaMask projects that + * are also using this function to create their loggers. + * + * @param projectName - The name of your project. This should be the name of + * your NPM package if you're developing one. + * @returns An instance of `debug`. + */ +function createProjectLogger(projectName) { + return globalLogger.extend(projectName); +} +exports.createProjectLogger = createProjectLogger; +/** + * Creates a logger via the `debug` library which is derived from the logger for + * the whole project whose log messages will be tagged using the name of your + * module. By default, such messages will be suppressed, but you can reveal them + * by setting the `DEBUG` environment variable to + * `metamask::`. You can also set this variable to + * `metamask::*` if you want to see log messages from the project, + * or `metamask:*` if you want to see log messages from all MetaMask projects. + * + * @param projectLogger - The logger created via {@link createProjectLogger}. + * @param moduleName - The name of your module. You could use the name of the + * file where you're using this logger or some other name. + * @returns An instance of `debug`. + */ +function createModuleLogger(projectLogger, moduleName) { + return projectLogger.extend(moduleName); +} +exports.createModuleLogger = createModuleLogger; +//# sourceMappingURL=logging.cjs.map + +/***/ }), + +/***/ 33745: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// +// Types +// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.calculateNumberSize = exports.calculateStringSize = exports.isASCII = exports.isPlainObject = exports.ESCAPE_CHARACTERS_REGEXP = exports.JsonSize = exports.getKnownPropertyNames = exports.hasProperty = exports.isObject = exports.isNullOrUndefined = exports.isNonEmptyArray = void 0; +// +// Type Guards +// +/** + * A {@link NonEmptyArray} type guard. + * + * @template Element - The non-empty array member type. + * @param value - The value to check. + * @returns Whether the value is a non-empty array. + */ +function isNonEmptyArray(value) { + return Array.isArray(value) && value.length > 0; +} +exports.isNonEmptyArray = isNonEmptyArray; +/** + * Type guard for "nullishness". + * + * @param value - Any value. + * @returns `true` if the value is null or undefined, `false` otherwise. + */ +function isNullOrUndefined(value) { + return value === null || value === undefined; +} +exports.isNullOrUndefined = isNullOrUndefined; +/** + * A type guard for {@link RuntimeObject}. + * + * @param value - The value to check. + * @returns Whether the specified value has a runtime type of `object` and is + * neither `null` nor an `Array`. + */ +function isObject(value) { + return Boolean(value) && typeof value === 'object' && !Array.isArray(value); +} +exports.isObject = isObject; +// +// Other utility functions +// +/** + * A type guard for ensuring an object has a property. + * + * @param objectToCheck - The object to check. + * @param name - The property name to check for. + * @returns Whether the specified object has an own property with the specified + * name, regardless of whether it is enumerable or not. + */ +const hasProperty = (objectToCheck, name) => Object.hasOwnProperty.call(objectToCheck, name); +exports.hasProperty = hasProperty; +/** + * `Object.getOwnPropertyNames()` is intentionally generic: it returns the + * immediate property names of an object, but it cannot make guarantees about + * the contents of that object, so the type of the property names is merely + * `string[]`. While this is technically accurate, it is also unnecessary if we + * have an object with a type that we own (such as an enum). + * + * @param object - The plain object. + * @returns The own property names of the object which are assigned a type + * derived from the object itself. + */ +function getKnownPropertyNames(object) { + return Object.getOwnPropertyNames(object); +} +exports.getKnownPropertyNames = getKnownPropertyNames; +/** + * Predefined sizes (in Bytes) of specific parts of JSON structure. + */ +var JsonSize; +(function (JsonSize) { + JsonSize[JsonSize["Null"] = 4] = "Null"; + JsonSize[JsonSize["Comma"] = 1] = "Comma"; + JsonSize[JsonSize["Wrapper"] = 1] = "Wrapper"; + JsonSize[JsonSize["True"] = 4] = "True"; + JsonSize[JsonSize["False"] = 5] = "False"; + JsonSize[JsonSize["Quote"] = 1] = "Quote"; + JsonSize[JsonSize["Colon"] = 1] = "Colon"; + // eslint-disable-next-line @typescript-eslint/no-shadow + JsonSize[JsonSize["Date"] = 24] = "Date"; +})(JsonSize = exports.JsonSize || (exports.JsonSize = {})); +/** + * Regular expression with pattern matching for (special) escaped characters. + */ +exports.ESCAPE_CHARACTERS_REGEXP = /"|\\|\n|\r|\t/gu; +/** + * Check if the value is plain object. + * + * @param value - Value to be checked. + * @returns True if an object is the plain JavaScript object, + * false if the object is not plain (e.g. function). + */ +function isPlainObject(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + let proto = value; + while (Object.getPrototypeOf(proto) !== null) { + proto = Object.getPrototypeOf(proto); + } + return Object.getPrototypeOf(value) === proto; + } + catch (_) { + return false; + } +} +exports.isPlainObject = isPlainObject; +/** + * Check if character is ASCII. + * + * @param character - Character. + * @returns True if a character code is ASCII, false if not. + */ +function isASCII(character) { + return character.charCodeAt(0) <= 127; +} +exports.isASCII = isASCII; +/** + * Calculate string size. + * + * @param value - String value to calculate size. + * @returns Number of bytes used to store whole string value. + */ +function calculateStringSize(value) { + const size = value.split('').reduce((total, character) => { + if (isASCII(character)) { + return total + 1; + } + return total + 2; + }, 0); + // Also detect characters that need backslash escape + return size + (value.match(exports.ESCAPE_CHARACTERS_REGEXP) ?? []).length; +} +exports.calculateStringSize = calculateStringSize; +/** + * Calculate size of a number ofter JSON serialization. + * + * @param value - Number value to calculate size. + * @returns Number of bytes used to store whole number in JSON. + */ +function calculateNumberSize(value) { + return value.toString().length; +} +exports.calculateNumberSize = calculateNumberSize; +//# sourceMappingURL=misc.cjs.map + +/***/ }), + +/***/ 5770: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.hexToBigInt = exports.hexToNumber = exports.bigIntToHex = exports.numberToHex = void 0; +const assert_1 = __webpack_require__(22011); +const hex_1 = __webpack_require__(93976); +/** + * Convert a number to a hexadecimal string. This verifies that the number is a + * non-negative safe integer. + * + * To convert a `bigint` to a hexadecimal string instead, use + * {@link bigIntToHex}. + * + * @example + * ```typescript + * numberToHex(0); // '0x0' + * numberToHex(1); // '0x1' + * numberToHex(16); // '0x10' + * ``` + * @param value - The number to convert to a hexadecimal string. + * @returns The hexadecimal string, with the "0x"-prefix. + * @throws If the number is not a non-negative safe integer. + */ +const numberToHex = (value) => { + (0, assert_1.assert)(typeof value === 'number', 'Value must be a number.'); + (0, assert_1.assert)(value >= 0, 'Value must be a non-negative number.'); + (0, assert_1.assert)(Number.isSafeInteger(value), 'Value is not a safe integer. Use `bigIntToHex` instead.'); + return (0, hex_1.add0x)(value.toString(16)); +}; +exports.numberToHex = numberToHex; +/** + * Convert a `bigint` to a hexadecimal string. This verifies that the `bigint` + * is a non-negative integer. + * + * To convert a number to a hexadecimal string instead, use {@link numberToHex}. + * + * @example + * ```typescript + * bigIntToHex(0n); // '0x0' + * bigIntToHex(1n); // '0x1' + * bigIntToHex(16n); // '0x10' + * ``` + * @param value - The `bigint` to convert to a hexadecimal string. + * @returns The hexadecimal string, with the "0x"-prefix. + * @throws If the `bigint` is not a non-negative integer. + */ +const bigIntToHex = (value) => { + (0, assert_1.assert)(typeof value === 'bigint', 'Value must be a bigint.'); + (0, assert_1.assert)(value >= 0, 'Value must be a non-negative bigint.'); + return (0, hex_1.add0x)(value.toString(16)); +}; +exports.bigIntToHex = bigIntToHex; +/** + * Convert a hexadecimal string to a number. This verifies that the string is a + * valid hex string, and that the resulting number is a safe integer. Both + * "0x"-prefixed and unprefixed strings are supported. + * + * To convert a hexadecimal string to a `bigint` instead, use + * {@link hexToBigInt}. + * + * @example + * ```typescript + * hexToNumber('0x0'); // 0 + * hexToNumber('0x1'); // 1 + * hexToNumber('0x10'); // 16 + * ``` + * @param value - The hexadecimal string to convert to a number. + * @returns The number. + * @throws If the value is not a valid hexadecimal string, or if the resulting + * number is not a safe integer. + */ +const hexToNumber = (value) => { + (0, hex_1.assertIsHexString)(value); + // `parseInt` accepts values without the "0x"-prefix, whereas `Number` does + // not. Using this is slightly faster than `Number(add0x(value))`. + const numberValue = parseInt(value, 16); + (0, assert_1.assert)(Number.isSafeInteger(numberValue), 'Value is not a safe integer. Use `hexToBigInt` instead.'); + return numberValue; +}; +exports.hexToNumber = hexToNumber; +/** + * Convert a hexadecimal string to a `bigint`. This verifies that the string is + * a valid hex string. Both "0x"-prefixed and unprefixed strings are supported. + * + * To convert a hexadecimal string to a number instead, use {@link hexToNumber}. + * + * @example + * ```typescript + * hexToBigInt('0x0'); // 0n + * hexToBigInt('0x1'); // 1n + * hexToBigInt('0x10'); // 16n + * ``` + * @param value - The hexadecimal string to convert to a `bigint`. + * @returns The `bigint`. + * @throws If the value is not a valid hexadecimal string. + */ +const hexToBigInt = (value) => { + (0, hex_1.assertIsHexString)(value); + // The `BigInt` constructor requires the "0x"-prefix to parse a hex string. + return BigInt((0, hex_1.add0x)(value)); +}; +exports.hexToBigInt = hexToBigInt; +//# sourceMappingURL=number.cjs.map + +/***/ }), + +/***/ 3028: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=opaque.cjs.map + +/***/ }), + +/***/ 2812: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createDeferredPromise = void 0; +/** + * Create a defered Promise. + * + * If the Promise is rejected prior to a handler being added, this can result in an + * `UnhandledPromiseRejection` error. Optionally this can be suppressed with the + * `suppressUnhandledRejection` flag, as it's common to belatedly handle deferred Promises, or to + * ignore them if they're no longer relevant (e.g. related to a cancelled request). + * + * However, be very careful that you have handled the Promise if you do this. Suppressing these + * errors is dangerous, they exist for good reason. An unhandled rejection can hide errors, making + * debugging extremely difficult. They should only be suppressed if you're confident that the + * Promise is always handled correctly, in both the success and failure cases. + * + * @param args - The arguments. + * @param args.suppressUnhandledRejection - This option adds an empty error handler + * to the Promise to suppress the UnhandledPromiseRejection error. This can be + * useful if the deferred Promise is sometimes intentionally not used. + * @returns A deferred Promise. + * @template Result - The result type of the Promise. + */ +function createDeferredPromise({ suppressUnhandledRejection = false, } = {}) { + let resolve; + let reject; + const promise = new Promise((innerResolve, innerReject) => { + resolve = innerResolve; + reject = innerReject; + }); + if (suppressUnhandledRejection) { + promise.catch((_error) => { + // This handler is used to suppress the UnhandledPromiseRejection error + }); + } + // @ts-expect-error We know that these are assigned, but TypeScript doesn't + return { promise, resolve, reject }; +} +exports.createDeferredPromise = createDeferredPromise; +//# sourceMappingURL=promise.cjs.map + +/***/ }), + +/***/ 32954: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.timeSince = exports.inMilliseconds = exports.Duration = void 0; +/** + * Common duration constants, in milliseconds. + */ +var Duration; +(function (Duration) { + /** + * A millisecond. + */ + Duration[Duration["Millisecond"] = 1] = "Millisecond"; + /** + * A second, in milliseconds. + */ + Duration[Duration["Second"] = 1000] = "Second"; + /** + * A minute, in milliseconds. + */ + Duration[Duration["Minute"] = 60000] = "Minute"; + /** + * An hour, in milliseconds. + */ + Duration[Duration["Hour"] = 3600000] = "Hour"; + /** + * A day, in milliseconds. + */ + Duration[Duration["Day"] = 86400000] = "Day"; + /** + * A week, in milliseconds. + */ + Duration[Duration["Week"] = 604800000] = "Week"; + /** + * A year, in milliseconds. + */ + Duration[Duration["Year"] = 31536000000] = "Year"; +})(Duration = exports.Duration || (exports.Duration = {})); +const isNonNegativeInteger = (number) => Number.isInteger(number) && number >= 0; +const assertIsNonNegativeInteger = (number, name) => { + if (!isNonNegativeInteger(number)) { + throw new Error(`"${name}" must be a non-negative integer. Received: "${number}".`); + } +}; +/** + * Calculates the millisecond value of the specified number of units of time. + * + * @param count - The number of units of time. + * @param duration - The unit of time to count. + * @returns The count multiplied by the specified duration. + */ +function inMilliseconds(count, duration) { + assertIsNonNegativeInteger(count, 'count'); + return count * duration; +} +exports.inMilliseconds = inMilliseconds; +/** + * Gets the milliseconds since a particular Unix epoch timestamp. + * + * @param timestamp - A Unix millisecond timestamp. + * @returns The number of milliseconds elapsed since the specified timestamp. + */ +function timeSince(timestamp) { + assertIsNonNegativeInteger(timestamp, 'timestamp'); + return Date.now() - timestamp; +} +exports.timeSince = timeSince; +//# sourceMappingURL=time.cjs.map + +/***/ }), + +/***/ 16871: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=transaction-types.cjs.map + +/***/ }), + +/***/ 49266: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.satisfiesVersionRange = exports.gtRange = exports.gtVersion = exports.assertIsSemVerRange = exports.assertIsSemVerVersion = exports.isValidSemVerRange = exports.isValidSemVerVersion = exports.VersionRangeStruct = exports.VersionStruct = void 0; +const superstruct_1 = __webpack_require__(35620); +const semver_1 = __webpack_require__(99589); +const assert_1 = __webpack_require__(22011); +/** + * A struct for validating a version string. + */ +exports.VersionStruct = (0, superstruct_1.refine)((0, superstruct_1.string)(), 'Version', (value) => { + if ((0, semver_1.valid)(value) === null) { + return `Expected SemVer version, got "${value}"`; + } + return true; +}); +exports.VersionRangeStruct = (0, superstruct_1.refine)((0, superstruct_1.string)(), 'Version range', (value) => { + if ((0, semver_1.validRange)(value) === null) { + return `Expected SemVer range, got "${value}"`; + } + return true; +}); +/** + * Checks whether a SemVer version is valid. + * + * @param version - A potential version. + * @returns `true` if the version is valid, and `false` otherwise. + */ +function isValidSemVerVersion(version) { + return (0, superstruct_1.is)(version, exports.VersionStruct); +} +exports.isValidSemVerVersion = isValidSemVerVersion; +/** + * Checks whether a SemVer version range is valid. + * + * @param versionRange - A potential version range. + * @returns `true` if the version range is valid, and `false` otherwise. + */ +function isValidSemVerRange(versionRange) { + return (0, superstruct_1.is)(versionRange, exports.VersionRangeStruct); +} +exports.isValidSemVerRange = isValidSemVerRange; +/** + * Asserts that a value is a valid concrete SemVer version. + * + * @param version - A potential SemVer concrete version. + */ +function assertIsSemVerVersion(version) { + (0, assert_1.assertStruct)(version, exports.VersionStruct); +} +exports.assertIsSemVerVersion = assertIsSemVerVersion; +/** + * Asserts that a value is a valid SemVer range. + * + * @param range - A potential SemVer range. + */ +function assertIsSemVerRange(range) { + (0, assert_1.assertStruct)(range, exports.VersionRangeStruct); +} +exports.assertIsSemVerRange = assertIsSemVerRange; +/** + * Checks whether a SemVer version is greater than another. + * + * @param version1 - The left-hand version. + * @param version2 - The right-hand version. + * @returns `version1 > version2`. + */ +function gtVersion(version1, version2) { + return (0, semver_1.gt)(version1, version2); +} +exports.gtVersion = gtVersion; +/** + * Checks whether a SemVer version is greater than all possibilities in a range. + * + * @param version - A SemvVer version. + * @param range - The range to check against. + * @returns `version > range`. + */ +function gtRange(version, range) { + return (0, semver_1.gtr)(version, range); +} +exports.gtRange = gtRange; +/** + * Returns whether a SemVer version satisfies a SemVer range. + * + * @param version - The SemVer version to check. + * @param versionRange - The SemVer version range to check against. + * @returns Whether the version satisfied the version range. + */ +function satisfiesVersionRange(version, versionRange) { + return (0, semver_1.satisfies)(version, versionRange, { + includePrerelease: true, + }); +} +exports.satisfiesVersionRange = satisfiesVersionRange; +//# sourceMappingURL=versions.cjs.map + +/***/ }), + +/***/ 39209: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var possibleNames = __webpack_require__(76578); + +var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; + +/** @type {import('.')} */ +module.exports = function availableTypedArrays() { + var /** @type {ReturnType} */ out = []; + for (var i = 0; i < possibleNames.length; i++) { + if (typeof g[possibleNames[i]] === 'function') { + // @ts-expect-error + out[out.length] = possibleNames[i]; + } + } + return out; +}; + + +/***/ }), + +/***/ 48343: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const { normalizeIPv6, normalizeIPv4, removeDotSegments, recomposeAuthority, normalizeComponentEncoding } = __webpack_require__(34834) +const SCHEMES = __webpack_require__(343) + +function normalize (uri, options) { + if (typeof uri === 'string') { + uri = serialize(parse(uri, options), options) + } else if (typeof uri === 'object') { + uri = parse(serialize(uri, options), options) + } + return uri +} + +function resolve (baseURI, relativeURI, options) { + const schemelessOptions = Object.assign({ scheme: 'null' }, options) + const resolved = resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true) + return serialize(resolved, { ...schemelessOptions, skipEscape: true }) +} + +function resolveComponents (base, relative, options, skipNormalization) { + const target = {} + if (!skipNormalization) { + base = parse(serialize(base, options), options) // normalize base components + relative = parse(serialize(relative, options), options) // normalize relative components + } + options = options || {} + + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme + // target.authority = relative.authority; + target.userinfo = relative.userinfo + target.host = relative.host + target.port = relative.port + target.path = removeDotSegments(relative.path || '') + target.query = relative.query + } else { + if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) { + // target.authority = relative.authority; + target.userinfo = relative.userinfo + target.host = relative.host + target.port = relative.port + target.path = removeDotSegments(relative.path || '') + target.query = relative.query + } else { + if (!relative.path) { + target.path = base.path + if (relative.query !== undefined) { + target.query = relative.query + } else { + target.query = base.query + } + } else { + if (relative.path.charAt(0) === '/') { + target.path = removeDotSegments(relative.path) + } else { + if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) { + target.path = '/' + relative.path + } else if (!base.path) { + target.path = relative.path + } else { + target.path = base.path.slice(0, base.path.lastIndexOf('/') + 1) + relative.path + } + target.path = removeDotSegments(target.path) + } + target.query = relative.query + } + // target.authority = base.authority; + target.userinfo = base.userinfo + target.host = base.host + target.port = base.port + } + target.scheme = base.scheme + } + + target.fragment = relative.fragment + + return target +} + +function equal (uriA, uriB, options) { + if (typeof uriA === 'string') { + uriA = unescape(uriA) + uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { ...options, skipEscape: true }) + } else if (typeof uriA === 'object') { + uriA = serialize(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true }) + } + + if (typeof uriB === 'string') { + uriB = unescape(uriB) + uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { ...options, skipEscape: true }) + } else if (typeof uriB === 'object') { + uriB = serialize(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true }) + } + + return uriA.toLowerCase() === uriB.toLowerCase() +} + +function serialize (cmpts, opts) { + const components = { + host: cmpts.host, + scheme: cmpts.scheme, + userinfo: cmpts.userinfo, + port: cmpts.port, + path: cmpts.path, + query: cmpts.query, + nid: cmpts.nid, + nss: cmpts.nss, + uuid: cmpts.uuid, + fragment: cmpts.fragment, + reference: cmpts.reference, + resourceName: cmpts.resourceName, + secure: cmpts.secure, + error: '' + } + const options = Object.assign({}, opts) + const uriTokens = [] + + // find scheme handler + const schemeHandler = SCHEMES[(options.scheme || components.scheme || '').toLowerCase()] + + // perform scheme specific serialization + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options) + + if (components.path !== undefined) { + if (!options.skipEscape) { + components.path = escape(components.path) + + if (components.scheme !== undefined) { + components.path = components.path.split('%3A').join(':') + } + } else { + components.path = unescape(components.path) + } + } + + if (options.reference !== 'suffix' && components.scheme) { + uriTokens.push(components.scheme) + uriTokens.push(':') + } + + const authority = recomposeAuthority(components, options) + if (authority !== undefined) { + if (options.reference !== 'suffix') { + uriTokens.push('//') + } + + uriTokens.push(authority) + + if (components.path && components.path.charAt(0) !== '/') { + uriTokens.push('/') + } + } + if (components.path !== undefined) { + let s = components.path + + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { + s = removeDotSegments(s) + } + + if (authority === undefined) { + s = s.replace(/^\/\//u, '/%2F') // don't allow the path to start with "//" + } + + uriTokens.push(s) + } + + if (components.query !== undefined) { + uriTokens.push('?') + uriTokens.push(components.query) + } + + if (components.fragment !== undefined) { + uriTokens.push('#') + uriTokens.push(components.fragment) + } + return uriTokens.join('') +} + +const hexLookUp = Array.from({ length: 127 }, (v, k) => /[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(k))) + +function nonSimpleDomain (value) { + let code = 0 + for (let i = 0, len = value.length; i < len; ++i) { + code = value.charCodeAt(i) + if (code > 126 || hexLookUp[code]) { + return true + } + } + return false +} + +const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u + +function parse (uri, opts) { + const options = Object.assign({}, opts) + const parsed = { + scheme: undefined, + userinfo: undefined, + host: '', + port: undefined, + path: '', + query: undefined, + fragment: undefined + } + const gotEncoding = uri.indexOf('%') !== -1 + let isIP = false + if (options.reference === 'suffix') uri = (options.scheme ? options.scheme + ':' : '') + '//' + uri + + const matches = uri.match(URI_PARSE) + + if (matches) { + // store each component + parsed.scheme = matches[1] + parsed.userinfo = matches[3] + parsed.host = matches[4] + parsed.port = parseInt(matches[5], 10) + parsed.path = matches[6] || '' + parsed.query = matches[7] + parsed.fragment = matches[8] + + // fix port number + if (isNaN(parsed.port)) { + parsed.port = matches[5] + } + if (parsed.host) { + const ipv4result = normalizeIPv4(parsed.host) + if (ipv4result.isIPV4 === false) { + const ipv6result = normalizeIPv6(ipv4result.host, { isIPV4: false }) + parsed.host = ipv6result.host.toLowerCase() + isIP = ipv6result.isIPV6 + } else { + parsed.host = ipv4result.host + isIP = true + } + } + if (parsed.scheme === undefined && parsed.userinfo === undefined && parsed.host === undefined && parsed.port === undefined && !parsed.path && parsed.query === undefined) { + parsed.reference = 'same-document' + } else if (parsed.scheme === undefined) { + parsed.reference = 'relative' + } else if (parsed.fragment === undefined) { + parsed.reference = 'absolute' + } else { + parsed.reference = 'uri' + } + + // check for reference errors + if (options.reference && options.reference !== 'suffix' && options.reference !== parsed.reference) { + parsed.error = parsed.error || 'URI is not a ' + options.reference + ' reference.' + } + + // find scheme handler + const schemeHandler = SCHEMES[(options.scheme || parsed.scheme || '').toLowerCase()] + + // check if scheme can't handle IRIs + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + // if host component is a domain name + if (parsed.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost)) && isIP === false && nonSimpleDomain(parsed.host)) { + // convert Unicode IDN -> ASCII IDN + try { + parsed.host = URL.domainToASCII(parsed.host.toLowerCase()) + } catch (e) { + parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e + } + } + // convert IRI -> URI + } + + if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) { + if (gotEncoding && parsed.scheme !== undefined) { + parsed.scheme = unescape(parsed.scheme) + } + if (gotEncoding && parsed.userinfo !== undefined) { + parsed.userinfo = unescape(parsed.userinfo) + } + if (gotEncoding && parsed.host !== undefined) { + parsed.host = unescape(parsed.host) + } + if (parsed.path !== undefined && parsed.path.length) { + parsed.path = escape(unescape(parsed.path)) + } + if (parsed.fragment !== undefined && parsed.fragment.length) { + parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)) + } + } + + // perform scheme specific parsing + if (schemeHandler && schemeHandler.parse) { + schemeHandler.parse(parsed, options) + } + } else { + parsed.error = parsed.error || 'URI can not be parsed.' + } + return parsed +} + +const fastUri = { + SCHEMES, + normalize, + resolve, + resolveComponents, + equal, + serialize, + parse +} + +module.exports = fastUri +module.exports["default"] = fastUri +module.exports.fastUri = fastUri + + +/***/ }), + +/***/ 343: +/***/ ((module) => { + +"use strict"; + + +const UUID_REG = /^[\da-f]{8}\b-[\da-f]{4}\b-[\da-f]{4}\b-[\da-f]{4}\b-[\da-f]{12}$/iu +const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu + +function isSecure (wsComponents) { + return typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === 'wss' +} + +function httpParse (components) { + if (!components.host) { + components.error = components.error || 'HTTP URIs must have a host.' + } + + return components +} + +function httpSerialize (components) { + const secure = String(components.scheme).toLowerCase() === 'https' + + // normalize the default port + if (components.port === (secure ? 443 : 80) || components.port === '') { + components.port = undefined + } + + // normalize the empty path + if (!components.path) { + components.path = '/' + } + + // NOTE: We do not parse query strings for HTTP URIs + // as WWW Form Url Encoded query strings are part of the HTML4+ spec, + // and not the HTTP spec. + + return components +} + +function wsParse (wsComponents) { +// indicate if the secure flag is set + wsComponents.secure = isSecure(wsComponents) + + // construct resouce name + wsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : '') + wsComponents.path = undefined + wsComponents.query = undefined + + return wsComponents +} + +function wsSerialize (wsComponents) { +// normalize the default port + if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === '') { + wsComponents.port = undefined + } + + // ensure scheme matches secure flag + if (typeof wsComponents.secure === 'boolean') { + wsComponents.scheme = (wsComponents.secure ? 'wss' : 'ws') + wsComponents.secure = undefined + } + + // reconstruct path from resource name + if (wsComponents.resourceName) { + const [path, query] = wsComponents.resourceName.split('?') + wsComponents.path = (path && path !== '/' ? path : undefined) + wsComponents.query = query + wsComponents.resourceName = undefined + } + + // forbid fragment component + wsComponents.fragment = undefined + + return wsComponents +} + +function urnParse (urnComponents, options) { + if (!urnComponents.path) { + urnComponents.error = 'URN can not be parsed' + return urnComponents + } + const matches = urnComponents.path.match(URN_REG) + if (matches) { + const scheme = options.scheme || urnComponents.scheme || 'urn' + urnComponents.nid = matches[1].toLowerCase() + urnComponents.nss = matches[2] + const urnScheme = `${scheme}:${options.nid || urnComponents.nid}` + const schemeHandler = SCHEMES[urnScheme] + urnComponents.path = undefined + + if (schemeHandler) { + urnComponents = schemeHandler.parse(urnComponents, options) + } + } else { + urnComponents.error = urnComponents.error || 'URN can not be parsed.' + } + + return urnComponents +} + +function urnSerialize (urnComponents, options) { + const scheme = options.scheme || urnComponents.scheme || 'urn' + const nid = urnComponents.nid.toLowerCase() + const urnScheme = `${scheme}:${options.nid || nid}` + const schemeHandler = SCHEMES[urnScheme] + + if (schemeHandler) { + urnComponents = schemeHandler.serialize(urnComponents, options) + } + + const uriComponents = urnComponents + const nss = urnComponents.nss + uriComponents.path = `${nid || options.nid}:${nss}` + + options.skipEscape = true + return uriComponents +} + +function urnuuidParse (urnComponents, options) { + const uuidComponents = urnComponents + uuidComponents.uuid = uuidComponents.nss + uuidComponents.nss = undefined + + if (!options.tolerant && (!uuidComponents.uuid || !UUID_REG.test(uuidComponents.uuid))) { + uuidComponents.error = uuidComponents.error || 'UUID is not valid.' + } + + return uuidComponents +} + +function urnuuidSerialize (uuidComponents) { + const urnComponents = uuidComponents + // normalize UUID + urnComponents.nss = (uuidComponents.uuid || '').toLowerCase() + return urnComponents +} + +const http = { + scheme: 'http', + domainHost: true, + parse: httpParse, + serialize: httpSerialize +} + +const https = { + scheme: 'https', + domainHost: http.domainHost, + parse: httpParse, + serialize: httpSerialize +} + +const ws = { + scheme: 'ws', + domainHost: true, + parse: wsParse, + serialize: wsSerialize +} + +const wss = { + scheme: 'wss', + domainHost: ws.domainHost, + parse: ws.parse, + serialize: ws.serialize +} + +const urn = { + scheme: 'urn', + parse: urnParse, + serialize: urnSerialize, + skipNormalize: true +} + +const urnuuid = { + scheme: 'urn:uuid', + parse: urnuuidParse, + serialize: urnuuidSerialize, + skipNormalize: true +} + +const SCHEMES = { + http, + https, + ws, + wss, + urn, + 'urn:uuid': urnuuid +} + +module.exports = SCHEMES + + +/***/ }), + +/***/ 64914: +/***/ ((module) => { + +"use strict"; + + +const HEX = { + 0: 0, + 1: 1, + 2: 2, + 3: 3, + 4: 4, + 5: 5, + 6: 6, + 7: 7, + 8: 8, + 9: 9, + a: 10, + A: 10, + b: 11, + B: 11, + c: 12, + C: 12, + d: 13, + D: 13, + e: 14, + E: 14, + f: 15, + F: 15 +} + +module.exports = { + HEX +} + + +/***/ }), + +/***/ 34834: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const { HEX } = __webpack_require__(64914) + +function normalizeIPv4 (host) { + if (findToken(host, '.') < 3) { return { host, isIPV4: false } } + const matches = host.match(/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/u) || [] + const [address] = matches + if (address) { + return { host: stripLeadingZeros(address, '.'), isIPV4: true } + } else { + return { host, isIPV4: false } + } +} + +/** + * @param {string[]} input + * @param {boolean} [keepZero=false] + * @returns {string|undefined} + */ +function stringArrayToHexStripped (input, keepZero = false) { + let acc = '' + let strip = true + for (const c of input) { + if (HEX[c] === undefined) return undefined + if (c !== '0' && strip === true) strip = false + if (!strip) acc += c + } + if (keepZero && acc.length === 0) acc = '0' + return acc +} + +function getIPV6 (input) { + let tokenCount = 0 + const output = { error: false, address: '', zone: '' } + const address = [] + const buffer = [] + let isZone = false + let endipv6Encountered = false + let endIpv6 = false + + function consume () { + if (buffer.length) { + if (isZone === false) { + const hex = stringArrayToHexStripped(buffer) + if (hex !== undefined) { + address.push(hex) + } else { + output.error = true + return false + } + } + buffer.length = 0 + } + return true + } + + for (let i = 0; i < input.length; i++) { + const cursor = input[i] + if (cursor === '[' || cursor === ']') { continue } + if (cursor === ':') { + if (endipv6Encountered === true) { + endIpv6 = true + } + if (!consume()) { break } + tokenCount++ + address.push(':') + if (tokenCount > 7) { + // not valid + output.error = true + break + } + if (i - 1 >= 0 && input[i - 1] === ':') { + endipv6Encountered = true + } + continue + } else if (cursor === '%') { + if (!consume()) { break } + // switch to zone detection + isZone = true + } else { + buffer.push(cursor) + continue + } + } + if (buffer.length) { + if (isZone) { + output.zone = buffer.join('') + } else if (endIpv6) { + address.push(buffer.join('')) + } else { + address.push(stringArrayToHexStripped(buffer)) + } + } + output.address = address.join('') + return output +} + +function normalizeIPv6 (host, opts = {}) { + if (findToken(host, ':') < 2) { return { host, isIPV6: false } } + const ipv6 = getIPV6(host) + + if (!ipv6.error) { + let newHost = ipv6.address + let escapedHost = ipv6.address + if (ipv6.zone) { + newHost += '%' + ipv6.zone + escapedHost += '%25' + ipv6.zone + } + return { host: newHost, escapedHost, isIPV6: true } + } else { + return { host, isIPV6: false } + } +} + +function stripLeadingZeros (str, token) { + let out = '' + let skip = true + const l = str.length + for (let i = 0; i < l; i++) { + const c = str[i] + if (c === '0' && skip) { + if ((i + 1 <= l && str[i + 1] === token) || i + 1 === l) { + out += c + skip = false + } + } else { + if (c === token) { + skip = true + } else { + skip = false + } + out += c + } + } + return out +} + +function findToken (str, token) { + let ind = 0 + for (let i = 0; i < str.length; i++) { + if (str[i] === token) ind++ + } + return ind +} + +const RDS1 = /^\.\.?\//u +const RDS2 = /^\/\.(?:\/|$)/u +const RDS3 = /^\/\.\.(?:\/|$)/u +const RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/u + +function removeDotSegments (input) { + const output = [] + + while (input.length) { + if (input.match(RDS1)) { + input = input.replace(RDS1, '') + } else if (input.match(RDS2)) { + input = input.replace(RDS2, '/') + } else if (input.match(RDS3)) { + input = input.replace(RDS3, '/') + output.pop() + } else if (input === '.' || input === '..') { + input = '' + } else { + const im = input.match(RDS5) + if (im) { + const s = im[0] + input = input.slice(s.length) + output.push(s) + } else { + throw new Error('Unexpected dot segment condition') + } + } + } + return output.join('') +} + +function normalizeComponentEncoding (components, esc) { + const func = esc !== true ? escape : unescape + if (components.scheme !== undefined) { + components.scheme = func(components.scheme) + } + if (components.userinfo !== undefined) { + components.userinfo = func(components.userinfo) + } + if (components.host !== undefined) { + components.host = func(components.host) + } + if (components.path !== undefined) { + components.path = func(components.path) + } + if (components.query !== undefined) { + components.query = func(components.query) + } + if (components.fragment !== undefined) { + components.fragment = func(components.fragment) + } + return components +} + +function recomposeAuthority (components, options) { + const uriTokens = [] + + if (components.userinfo !== undefined) { + uriTokens.push(components.userinfo) + uriTokens.push('@') + } + + if (components.host !== undefined) { + let host = unescape(components.host) + const ipV4res = normalizeIPv4(host) + + if (ipV4res.isIPV4) { + host = ipV4res.host + } else { + const ipV6res = normalizeIPv6(ipV4res.host, { isIPV4: false }) + if (ipV6res.isIPV6 === true) { + host = `[${ipV6res.escapedHost}]` + } else { + host = components.host + } + } + uriTokens.push(host) + } + + if (typeof components.port === 'number' || typeof components.port === 'string') { + uriTokens.push(':') + uriTokens.push(String(components.port)) + } + + return uriTokens.length ? uriTokens.join('') : undefined +}; + +module.exports = { + recomposeAuthority, + normalizeComponentEncoding, + removeDotSegments, + normalizeIPv4, + normalizeIPv6, + stringArrayToHexStripped +} + + +/***/ }), + +/***/ 90294: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + HI: () => (/* reexport */ mimcsponge_buildMimcSponge), + vu: () => (/* reexport */ pedersen_hash_buildPedersenHash) +}); + +// UNUSED EXPORTS: SMT, SMTMemDb, buildBabyjub, buildEddsa, buildMimc7, buildPoseidon, buildPoseidonOpt, buildPoseidonReference, buildPoseidonWasm, buildSMT, evmasm, mimc7Contract, mimcSpongecontract, newMemEmptyTrie, poseidonContract + +;// CONCATENATED MODULE: ./node_modules/circomlibjs/node_modules/ffjavascript/build/browser.esm.js +/* global BigInt */ +const hexLen = [ 0, 1, 2, 2, 3, 3, 3, 3, 4 ,4 ,4 ,4 ,4 ,4 ,4 ,4]; + +function fromString(s, radix) { + if ((!radix)||(radix==10)) { + return BigInt(s); + } else if (radix==16) { + if (s.slice(0,2) == "0x") { + return BigInt(s); + } else { + return BigInt("0x"+s); + } + } +} + +const e = fromString; + +function fromArray(a, radix) { + let acc =BigInt(0); + radix = BigInt(radix); + for (let i=0; i> BigInt(n); +} + +const shl = shiftLeft; +const shr = shiftRight; + +function isOdd$5(a) { + return (BigInt(a) & BigInt(1)) == BigInt(1); +} + + +function naf(n) { + let E = BigInt(n); + const res = []; + while (E) { + if (E & BigInt(1)) { + const z = 2 - Number(E % BigInt(4)); + res.push( z ); + E = E - BigInt(z); + } else { + res.push( 0 ); + } + E = E >> BigInt(1); + } + return res; +} + + +function bits(n) { + let E = BigInt(n); + const res = []; + while (E) { + if (E & BigInt(1)) { + res.push(1); + } else { + res.push( 0 ); + } + E = E >> BigInt(1); + } + return res; +} + +function toNumber$1(s) { + if (s>BigInt(Number.MAX_SAFE_INTEGER )) { + throw new Error("Number too big"); + } + return Number(s); +} + +function toArray(s, radix) { + const res = []; + let rem = BigInt(s); + radix = BigInt(radix); + while (rem) { + res.unshift( Number(rem % radix)); + rem = rem / radix; + } + return res; +} + + +function add(a, b) { + return BigInt(a) + BigInt(b); +} + +function sub(a, b) { + return BigInt(a) - BigInt(b); +} + +function neg(a) { + return -BigInt(a); +} + +function mul(a, b) { + return BigInt(a) * BigInt(b); +} + +function square$2(a) { + return BigInt(a) * BigInt(a); +} + +function pow(a, b) { + return BigInt(a) ** BigInt(b); +} + +function exp$1(a, b) { + return BigInt(a) ** BigInt(b); +} + +function abs$1(a) { + return BigInt(a) >= 0 ? BigInt(a) : -BigInt(a); +} + +function div(a, b) { + return BigInt(a) / BigInt(b); +} + +function mod(a, b) { + return BigInt(a) % BigInt(b); +} + +function eq(a, b) { + return BigInt(a) == BigInt(b); +} + +function neq(a, b) { + return BigInt(a) != BigInt(b); +} + +function lt(a, b) { + return BigInt(a) < BigInt(b); +} + +function gt(a, b) { + return BigInt(a) > BigInt(b); +} + +function leq(a, b) { + return BigInt(a) <= BigInt(b); +} + +function geq(a, b) { + return BigInt(a) >= BigInt(b); +} + +function band(a, b) { + return BigInt(a) & BigInt(b); +} + +function bor(a, b) { + return BigInt(a) | BigInt(b); +} + +function bxor(a, b) { + return BigInt(a) ^ BigInt(b); +} + +function land(a, b) { + return BigInt(a) && BigInt(b); +} + +function lor(a, b) { + return BigInt(a) || BigInt(b); +} + +function lnot(a) { + return !BigInt(a); +} + +// Returns a buffer with Little Endian Representation +function toRprLE(buff, o, e, n8) { + const s = "0000000" + e.toString(16); + const v = new Uint32Array(buff.buffer, buff.byteOffset + o, n8/4); + const l = (((s.length-7)*4 - 1) >> 5)+1; // Number of 32bit words; + for (let i=0; i> 5)+1; // Number of 32bit words; + for (let i=0; i a[a.length-i-1] = ch.toString(16).padStart(8,"0") ); + return fromString(a.join(""), 16); +} + +// Pases a buffer with Big Endian Representation +function fromRprBE(buff, o, n8) { + n8 = n8 || buff.byteLength; + o = o || 0; + const v = new DataView(buff.buffer, buff.byteOffset + o, n8); + const a = new Array(n8/4); + for (let i=0; i. +*/ + +/* + This library does operations on polynomials with coefficients in a field F. + + A polynomial P(x) = p0 + p1 * x + p2 * x^2 + ... + pn * x^n is represented + by the array [ p0, p1, p2, ... , pn ]. + */ + +class PolField { + constructor (F) { + this.F = F; + + let rem = F.sqrt_t; + let s = F.sqrt_s; + + const five = this.F.add(this.F.add(this.F.two, this.F.two), this.F.one); + + this.w = new Array(s+1); + this.wi = new Array(s+1); + this.w[s] = this.F.pow(five, rem); + this.wi[s] = this.F.inv(this.w[s]); + + let n=s-1; + while (n>=0) { + this.w[n] = this.F.square(this.w[n+1]); + this.wi[n] = this.F.square(this.wi[n+1]); + n--; + } + + + this.roots = []; +/* for (let i=0; i<16; i++) { + let r = this.F.one; + n = 1 << i; + const rootsi = new Array(n); + for (let j=0; j this.F.sqrt_s) n = this.s; + for (let i=n; (i>=0) && (!this.roots[i]); i--) { + let r = this.F.one; + const nroots = 1 << i; + const rootsi = new Array(nroots); + for (let j=0; j a.length) { + [b, a] = [a, b]; + } + + if ((b.length <= 2) || (b.length < log2$2(a.length))) { + return this.mulNormal(a,b); + } else { + return this.mulFFT(a,b); + } + } + + mulNormal(a, b) { + let res = []; + for (let i=0; i0) { + const z = new Array(n).fill(this.F.zero); + return z.concat(p); + } else { + if (-n >= p.length) return []; + return p.slice(-n); + } + } + + eval2(p, x) { + let v = this.F.zero; + let ix = this.F.one; + for (let i=0; i> 1), + F.mul( + x, + _eval(p, newX, offset+step , step << 1, n >> 1))); + return res; + } + } + + lagrange(points) { + let roots = [this.F.one]; + for (let i=0; i> 1; + const p1 = this._fft(pall, bits-1, offset, step*2); + const p2 = this._fft(pall, bits-1, offset+step, step*2); + + const out = new Array(n); + + let m= this.F.one; + for (let i=0; i0 && this.F.eq(p[i], this.F.zero) ) i--; + return p.slice(0, i+1); + } + + eq(a, b) { + const pa = this.reduce(a); + const pb = this.reduce(b); + + if (pa.length != pb.length) return false; + for (let i=0; i=0; i--) { + res[i] = this.F.add(this.F.mul(res[i+1], r), p[i+1]); + } + return res; + } + + _next2Power(v) { + v--; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + v++; + return v; + } + + toString(p) { + const ap = this.normalize(p); + let S = ""; + for (let i=ap.length-1; i>=0; i--) { + if (!this.F.eq(p[i], this.F.zero)) { + if (S!="") S += " + "; + S = S + p[i].toString(10); + if (i>0) { + S = S + "x"; + if (i>1) { + S = S + "^" +i; + } + } + } + } + return S; + } + + normalize(p) { + const res = new Array(p.length); + for (let i=0; i + // rec = x^(k-2-scaleV)/ v + // + // res = x^m/v = x^(m + (2*k-2 - scaleV) - (2*k-2 - scaleV)) /v => + // res = rec * x^(m - (2*k-2 - scaleV)) => + // res = rec * x^(m - 2*k + 2 + scaleV) + + const rec = this._reciprocal(this.scaleX(v, scaleV), kbits); + const res = this.scaleX(rec, m - 2*k + 2 + scaleV); + + return res; + } + + div(_u, _v) { + if (_u.length < _v.length) return []; + const kbits = log2$2(_v.length-1)+1; + const k = 1 << kbits; + + const u = this.scaleX(_u, k-_v.length); + const v = this.scaleX(_v, k-_v.length); + + const n = v.length-1; + let m = u.length-1; + + const s = this._reciprocal(v, kbits); + let t; + if (m>2*n) { + t = this.sub(this.scaleX([this.F.one], 2*n), this.mul(s, v)); + } + + let q = []; + let rem = u; + let us, ut; + let finish = false; + + while (!finish) { + us = this.mul(rem, s); + q = this.add(q, this.scaleX(us, -2*n)); + + if ( m > 2*n ) { + ut = this.mul(rem, t); + rem = this.scaleX(ut, -2*n); + m = rem.length-1; + } else { + finish = true; + } + } + + return q; + } + + + // returns the ith nth-root of one + oneRoot(n, i) { + let nbits = log2$2(n-1)+1; + let res = this.F.one; + let r = i; + + if(i>=n) { + throw new Error("Given 'i' should be lower than 'n'"); + } + else if (1<0) { + if (r & 1 == 1) { + res = this.F.mul(res, this.w[nbits]); + } + r = r >> 1; + nbits --; + } + return res; + } + + computeVanishingPolinomial(bits, t) { + const m = 1 << bits; + return this.F.sub(this.F.pow(t, m), this.F.one); + } + + evaluateLagrangePolynomials(bits, t) { + const m= 1 << bits; + const tm = this.F.pow(t, m); + const u= new Array(m).fill(this.F.zero); + this._setRoots(bits); + const omega = this.w[bits]; + + if (this.F.eq(tm, this.F.one)) { + for (let i = 0; i < m; i++) { + if (this.F.eq(this.roots[bits][0],t)) { // i.e., t equals omega^i + u[i] = this.F.one; + return u; + } + } + } + + const z = this.F.sub(tm, this.F.one); + // let l = this.F.mul(z, this.F.pow(this.F.twoinv, m)); + let l = this.F.mul(z, this.F.inv(this.F.e(m))); + for (let i = 0; i < m; i++) { + u[i] = this.F.mul(l, this.F.inv(this.F.sub(t,this.roots[bits][i]))); + l = this.F.mul(l, omega); + } + + return u; + } + + log2(V) { + return log2$2(V); + } +} + +function log2$2( V ) +{ + return( ( ( V & 0xFFFF0000 ) !== 0 ? ( V &= 0xFFFF0000, 16 ) : 0 ) | ( ( V & 0xFF00FF00 ) !== 0 ? ( V &= 0xFF00FF00, 8 ) : 0 ) | ( ( V & 0xF0F0F0F0 ) !== 0 ? ( V &= 0xF0F0F0F0, 4 ) : 0 ) | ( ( V & 0xCCCCCCCC ) !== 0 ? ( V &= 0xCCCCCCCC, 2 ) : 0 ) | ( ( V & 0xAAAAAAAA ) !== 0 ) ); +} + + +function __fft$1(PF, pall, bits, offset, step) { + + const n = 1 << bits; + if (n==1) { + return [ pall[offset] ]; + } else if (n==2) { + return [ + PF.F.add(pall[offset], pall[offset + step]), + PF.F.sub(pall[offset], pall[offset + step])]; + } + + const ndiv2 = n >> 1; + const p1 = __fft$1(PF, pall, bits-1, offset, step*2); + const p2 = __fft$1(PF, pall, bits-1, offset+step, step*2); + + const out = new Array(n); + + for (let i=0; i> 1; + const p1 = __fft2(PF, pall.slice(0, ndiv2), bits-1); + const p2 = __fft2(PF, pall.slice(ndiv2), bits-1); + + const out = new Array(n); + + for (let i=0; i>=1; + } + return res; +} + +function rev(idx, bits) { + return ( + _revTable$1[idx >>> 24] | + (_revTable$1[(idx >>> 16) & 0xFF] << 8) | + (_revTable$1[(idx >>> 8) & 0xFF] << 16) | + (_revTable$1[idx & 0xFF] << 24) + ) >>> (32-bits); +} + +function __bitReverse(p, bits) { + for (let k=0; kk) { + const tmp= p[k]; + p[k] = p[r]; + p[r] = tmp; } } } -module.exports = ModuleBuilderWat; +/* + Copyright 2018 0kims association. + + This file is part of snarkjs. + + snarkjs is a free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or (at your option) + any later version. + + snarkjs is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along with + snarkjs. If not, see . +*/ -/***/ }), -/***/ 77831: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +function mulScalar(F, base, e) { + let res; + + if (isZero$1(e)) return F.zero; + + const n = naf(e); + + if (n[n.length-1] == 1) { + res = base; + } else if (n[n.length-1] == -1) { + res = F.neg(base); + } else { + throw new Error("invlaud NAF"); + } + + for (let i=n.length-2; i>=0; i--) { + + res = F.double(res); + + if (n[i] == 1) { + res = F.add(res, base); + } else if (n[i] == -1) { + res = F.sub(res, base); + } + } + + return res; +} + + +/* +exports.mulScalar = (F, base, e) =>{ + let res = F.zero; + let rem = bigInt(e); + let exp = base; + + while (! rem.eq(bigInt.zero)) { + if (rem.and(bigInt.one).eq(bigInt.one)) { + res = F.add(res, exp); + } + exp = F.double(exp); + rem = rem.shiftRight(1); + } + + return res; +}; +*/ + + +function exp(F, base, e) { + + if (isZero$1(e)) return F.one; + + const n = bits(e); + + if (n.length==0) return F.one; + + let res = base; + + for (let i=n.length-2; i>=0; i--) { + + res = F.square(res); + + if (n[i]) { + res = F.mul(res, base); + } + } + + return res; +} + +// Check here: https://eprint.iacr.org/2012/685.pdf + +function buildSqrt (F) { + if ((F.m % 2) == 1) { + if (eq(mod(F.p, 4), 1 )) { + if (eq(mod(F.p, 8), 1 )) { + if (eq(mod(F.p, 16), 1 )) { + // alg7_muller(F); + alg5_tonelliShanks(F); + } else if (eq(mod(F.p, 16), 9 )) { + alg4_kong(F); + } else { + throw new Error("Field withot sqrt"); + } + } else if (eq(mod(F.p, 8), 5 )) { + alg3_atkin(F); + } else { + throw new Error("Field withot sqrt"); + } + } else if (eq(mod(F.p, 4), 3 )) { + alg2_shanks(F); + } + } else { + const pm2mod4 = mod(pow(F.p, F.m/2), 4); + if (pm2mod4 == 1) { + alg10_adj(F); + } else if (pm2mod4 == 3) { + alg9_adj(F); + } else { + alg8_complex(F); + } + + } +} + + +function alg5_tonelliShanks(F) { + F.sqrt_q = pow(F.p, F.m); + + F.sqrt_s = 0; + F.sqrt_t = sub(F.sqrt_q, 1); + + while (!isOdd$5(F.sqrt_t)) { + F.sqrt_s = F.sqrt_s + 1; + F.sqrt_t = div(F.sqrt_t, 2); + } + + let c0 = F.one; + + while (F.eq(c0, F.one)) { + const c = F.random(); + F.sqrt_z = F.pow(c, F.sqrt_t); + c0 = F.pow(F.sqrt_z, 2 ** (F.sqrt_s-1) ); + } + + F.sqrt_tm1d2 = div(sub(F.sqrt_t, 1),2); + + F.sqrt = function(a) { + const F=this; + if (F.isZero(a)) return F.zero; + let w = F.pow(a, F.sqrt_tm1d2); + const a0 = F.pow( F.mul(F.square(w), a), 2 ** (F.sqrt_s-1) ); + if (F.eq(a0, F.negone)) return null; + + let v = F.sqrt_s; + let x = F.mul(a, w); + let b = F.mul(x, w); + let z = F.sqrt_z; + while (!F.eq(b, F.one)) { + let b2k = F.square(b); + let k=1; + while (!F.eq(b2k, F.one)) { + b2k = F.square(b2k); + k++; + } + + w = z; + for (let i=0; i>> 0; + st[d] = (st[d] ^ st[a]) >>> 0; + st[d] = ((st[d] << 16) | ((st[d]>>>16) & 0xFFFF)) >>> 0; + + st[c] = (st[c] + st[d]) >>> 0; + st[b] = (st[b] ^ st[c]) >>> 0; + st[b] = ((st[b] << 12) | ((st[b]>>>20) & 0xFFF)) >>> 0; + + st[a] = (st[a] + st[b]) >>> 0; + st[d] = (st[d] ^ st[a]) >>> 0; + st[d] = ((st[d] << 8) | ((st[d]>>>24) & 0xFF)) >>> 0; + + st[c] = (st[c] + st[d]) >>> 0; + st[b] = (st[b] ^ st[c]) >>> 0; + st[b] = ((st[b] << 7) | ((st[b]>>>25) & 0x7F)) >>> 0; +} + +function doubleRound(st) { + quarterRound(st, 0, 4, 8,12); + quarterRound(st, 1, 5, 9,13); + quarterRound(st, 2, 6,10,14); + quarterRound(st, 3, 7,11,15); + + quarterRound(st, 0, 5,10,15); + quarterRound(st, 1, 6,11,12); + quarterRound(st, 2, 7, 8,13); + quarterRound(st, 3, 4, 9,14); +} + +class ChaCha { + + constructor(seed) { + seed = seed || [0,0,0,0,0,0,0,0]; + this.state = [ + 0x61707865, + 0x3320646E, + 0x79622D32, + 0x6B206574, + seed[0], + seed[1], + seed[2], + seed[3], + seed[4], + seed[5], + seed[6], + seed[7], + 0, + 0, + 0, + 0 + ]; + this.idx = 16; + this.buff = new Array(16); + } + + nextU32() { + if (this.idx == 16) this.update(); + return this.buff[this.idx++]; + } + + nextU64() { + return add(mul(this.nextU32(), 0x100000000), this.nextU32()); + } + + nextBool() { + return (this.nextU32() & 1) == 1; + } + + update() { + // Copy the state + for (let i=0; i<16; i++) this.buff[i] = this.state[i]; + + // Apply the rounds + for (let i=0; i<10; i++) doubleRound(this.buff); + + // Add to the initial + for (let i=0; i<16; i++) this.buff[i] = (this.buff[i] + this.state[i]) >>> 0; + + this.idx = 0; + + this.state[12] = (this.state[12] + 1) >>> 0; + if (this.state[12] != 0) return; + this.state[13] = (this.state[13] + 1) >>> 0; + if (this.state[13] != 0) return; + this.state[14] = (this.state[14] + 1) >>> 0; + if (this.state[14] != 0) return; + this.state[15] = (this.state[15] + 1) >>> 0; + } +} + +function getRandomBytes(n) { + let array = new Uint8Array(n); + { // Browser + if (typeof globalThis.crypto !== "undefined") { // Supported + globalThis.crypto.getRandomValues(array); + } else { // fallback + for (let i=0; i>>0; + } + } + } + return array; +} + +function getRandomSeed() { + const arr = getRandomBytes(32); + const arrV = new Uint32Array(arr.buffer); + const seed = []; + for (let i=0; i<8; i++) { + seed.push(arrV[i]); + } + return seed; +} + +let threadRng = null; + +function getThreadRng() { + if (threadRng) return threadRng; + threadRng = new ChaCha(getRandomSeed()); + return threadRng; +} + +/* + Copyright 2018 0kims association. + + This file is part of snarkjs. + + snarkjs is a free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or (at your option) + any later version. + + snarkjs is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along with + snarkjs. If not, see . +*/ + +/* + This library does operations on polynomials with coefficients in a field F. + + A polynomial P(x) = p0 + p1 * x + p2 * x^2 + ... + pn * x^n is represented + by the array [ p0, p1, p2, ... , pn ]. + */ + +class FFT { + constructor (G, F, opMulGF) { + this.F = F; + this.G = G; + this.opMulGF = opMulGF; + + let rem = F.sqrt_t || F.t; + let s = F.sqrt_s || F.s; + + let nqr = F.one; + while (F.eq(F.pow(nqr, F.half), F.one)) nqr = F.add(nqr, F.one); + + this.w = new Array(s+1); + this.wi = new Array(s+1); + this.w[s] = this.F.pow(nqr, rem); + this.wi[s] = this.F.inv(this.w[s]); + + let n=s-1; + while (n>=0) { + this.w[n] = this.F.square(this.w[n+1]); + this.wi[n] = this.F.square(this.wi[n+1]); + n--; + } + + + this.roots = []; + /* + for (let i=0; i<16; i++) { + let r = this.F.one; + n = 1 << i; + const rootsi = new Array(n); + for (let j=0; j=0) && (!this.roots[i]); i--) { + let r = this.F.one; + const nroots = 1 << i; + const rootsi = new Array(nroots); + for (let j=0; j> 1; + const p1 = __fft(PF, pall, bits-1, offset, step*2); + const p2 = __fft(PF, pall, bits-1, offset+step, step*2); + + const out = new Array(n); + + for (let i=0; i> this.one; + this.bitLength = bitLength$6(this.p); + this.mask = (this.one << BigInt(this.bitLength)) - this.one; + + this.n64 = Math.floor((this.bitLength - 1) / 64)+1; + this.n32 = this.n64*2; + this.n8 = this.n64*8; + this.R = this.e(this.one << BigInt(this.n64*64)); + this.Ri = this.inv(this.R); + + const e = this.negone >> this.one; + this.nqr = this.two; + let r = this.pow(this.nqr, e); + while (!this.eq(r, this.negone)) { + this.nqr = this.nqr + this.one; + r = this.pow(this.nqr, e); + } + + + this.s = 0; + this.t = this.negone; + + while ((this.t & this.one) == this.zero) { + this.s = this.s + 1; + this.t = this.t >> this.one; + } + + this.nqr_to_t = this.pow(this.nqr, this.t); + + buildSqrt(this); + + this.FFT = new FFT(this, this, this.mul.bind(this)); + + this.fft = this.FFT.fft.bind(this.FFT); + this.ifft = this.FFT.ifft.bind(this.FFT); + this.w = this.FFT.w; + this.wi = this.FFT.wi; + + this.shift = this.square(this.nqr); + this.k = this.exp(this.nqr, 2**this.s); + } + + e(a,b) { + let res; + if (!b) { + res = BigInt(a); + } else if (b==16) { + res = BigInt("0x"+a); + } + if (res < 0) { + let nres = -res; + if (nres >= this.p) nres = nres % this.p; + return this.p - nres; + } else { + return (res>= this.p) ? res%this.p : res; + } + + } + + add(a, b) { + const res = a + b; + return res >= this.p ? res-this.p : res; + } + + sub(a, b) { + return (a >= b) ? a-b : this.p-b+a; + } + + neg(a) { + return a ? this.p-a : a; + } + + mul(a, b) { + return (a*b)%this.p; + } + + mulScalar(base, s) { + return (base * this.e(s)) % this.p; + } + + square(a) { + return (a*a) % this.p; + } + + eq(a, b) { + return a==b; + } + + neq(a, b) { + return a!=b; + } + + lt(a, b) { + const aa = (a > this.half) ? a - this.p : a; + const bb = (b > this.half) ? b - this.p : b; + return aa < bb; + } + + gt(a, b) { + const aa = (a > this.half) ? a - this.p : a; + const bb = (b > this.half) ? b - this.p : b; + return aa > bb; + } + + leq(a, b) { + const aa = (a > this.half) ? a - this.p : a; + const bb = (b > this.half) ? b - this.p : b; + return aa <= bb; + } + + geq(a, b) { + const aa = (a > this.half) ? a - this.p : a; + const bb = (b > this.half) ? b - this.p : b; + return aa >= bb; + } + + div(a, b) { + return this.mul(a, this.inv(b)); + } + + idiv(a, b) { + if (!b) throw new Error("Division by zero"); + return a / b; + } + + inv(a) { + if (!a) throw new Error("Division by zero"); + + let t = this.zero; + let r = this.p; + let newt = this.one; + let newr = a % this.p; + while (newr) { + let q = r/newr; + [t, newt] = [newt, t-q*newt]; + [r, newr] = [newr, r-q*newr]; + } + if (t= this.p ? res-this.p : res; + } + + bor(a, b) { + const res = ((a | b) & this.mask); + return res >= this.p ? res-this.p : res; + } + + bxor(a, b) { + const res = ((a ^ b) & this.mask); + return res >= this.p ? res-this.p : res; + } + + bnot(a) { + const res = a ^ this.mask; + return res >= this.p ? res-this.p : res; + } + + shl(a, b) { + if (Number(b) < this.bitLength) { + const res = (a << b) & this.mask; + return res >= this.p ? res-this.p : res; + } else { + const nb = this.p - b; + if (Number(nb) < this.bitLength) { + return a >> nb; + } else { + return this.zero; + } + } + } + + shr(a, b) { + if (Number(b) < this.bitLength) { + return a >> b; + } else { + const nb = this.p - b; + if (Number(nb) < this.bitLength) { + const res = (a << nb) & this.mask; + return res >= this.p ? res-this.p : res; + } else { + return 0; + } + } + } + + land(a, b) { + return (a && b) ? this.one : this.zero; + } + + lor(a, b) { + return (a || b) ? this.one : this.zero; + } + + lnot(a) { + return (a) ? this.zero : this.one; + } + + sqrt_old(n) { + + if (n == this.zero) return this.zero; + + // Test that have solution + const res = this.pow(n, this.negone >> this.one); + if ( res != this.one ) return null; + + let m = this.s; + let c = this.nqr_to_t; + let t = this.pow(n, this.t); + let r = this.pow(n, this.add(this.t, this.one) >> this.one ); + + while ( t != this.one ) { + let sq = this.square(t); + let i = 1; + while (sq != this.one ) { + i++; + sq = this.square(sq); + } + + // b = c ^ m-i-1 + let b = c; + for (let j=0; j< m-i-1; j ++) b = this.square(b); + + m = i; + c = this.square(b); + t = this.mul(t, c); + r = this.mul(r, b); + } + + if (r > (this.p >> this.one)) { + r = this.neg(r); + } + + return r; + } + + normalize(a, b) { + a = BigInt(a,b); + if (a < 0) { + let na = -a; + if (na >= this.p) na = na % this.p; + return this.p - na; + } else { + return (a>= this.p) ? a%this.p : a; + } + } + + random() { + const nBytes = (this.bitLength*2 / 8); + let res =this.zero; + for (let i=0; i this.half)&&(base == 10)) { + const v = this.p-a; + vs = "-"+v.toString(base); + } else { + vs = a.toString(base); + } + return vs; + } + + isZero(a) { + return a == this.zero; + } + + fromRng(rng) { + let v; + do { + v=this.zero; + for (let i=0; i= this.p); + v = (v * this.Ri) % this.p; // Convert from montgomery + return v; + } + + fft(a) { + return this.FFT.fft(a); + } + + ifft(a) { + return this.FFT.ifft(a); + } + + // Returns a buffer with Little Endian Representation + toRprLE(buff, o, e) { + toRprLE(buff, o, e, this.n64*8); + } + + // Returns a buffer with Big Endian Representation + toRprBE(buff, o, e) { + toRprBE(buff, o, e, this.n64*8); + } + + // Returns a buffer with Big Endian Montgomery Representation + toRprBEM(buff, o, e) { + return this.toRprBE(buff, o, this.mul(this.R, e)); + } + + toRprLEM(buff, o, e) { + return this.toRprLE(buff, o, this.mul(this.R, e)); + } + + + // Pases a buffer with Little Endian Representation + fromRprLE(buff, o) { + return fromRprLE(buff, o, this.n8); + } + + // Pases a buffer with Big Endian Representation + fromRprBE(buff, o) { + return fromRprBE(buff, o, this.n8); + } + + fromRprLEM(buff, o) { + return this.mul(this.fromRprLE(buff, o), this.Ri); + } + + fromRprBEM(buff, o) { + return this.mul(this.fromRprBE(buff, o), this.Ri); + } + + toObject(a) { + return a; + } +} + +/* + Copyright 2018 0kims association. + + This file is part of snarkjs. + + snarkjs is a free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or (at your option) + any later version. + + snarkjs is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along with + snarkjs. If not, see . +*/ + + +class F2Field { + constructor(F, nonResidue) { + this.type="F2"; + this.F = F; + this.zero = [this.F.zero, this.F.zero]; + this.one = [this.F.one, this.F.zero]; + this.negone = this.neg(this.one); + this.nonResidue = nonResidue; + this.m = F.m*2; + this.p = F.p; + this.n64 = F.n64*2; + this.n32 = this.n64*2; + this.n8 = this.n64*8; + + buildSqrt(this); + } + + _mulByNonResidue(a) { + return this.F.mul(this.nonResidue, a); + } + + copy(a) { + return [this.F.copy(a[0]), this.F.copy(a[1])]; + } + + add(a, b) { + return [ + this.F.add(a[0], b[0]), + this.F.add(a[1], b[1]) + ]; + } + + double(a) { + return this.add(a,a); + } + + sub(a, b) { + return [ + this.F.sub(a[0], b[0]), + this.F.sub(a[1], b[1]) + ]; + } + + neg(a) { + return this.sub(this.zero, a); + } + + conjugate(a) { + return [ + a[0], + this.F.neg(a[1]) + ]; + } + + mul(a, b) { + const aA = this.F.mul(a[0] , b[0]); + const bB = this.F.mul(a[1] , b[1]); + + return [ + this.F.add( aA , this._mulByNonResidue(bB)), + this.F.sub( + this.F.mul( + this.F.add(a[0], a[1]), + this.F.add(b[0], b[1])), + this.F.add(aA, bB))]; + } + + inv(a) { + const t0 = this.F.square(a[0]); + const t1 = this.F.square(a[1]); + const t2 = this.F.sub(t0, this._mulByNonResidue(t1)); + const t3 = this.F.inv(t2); + return [ + this.F.mul(a[0], t3), + this.F.neg(this.F.mul( a[1], t3)) ]; + } + + div(a, b) { + return this.mul(a, this.inv(b)); + } + + square(a) { + const ab = this.F.mul(a[0] , a[1]); + + /* + [ + (a + b) * (a + non_residue * b) - ab - non_residue * ab, + ab + ab + ]; + */ + + return [ + this.F.sub( + this.F.mul( + this.F.add(a[0], a[1]) , + this.F.add( + a[0] , + this._mulByNonResidue(a[1]))), + this.F.add( + ab, + this._mulByNonResidue(ab))), + this.F.add(ab, ab) + ]; + } + + isZero(a) { + return this.F.isZero(a[0]) && this.F.isZero(a[1]); + } + + eq(a, b) { + return this.F.eq(a[0], b[0]) && this.F.eq(a[1], b[1]); + } + + mulScalar(base, e) { + return mulScalar(this, base, e); + } + + pow(base, e) { + return exp(this, base, e); + } + + exp(base, e) { + return exp(this, base, e); + } + + toString(a) { + return `[ ${this.F.toString(a[0])} , ${this.F.toString(a[1])} ]`; + } + + fromRng(rng) { + const c0 = this.F.fromRng(rng); + const c1 = this.F.fromRng(rng); + return [c0, c1]; + } + + gt(a, b) { + if (this.F.gt(a[0], b[0])) return true; + if (this.F.gt(b[0], a[0])) return false; + if (this.F.gt(a[1], b[1])) return true; + return false; + } + + geq(a, b) { + return this.gt(a, b) || this.eq(a, b); + } + + lt(a, b) { + return !this.geq(a,b); + } + + leq(a, b) { + return !this.gt(a,b); + } + + neq(a, b) { + return !this.eq(a,b); + } + + random() { + return [this.F.random(), this.F.random()]; + } + + + toRprLE(buff, o, e) { + this.F.toRprLE(buff, o, e[0]); + this.F.toRprLE(buff, o+this.F.n8, e[1]); + } + + toRprBE(buff, o, e) { + this.F.toRprBE(buff, o, e[1]); + this.F.toRprBE(buff, o+this.F.n8, e[0]); + } + + toRprLEM(buff, o, e) { + this.F.toRprLEM(buff, o, e[0]); + this.F.toRprLEM(buff, o+this.F.n8, e[1]); + } + + + toRprBEM(buff, o, e) { + this.F.toRprBEM(buff, o, e[1]); + this.F.toRprBEM(buff, o+this.F.n8, e[0]); + } + + fromRprLE(buff, o) { + o = o || 0; + const c0 = this.F.fromRprLE(buff, o); + const c1 = this.F.fromRprLE(buff, o+this.F.n8); + return [c0, c1]; + } + + fromRprBE(buff, o) { + o = o || 0; + const c1 = this.F.fromRprBE(buff, o); + const c0 = this.F.fromRprBE(buff, o+this.F.n8); + return [c0, c1]; + } + + fromRprLEM(buff, o) { + o = o || 0; + const c0 = this.F.fromRprLEM(buff, o); + const c1 = this.F.fromRprLEM(buff, o+this.F.n8); + return [c0, c1]; + } + + fromRprBEM(buff, o) { + o = o || 0; + const c1 = this.F.fromRprBEM(buff, o); + const c0 = this.F.fromRprBEM(buff, o+this.F.n8); + return [c0, c1]; + } + + toObject(a) { + return a; + } + +} + +/* + Copyright 2018 0kims association. + + This file is part of snarkjs. + + snarkjs is a free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or (at your option) + any later version. + + snarkjs is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along with + snarkjs. If not, see . +*/ + + +class F3Field { + constructor(F, nonResidue) { + this.type="F3"; + this.F = F; + this.zero = [this.F.zero, this.F.zero, this.F.zero]; + this.one = [this.F.one, this.F.zero, this.F.zero]; + this.negone = this.neg(this.one); + this.nonResidue = nonResidue; + this.m = F.m*3; + this.p = F.p; + this.n64 = F.n64*3; + this.n32 = this.n64*2; + this.n8 = this.n64*8; + } + + _mulByNonResidue(a) { + return this.F.mul(this.nonResidue, a); + } + + copy(a) { + return [this.F.copy(a[0]), this.F.copy(a[1]), this.F.copy(a[2])]; + } + + add(a, b) { + return [ + this.F.add(a[0], b[0]), + this.F.add(a[1], b[1]), + this.F.add(a[2], b[2]) + ]; + } + + double(a) { + return this.add(a,a); + } + + sub(a, b) { + return [ + this.F.sub(a[0], b[0]), + this.F.sub(a[1], b[1]), + this.F.sub(a[2], b[2]) + ]; + } + + neg(a) { + return this.sub(this.zero, a); + } + + mul(a, b) { + + const aA = this.F.mul(a[0] , b[0]); + const bB = this.F.mul(a[1] , b[1]); + const cC = this.F.mul(a[2] , b[2]); + + return [ + this.F.add( + aA, + this._mulByNonResidue( + this.F.sub( + this.F.mul( + this.F.add(a[1], a[2]), + this.F.add(b[1], b[2])), + this.F.add(bB, cC)))), // aA + non_residue*((b+c)*(B+C)-bB-cC), + + this.F.add( + this.F.sub( + this.F.mul( + this.F.add(a[0], a[1]), + this.F.add(b[0], b[1])), + this.F.add(aA, bB)), + this._mulByNonResidue( cC)), // (a+b)*(A+B)-aA-bB+non_residue*cC + + this.F.add( + this.F.sub( + this.F.mul( + this.F.add(a[0], a[2]), + this.F.add(b[0], b[2])), + this.F.add(aA, cC)), + bB)]; // (a+c)*(A+C)-aA+bB-cC) + } + + inv(a) { + const t0 = this.F.square(a[0]); // t0 = a^2 ; + const t1 = this.F.square(a[1]); // t1 = b^2 ; + const t2 = this.F.square(a[2]); // t2 = c^2; + const t3 = this.F.mul(a[0],a[1]); // t3 = ab + const t4 = this.F.mul(a[0],a[2]); // t4 = ac + const t5 = this.F.mul(a[1],a[2]); // t5 = bc; + // c0 = t0 - non_residue * t5; + const c0 = this.F.sub(t0, this._mulByNonResidue(t5)); + // c1 = non_residue * t2 - t3; + const c1 = this.F.sub(this._mulByNonResidue(t2), t3); + const c2 = this.F.sub(t1, t4); // c2 = t1-t4 + + // t6 = (a * c0 + non_residue * (c * c1 + b * c2)).inv(); + const t6 = + this.F.inv( + this.F.add( + this.F.mul(a[0], c0), + this._mulByNonResidue( + this.F.add( + this.F.mul(a[2], c1), + this.F.mul(a[1], c2))))); + + return [ + this.F.mul(t6, c0), // t6*c0 + this.F.mul(t6, c1), // t6*c1 + this.F.mul(t6, c2)]; // t6*c2 + } + + div(a, b) { + return this.mul(a, this.inv(b)); + } + + square(a) { + const s0 = this.F.square(a[0]); // s0 = a^2 + const ab = this.F.mul(a[0], a[1]); // ab = a*b + const s1 = this.F.add(ab, ab); // s1 = 2ab; + const s2 = this.F.square( + this.F.add(this.F.sub(a[0],a[1]), a[2])); // s2 = (a - b + c)^2; + const bc = this.F.mul(a[1],a[2]); // bc = b*c + const s3 = this.F.add(bc, bc); // s3 = 2*bc + const s4 = this.F.square(a[2]); // s4 = c^2 + + + return [ + this.F.add( + s0, + this._mulByNonResidue(s3)), // s0 + non_residue * s3, + this.F.add( + s1, + this._mulByNonResidue(s4)), // s1 + non_residue * s4, + this.F.sub( + this.F.add( this.F.add(s1, s2) , s3 ), + this.F.add(s0, s4))]; // s1 + s2 + s3 - s0 - s4 + } + + isZero(a) { + return this.F.isZero(a[0]) && this.F.isZero(a[1]) && this.F.isZero(a[2]); + } + + eq(a, b) { + return this.F.eq(a[0], b[0]) && this.F.eq(a[1], b[1]) && this.F.eq(a[2], b[2]); + } + + affine(a) { + return [this.F.affine(a[0]), this.F.affine(a[1]), this.F.affine(a[2])]; + } + + mulScalar(base, e) { + return mulScalar(this, base, e); + } + + pow(base, e) { + return exp(this, base, e); + } + + exp(base, e) { + return exp(this, base, e); + } + + toString(a) { + return `[ ${this.F.toString(a[0])} , ${this.F.toString(a[1])}, ${this.F.toString(a[2])} ]`; + } + + fromRng(rng) { + const c0 = this.F.fromRng(rng); + const c1 = this.F.fromRng(rng); + const c2 = this.F.fromRng(rng); + return [c0, c1, c2]; + } + + gt(a, b) { + if (this.F.gt(a[0], b[0])) return true; + if (this.F.gt(b[0], a[0])) return false; + if (this.F.gt(a[1], b[1])) return true; + if (this.F.gt(b[1], a[1])) return false; + if (this.F.gt(a[2], b[2])) return true; + return false; + } + + + geq(a, b) { + return this.gt(a, b) || this.eq(a, b); + } + + lt(a, b) { + return !this.geq(a,b); + } + + leq(a, b) { + return !this.gt(a,b); + } + + neq(a, b) { + return !this.eq(a,b); + } + + random() { + return [this.F.random(), this.F.random(), this.F.random()]; + } + + + toRprLE(buff, o, e) { + this.F.toRprLE(buff, o, e[0]); + this.F.toRprLE(buff, o+this.F.n8, e[1]); + this.F.toRprLE(buff, o+this.F.n8*2, e[2]); + } + + toRprBE(buff, o, e) { + this.F.toRprBE(buff, o, e[2]); + this.F.toRprBE(buff, o+this.F.n8, e[1]); + this.F.toRprBE(buff, o+this.F.n8*2, e[0]); + } + + toRprLEM(buff, o, e) { + this.F.toRprLEM(buff, o, e[0]); + this.F.toRprLEM(buff, o+this.F.n8, e[1]); + this.F.toRprLEM(buff, o+this.F.n8*2, e[2]); + } + + + toRprBEM(buff, o, e) { + this.F.toRprBEM(buff, o, e[2]); + this.F.toRprBEM(buff, o+this.F.n8, e[1]); + this.F.toRprBEM(buff, o+this.F.n8*2, e[0]); + } + + fromRprLE(buff, o) { + o = o || 0; + const c0 = this.F.fromRprLE(buff, o); + const c1 = this.F.fromRprLE(buff, o+this.n8); + const c2 = this.F.fromRprLE(buff, o+this.n8*2); + return [c0, c1, c2]; + } + + fromRprBE(buff, o) { + o = o || 0; + const c2 = this.F.fromRprBE(buff, o); + const c1 = this.F.fromRprBE(buff, o+this.n8); + const c0 = this.F.fromRprBE(buff, o+this.n8*2); + return [c0, c1, c2]; + } + + fromRprLEM(buff, o) { + o = o || 0; + const c0 = this.F.fromRprLEM(buff, o); + const c1 = this.F.fromRprLEM(buff, o+this.n8); + const c2 = this.F.fromRprLEM(buff, o+this.n8*2); + return [c0, c1, c2]; + } + + fromRprBEM(buff, o) { + o = o || 0; + const c2 = this.F.fromRprBEM(buff, o); + const c1 = this.F.fromRprBEM(buff, o+this.n8); + const c0 = this.F.fromRprBEM(buff, o+this.n8*2); + return [c0, c1, c2]; + } + + toObject(a) { + return a; + } +} + +/* + Copyright 2018 0kims association. + + This file is part of snarkjs. + + snarkjs is a free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or (at your option) + any later version. + + snarkjs is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along with + snarkjs. If not, see . +*/ + + + +function isGreatest(F, a) { + if (Array.isArray(a)) { + for (let i=a.length-1; i>=0; i--) { + if (!F.F.isZero(a[i])) { + return isGreatest(F.F, a[i]); + } + } + return 0; + } else { + const na = F.neg(a); + return gt(a, na); + } +} + + +class EC { + + constructor(F, g) { + this.F = F; + this.g = g; + if (this.g.length == 2) this.g[2] = this.F.one; + this.zero = [this.F.zero, this.F.one, this.F.zero]; + } + + add(p1, p2) { + + const F = this.F; + + if (this.eq(p1, this.zero)) return p2; + if (this.eq(p2, this.zero)) return p1; + + const res = new Array(3); + + const Z1Z1 = F.square( p1[2] ); + const Z2Z2 = F.square( p2[2] ); + + const U1 = F.mul( p1[0] , Z2Z2 ); // U1 = X1 * Z2Z2 + const U2 = F.mul( p2[0] , Z1Z1 ); // U2 = X2 * Z1Z1 + + const Z1_cubed = F.mul( p1[2] , Z1Z1); + const Z2_cubed = F.mul( p2[2] , Z2Z2); + + const S1 = F.mul( p1[1] , Z2_cubed); // S1 = Y1 * Z2 * Z2Z2 + const S2 = F.mul( p2[1] , Z1_cubed); // S2 = Y2 * Z1 * Z1Z1 + + if (F.eq(U1,U2) && F.eq(S1,S2)) { + return this.double(p1); + } + + const H = F.sub( U2 , U1 ); // H = U2-U1 + + const S2_minus_S1 = F.sub( S2 , S1 ); + + const I = F.square( F.add(H,H) ); // I = (2 * H)^2 + const J = F.mul( H , I ); // J = H * I + + const r = F.add( S2_minus_S1 , S2_minus_S1 ); // r = 2 * (S2-S1) + const V = F.mul( U1 , I ); // V = U1 * I + + res[0] = + F.sub( + F.sub( F.square(r) , J ), + F.add( V , V )); // X3 = r^2 - J - 2 * V + + const S1_J = F.mul( S1 , J ); + + res[1] = + F.sub( + F.mul( r , F.sub(V,res[0])), + F.add( S1_J,S1_J )); // Y3 = r * (V-X3)-2 S1 J + + res[2] = + F.mul( + H, + F.sub( + F.square( F.add(p1[2],p2[2]) ), + F.add( Z1Z1 , Z2Z2 ))); // Z3 = ((Z1+Z2)^2-Z1Z1-Z2Z2) * H + + return res; + } + + neg(p) { + return [p[0], this.F.neg(p[1]), p[2]]; + } + + sub(a, b) { + return this.add(a, this.neg(b)); + } + + double(p) { + const F = this.F; + + const res = new Array(3); + + if (this.eq(p, this.zero)) return p; + + const A = F.square( p[0] ); // A = X1^2 + const B = F.square( p[1] ); // B = Y1^2 + const C = F.square( B ); // C = B^2 + + let D = + F.sub( + F.square( F.add(p[0] , B )), + F.add( A , C)); + D = F.add(D,D); // D = 2 * ((X1 + B)^2 - A - C) + + const E = F.add( F.add(A,A), A); // E = 3 * A + const FF =F.square( E ); // F = E^2 + + res[0] = F.sub( FF , F.add(D,D) ); // X3 = F - 2 D + + let eightC = F.add( C , C ); + eightC = F.add( eightC , eightC ); + eightC = F.add( eightC , eightC ); + + res[1] = + F.sub( + F.mul( + E, + F.sub( D, res[0] )), + eightC); // Y3 = E * (D - X3) - 8 * C + + const Y1Z1 = F.mul( p[1] , p[2] ); + res[2] = F.add( Y1Z1 , Y1Z1 ); // Z3 = 2 * Y1 * Z1 + + return res; + } + + timesScalar(base, e) { + return mulScalar(this, base, e); + } + + mulScalar(base, e) { + return mulScalar(this, base, e); + } + + affine(p) { + const F = this.F; + if (this.isZero(p)) { + return this.zero; + } else if (F.eq(p[2], F.one)) { + return p; + } else { + const Z_inv = F.inv(p[2]); + const Z2_inv = F.square(Z_inv); + const Z3_inv = F.mul(Z2_inv, Z_inv); + + const res = new Array(3); + res[0] = F.mul(p[0],Z2_inv); + res[1] = F.mul(p[1],Z3_inv); + res[2] = F.one; + + return res; + } + } + + multiAffine(arr) { + const keys = Object.keys(arr); + const F = this.F; + const accMul = new Array(keys.length+1); + accMul[0] = F.one; + for (let i = 0; i< keys.length; i++) { + if (F.eq(arr[keys[i]][2], F.zero)) { + accMul[i+1] = accMul[i]; + } else { + accMul[i+1] = F.mul(accMul[i], arr[keys[i]][2]); + } + } + + accMul[keys.length] = F.inv(accMul[keys.length]); + + for (let i = keys.length-1; i>=0; i--) { + if (F.eq(arr[keys[i]][2], F.zero)) { + accMul[i] = accMul[i+1]; + arr[keys[i]] = this.zero; + } else { + const Z_inv = F.mul(accMul[i], accMul[i+1]); + accMul[i] = F.mul(arr[keys[i]][2], accMul[i+1]); + + const Z2_inv = F.square(Z_inv); + const Z3_inv = F.mul(Z2_inv, Z_inv); + + arr[keys[i]][0] = F.mul(arr[keys[i]][0],Z2_inv); + arr[keys[i]][1] = F.mul(arr[keys[i]][1],Z3_inv); + arr[keys[i]][2] = F.one; + } + } + + } + + eq(p1, p2) { + const F = this.F; + + if (this.F.eq(p1[2], this.F.zero)) return this.F.eq(p2[2], this.F.zero); + if (this.F.eq(p2[2], this.F.zero)) return false; + + const Z1Z1 = F.square( p1[2] ); + const Z2Z2 = F.square( p2[2] ); + + const U1 = F.mul( p1[0] , Z2Z2 ); + const U2 = F.mul( p2[0] , Z1Z1 ); + + const Z1_cubed = F.mul( p1[2] , Z1Z1); + const Z2_cubed = F.mul( p2[2] , Z2Z2); + + const S1 = F.mul( p1[1] , Z2_cubed); + const S2 = F.mul( p2[1] , Z1_cubed); + + return (F.eq(U1,U2) && F.eq(S1,S2)); + } + + isZero(p) { + return this.F.isZero(p[2]); + } + + toString(p) { + const cp = this.affine(p); + return `[ ${this.F.toString(cp[0])} , ${this.F.toString(cp[1])} ]`; + } + + fromRng(rng) { + const F = this.F; + let P = []; + let greatest; + do { + P[0] = F.fromRng(rng); + greatest = rng.nextBool(); + const x3b = F.add(F.mul(F.square(P[0]), P[0]), this.b); + P[1] = F.sqrt(x3b); + } while ((P[1] == null)||(F.isZero[P])); + + const s = isGreatest(F, P[1]); + if (greatest ^ s) P[1] = F.neg(P[1]); + P[2] = F.one; + + if (this.cofactor) { + P = this.mulScalar(P, this.cofactor); + } + + P = this.affine(P); + + return P; + + } + + toRprLE(buff, o, p) { + p = this.affine(p); + if (this.isZero(p)) { + const BuffV = new Uint8Array(buff, o, this.F.n8*2); + BuffV.fill(0); + return; + } + this.F.toRprLE(buff, o, p[0]); + this.F.toRprLE(buff, o+this.F.n8, p[1]); + } + + toRprBE(buff, o, p) { + p = this.affine(p); + if (this.isZero(p)) { + const BuffV = new Uint8Array(buff, o, this.F.n8*2); + BuffV.fill(0); + return; + } + this.F.toRprBE(buff, o, p[0]); + this.F.toRprBE(buff, o+this.F.n8, p[1]); + } + + toRprLEM(buff, o, p) { + p = this.affine(p); + if (this.isZero(p)) { + const BuffV = new Uint8Array(buff, o, this.F.n8*2); + BuffV.fill(0); + return; + } + this.F.toRprLEM(buff, o, p[0]); + this.F.toRprLEM(buff, o+this.F.n8, p[1]); + } + + toRprLEJM(buff, o, p) { + p = this.affine(p); + if (this.isZero(p)) { + const BuffV = new Uint8Array(buff, o, this.F.n8*2); + BuffV.fill(0); + return; + } + this.F.toRprLEM(buff, o, p[0]); + this.F.toRprLEM(buff, o+this.F.n8, p[1]); + this.F.toRprLEM(buff, o+2*this.F.n8, p[2]); + } + + + toRprBEM(buff, o, p) { + p = this.affine(p); + if (this.isZero(p)) { + const BuffV = new Uint8Array(buff, o, this.F.n8*2); + BuffV.fill(0); + return; + } + this.F.toRprBEM(buff, o, p[0]); + this.F.toRprBEM(buff, o+this.F.n8, p[1]); + } + + fromRprLE(buff, o) { + o = o || 0; + const x = this.F.fromRprLE(buff, o); + const y = this.F.fromRprLE(buff, o+this.F.n8); + if (this.F.isZero(x) && this.F.isZero(y)) { + return this.zero; + } + return [x, y, this.F.one]; + } + + fromRprBE(buff, o) { + o = o || 0; + const x = this.F.fromRprBE(buff, o); + const y = this.F.fromRprBE(buff, o+this.F.n8); + if (this.F.isZero(x) && this.F.isZero(y)) { + return this.zero; + } + return [x, y, this.F.one]; + } + + fromRprLEM(buff, o) { + o = o || 0; + const x = this.F.fromRprLEM(buff, o); + const y = this.F.fromRprLEM(buff, o+this.F.n8); + if (this.F.isZero(x) && this.F.isZero(y)) { + return this.zero; + } + return [x, y, this.F.one]; + } + + fromRprLEJM(buff, o) { + o = o || 0; + const x = this.F.fromRprLEM(buff, o); + const y = this.F.fromRprLEM(buff, o+this.F.n8); + const z = this.F.fromRprLEM(buff, o+this.F.n8*2); + if (this.F.isZero(x) && this.F.isZero(y)) { + return this.zero; + } + return [x, y, z]; + } + + fromRprBEM(buff, o) { + o = o || 0; + const x = this.F.fromRprBEM(buff, o); + const y = this.F.fromRprBEM(buff, o+this.F.n8); + if (this.F.isZero(x) && this.F.isZero(y)) { + return this.zero; + } + return [x, y, this.F.one]; + } + + fromRprCompressed(buff, o) { + const F = this.F; + const v = new Uint8Array(buff.buffer, o, F.n8); + if (v[0] & 0x40) return this.zero; + const P = new Array(3); + + const greatest = ((v[0] & 0x80) != 0); + v[0] = v[0] & 0x7F; + P[0] = F.fromRprBE(buff, o); + if (greatest) v[0] = v[0] | 0x80; // set back again the old value + + const x3b = F.add(F.mul(F.square(P[0]), P[0]), this.b); + P[1] = F.sqrt(x3b); + + if (P[1] === null) { + throw new Error("Invalid Point!"); + } + + const s = isGreatest(F, P[1]); + if (greatest ^ s) P[1] = F.neg(P[1]); + P[2] = F.one; + + return P; + } + + toRprCompressed(buff, o, p) { + p = this.affine(p); + const v = new Uint8Array(buff.buffer, o, this.F.n8); + if (this.isZero(p)) { + v.fill(0); + v[0] = 0x40; + return; + } + this.F.toRprBE(buff, o, p[0]); + + if (isGreatest(this.F, p[1])) { + v[0] = v[0] | 0x80; + } + } + + + fromRprUncompressed(buff, o) { + if (buff[0] & 0x40) return this.zero; + + return this.fromRprBE(buff, o); + } + + toRprUncompressed(buff, o, p) { + this.toRprBE(buff, o, p); + + if (this.isZero(p)) { + buff[o] = buff[o] | 0x40; + } + } + + +} + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +var utils$6 = {}; -/* provided dependency */ var console = __webpack_require__(96763); /* Copyright 2019 0KIMS association. - This file is part of websnark (Web Assembly zkSnark Prover). + This file is part of wasmsnark (Web Assembly zkSnark Prover). - websnark is a free software: you can redistribute it and/or modify it + wasmsnark is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - websnark is distributed in the hope that it will be useful, but WITHOUT + wasmsnark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License - along with websnark. If not, see . + along with wasmsnark. If not, see . */ -/* globals WebAssembly */ -const bigInt = __webpack_require__(92096); -const ModuleBuilder = __webpack_require__(80442); +utils$6.bigInt2BytesLE = function bigInt2BytesLE(_a, len) { + const b = Array(len); + let v = BigInt(_a); + for (let i=0; i> 8n; + } + return b; +}; -function buf2hex(buffer) { // buffer is an ArrayBuffer - return Array.prototype.map.call(new Uint8Array(buffer), x => ("00" + x.toString(16)).slice(-2)).join(""); -} +utils$6.bigInt2U32LE = function bigInt2BytesLE(_a, len) { + const b = Array(len); + let v = BigInt(_a); + for (let i=0; i> 32n; + } + return b; +}; +utils$6.isOcamNum = function(a) { + if (!Array.isArray(a)) return false; + if (a.length != 3) return false; + if (typeof a[0] !== "number") return false; + if (typeof a[1] !== "number") return false; + if (!Array.isArray(a[2])) return false; + return true; +}; -async function buildProtoboard(builder, defBytes, bitsPerBytes) { - const protoboard = new Protoboard(); +/* + Copyright 2019 0KIMS association. - protoboard.defBytes = defBytes; - protoboard.bitsPerBytes = bitsPerBytes || 32; + This file is part of wasmsnark (Web Assembly zkSnark Prover). - protoboard.memory = new WebAssembly.Memory({initial:20000}); - protoboard.i32 = new Uint32Array(protoboard.memory.buffer); - protoboard.i8 = new Uint8Array(protoboard.memory.buffer); + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - const moduleBuilder = new ModuleBuilder(); + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. - const fLog32 = moduleBuilder.addIimportFunction("debug_log32", "debug", "log32"); - fLog32.addParam("x", "i32"); - const fLog64 = moduleBuilder.addIimportFunction("debug_log64", "debug", "log64"); - fLog64.addParam("x", "i32"); - fLog64.addParam("y", "i32"); + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ - buildLog32(moduleBuilder); - buildLog64(moduleBuilder); +var build_int = function buildInt(module, n64, _prefix) { - builder(moduleBuilder, protoboard); + const prefix = _prefix || "int"; + if (module.modules[prefix]) return prefix; // already builded + module.modules[prefix] = {}; + const n32 = n64*2; + const n8 = n64*8; - const code = moduleBuilder.build(); - - const wasmModule = await WebAssembly.compile(code); - - protoboard.log = console.log; - - protoboard.instance = await WebAssembly.instantiate(wasmModule, { - env: { - "memory": protoboard.memory - }, - debug: { - log32: function (c1) { - if (c1<0) c1 = 0x100000000+c1; - let s=c1.toString(16); - while (s.length<8) s = "0"+s; - protoboard.log(s + ": " + c1.toString()); - }, - log64: function (c1, c2) { - if (c1<0) c1 = 0x100000000+c1; - if (c2<0) c2 = 0x100000000+c2; - const n = bigInt(c1) + bigInt(c2).shiftLeft(32); - let s=n.toString(16); - while (s.length<16) s = "0"+s; - protoboard.log(s + ": " + n.toString()); - } - } - }); - - Object.assign(protoboard, protoboard.instance.exports); - Object.assign(protoboard, moduleBuilder.modules); - - return protoboard; - - function buildLog32(module) { - - const f = module.addFunction("log32"); - f.addParam("x", "i32"); + function buildCopy() { + const f = module.addFunction(prefix+"_copy"); + f.addParam("px", "i32"); + f.addParam("pr", "i32"); const c = f.getCodeBuilder(); - f.addCode(c.call("debug_log32", c.getLocal("x"))); + + for (let i=0; i>1) )&&(i>1, k>>1) + ) + ) + ); + + f.addCode( + c.setLocal(c1, + c.i64_add( + c.getLocal(c1), + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ) + ) + ); + } + + // Add the old carry + + if (k>0) { + f.addCode( + c.setLocal(c0, + c.i64_add( + c.i64_and( + c.getLocal(c0), + c.i64_const(0xFFFFFFFF) + ), + c.i64_and( + c.getLocal(c0_old), + c.i64_const(0xFFFFFFFF) + ), + ) + ) + ); + + f.addCode( + c.setLocal(c1, + c.i64_add( + c.i64_add( + c.getLocal(c1), + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ), + c.getLocal(c1_old) + ) + ) + ); + } + + f.addCode( + c.i64_store32( + c.getLocal("r"), + k*4, + c.getLocal(c0) + ) + ); + + f.addCode( + c.setLocal( + c0_old, + c.getLocal(c1) + ), + c.setLocal( + c1_old, + c.i64_shr_u( + c.getLocal(c0_old), + c.i64_const(32) + ) + ) + ); + + } + f.addCode( + c.i64_store32( + c.getLocal("r"), + n32*4*2-4, + c.getLocal(c0_old) + ) + ); + + } + + + function buildSquareOld() { + const f = module.addFunction(prefix+"_squareOld"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); + } + + function _buildMul1() { + const f = module.addFunction(prefix+"__mul1"); + f.addParam("px", "i32"); + f.addParam("y", "i64"); + f.addParam("pr", "i32"); + f.addLocal("c", "i64"); + + const c = f.getCodeBuilder(); + + f.addCode(c.setLocal( + "c", + c.i64_mul( + c.i64_load32_u(c.getLocal("px"), 0, 0), + c.getLocal("y") + ) + )); + + f.addCode(c.i64_store32( + c.getLocal("pr"), + 0, + 0, + c.getLocal("c"), + )); + + for (let i=1; i3)&&(Y[eY]==0) ey--; + f.addCode(c.block(c.loop( + c.br_if( + 1, + c.i32_or( + c.i32_load8_u( + c.i32_add(Y , c.getLocal("eY")), + 0, + 0 + ), + c.i32_eq( + c.getLocal("eY"), + c.i32_const(3) + ) + ) + ), + c.setLocal("eY", c.i32_sub(c.getLocal("eY"), c.i32_const(1))), + c.br(0) + ))); + + f.addCode( + c.setLocal( + "sy", + c.i64_add( + c.i64_load32_u( + c.i32_sub( + c.i32_add( Y, c.getLocal("eY")), + c.i32_const(3) + ), + 0, + 0 + ), + c.i64_const(1) + ) ) + ); + + // Force a divide by 0 if quotien is 0 + f.addCode( + c.if( + c.i64_eq( + c.getLocal("sy"), + c.i64_const(1) + ), + c.drop(c.i64_div_u(c.i64_const(0), c.i64_const(0))) + ) + ); + + f.addCode(c.block(c.loop( + + // while (eX>7)&&(Y[eX]==0) ex--; + c.block(c.loop( + c.br_if( + 1, + c.i32_or( + c.i32_load8_u( + c.i32_add(R , c.getLocal("eX")), + 0, + 0 + ), + c.i32_eq( + c.getLocal("eX"), + c.i32_const(7) + ) + ) + ), + c.setLocal("eX", c.i32_sub(c.getLocal("eX"), c.i32_const(1))), + c.br(0) + )), + + c.setLocal( + "sx", + c.i64_load( + c.i32_sub( + c.i32_add( R, c.getLocal("eX")), + c.i32_const(7) + ), + 0, + 0 + ) + ), + + c.setLocal( + "sx", + c.i64_div_u( + c.getLocal("sx"), + c.getLocal("sy") + ) + ), + c.setLocal( + "ec", + c.i32_sub( + c.i32_sub( + c.getLocal("eX"), + c.getLocal("eY") + ), + c.i32_const(4) + ) + ), + + // While greater than 32 bits or ec is neg, shr and inc exp + c.block(c.loop( + c.br_if( + 1, + c.i32_and( + c.i64_eqz( + c.i64_and( + c.getLocal("sx"), + c.i64_const("0xFFFFFFFF00000000") + ) + ), + c.i32_ge_s( + c.getLocal("ec"), + c.i32_const(0) + ) + ) + ), + + c.setLocal( + "sx", + c.i64_shr_u( + c.getLocal("sx"), + c.i64_const(8) + ) + ), + + c.setLocal( + "ec", + c.i32_add( + c.getLocal("ec"), + c.i32_const(1) + ) + ), + c.br(0) + )), + + c.if( + c.i64_eqz(c.getLocal("sx")), + [ + ...c.br_if( + 2, + c.i32_eqz(c.call(prefix + "_gte", R, Y)) + ), + ...c.setLocal("sx", c.i64_const(1)), + ...c.setLocal("ec", c.i32_const(0)) + ] + ), + + c.call(prefix + "__mul1", Y, c.getLocal("sx"), R2), + c.drop(c.call( + prefix + "_sub", + R, + c.i32_sub(R2, c.getLocal("ec")), + R + )), + c.call( + prefix + "__add1", + c.i32_add(C, c.getLocal("ec")), + c.getLocal("sx") + ), + c.br(0) + ))); + } + + function buildInverseMod() { + + const f = module.addFunction(prefix+"_inverseMod"); + f.addParam("px", "i32"); + f.addParam("pm", "i32"); + f.addParam("pr", "i32"); + f.addLocal("t", "i32"); + f.addLocal("newt", "i32"); + f.addLocal("r", "i32"); + f.addLocal("qq", "i32"); + f.addLocal("qr", "i32"); + f.addLocal("newr", "i32"); + f.addLocal("swp", "i32"); + f.addLocal("x", "i32"); + f.addLocal("signt", "i32"); + f.addLocal("signnewt", "i32"); + f.addLocal("signx", "i32"); + + const c = f.getCodeBuilder(); + + const aux1 = c.i32_const(module.alloc(n8)); + const aux2 = c.i32_const(module.alloc(n8)); + const aux3 = c.i32_const(module.alloc(n8)); + const aux4 = c.i32_const(module.alloc(n8)); + const aux5 = c.i32_const(module.alloc(n8)); + const aux6 = c.i32_const(module.alloc(n8)); + const mulBuff = c.i32_const(module.alloc(n8*2)); + const aux7 = c.i32_const(module.alloc(n8)); + + f.addCode( + c.setLocal("t", aux1), + c.call(prefix + "_zero", aux1), + c.setLocal("signt", c.i32_const(0)), + ); + + f.addCode( + c.setLocal("r", aux2), + c.call(prefix + "_copy", c.getLocal("pm"), aux2) + ); + + f.addCode( + c.setLocal("newt", aux3), + c.call(prefix + "_one", aux3), + c.setLocal("signnewt", c.i32_const(0)), + ); + + f.addCode( + c.setLocal("newr", aux4), + c.call(prefix + "_copy", c.getLocal("px"), aux4) + ); + + + + + f.addCode(c.setLocal("qq", aux5)); + f.addCode(c.setLocal("qr", aux6)); + f.addCode(c.setLocal("x", aux7)); + + f.addCode(c.block(c.loop( + c.br_if( + 1, + c.call(prefix + "_isZero", c.getLocal("newr") ) + ), + c.call(prefix + "_div", c.getLocal("r"), c.getLocal("newr"), c.getLocal("qq"), c.getLocal("qr")), + + c.call(prefix + "_mul", c.getLocal("qq"), c.getLocal("newt"), mulBuff), + + c.if( + c.getLocal("signt"), + c.if( + c.getLocal("signnewt"), + c.if ( + c.call(prefix + "_gte", mulBuff, c.getLocal("t")), + [ + ...c.drop(c.call(prefix + "_sub", mulBuff, c.getLocal("t"), c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(0)) + ], + [ + ...c.drop(c.call(prefix + "_sub", c.getLocal("t"), mulBuff, c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(1)) + ], + ), + [ + ...c.drop(c.call(prefix + "_add", mulBuff, c.getLocal("t"), c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(1)) + ] + ), + c.if( + c.getLocal("signnewt"), + [ + ...c.drop(c.call(prefix + "_add", mulBuff, c.getLocal("t"), c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(0)) + ], + c.if ( + c.call(prefix + "_gte", c.getLocal("t"), mulBuff), + [ + ...c.drop(c.call(prefix + "_sub", c.getLocal("t"), mulBuff, c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(0)) + ], + [ + ...c.drop(c.call(prefix + "_sub", mulBuff, c.getLocal("t"), c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(1)) + ] + ) + ) + ), + + c.setLocal("swp", c.getLocal("t")), + c.setLocal("t", c.getLocal("newt")), + c.setLocal("newt", c.getLocal("x")), + c.setLocal("x", c.getLocal("swp")), + + c.setLocal("signt", c.getLocal("signnewt")), + c.setLocal("signnewt", c.getLocal("signx")), + + c.setLocal("swp", c.getLocal("r")), + c.setLocal("r", c.getLocal("newr")), + c.setLocal("newr", c.getLocal("qr")), + c.setLocal("qr", c.getLocal("swp")), + + c.br(0) + ))); + + f.addCode(c.if( + c.getLocal("signt"), + c.drop(c.call(prefix + "_sub", c.getLocal("pm"), c.getLocal("t"), c.getLocal("pr"))), + c.call(prefix + "_copy", c.getLocal("t"), c.getLocal("pr")) )); } -} -class Protoboard { + buildCopy(); + buildZero(); + buildIsZero(); + buildOne(); + buildEq(); + buildGte(); + buildAdd(); + buildSub(); + buildMul(); + buildSquare(); + buildSquareOld(); + buildDiv(); + buildInverseMod(); + module.exportFunction(prefix+"_copy"); + module.exportFunction(prefix+"_zero"); + module.exportFunction(prefix+"_one"); + module.exportFunction(prefix+"_isZero"); + module.exportFunction(prefix+"_eq"); + module.exportFunction(prefix+"_gte"); + module.exportFunction(prefix+"_add"); + module.exportFunction(prefix+"_sub"); + module.exportFunction(prefix+"_mul"); + module.exportFunction(prefix+"_square"); + module.exportFunction(prefix+"_squareOld"); + module.exportFunction(prefix+"_div"); + module.exportFunction(prefix+"_inverseMod"); - constructor() { - - } - - alloc(length) { - if (typeof length === "undefined") { - length = this.defBytes; - } - length = (((length-1)>>3) +1)<<3; // Align to 64 bits. - - const res = this.i32[0]; - this.i32[0] += length; - return res; - } - - set(pos, nums, nBytes) { - if (!Array.isArray(nums)) { - nums = [nums]; - } - if (typeof nBytes === "undefined") { - nBytes = this.defBytes; - } - - const words = Math.floor((nBytes -1)/4)+1; - let p = pos; - - const CHUNK = bigInt.one.shiftLeft(this.bitsPerBytes); - - for (let i=0; i>2] = rd.remainder.toJSNumber(); - v = rd.quotient; - p += 4; - } - if (!v.isZero()) { - throw new Error('Expected v to be 0'); - } -/* this.i32[p>>2] = bigInt(nums[i]).shiftRight( (words-1)*this.bitsPerBytes).toJSNumber(); - p += 4; -*/ } - - return pos; - } - - get(pos, nElements, nBytes) { - if (typeof nBytes == "undefined") { - if (typeof nElements == "undefined") { - nElements = 1; - nBytes = this.defBytes; - } else { - nElements = nBytes; - nBytes = this.defBytes; - } - } - - const words = Math.floor((nBytes -1)/4)+1; - - const CHUNK = bigInt.one.shiftLeft(this.bitsPerBytes); - - - const nums = []; - for (let i=0; i=0; j--) { - acc = acc.times(CHUNK); - let v = this.i32[(pos>>2)+j]; - if (this.bitsPerBytes <32) { - if (v&0x80000000) v = v-0x100000000; - } - acc = acc.add(v); - } - nums.push(acc); - pos += words*4; - } - - if (nums.length == 1) return nums[0]; - return nums; - } -} - -module.exports = buildProtoboard; - - -/***/ }), - -/***/ 60484: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmbuilder - - wasmbuilder is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmbuilder is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmbuilder. If not, see . -*/ - -const bigInt = __webpack_require__(92096); - -function toNumber(n) { - let v; - if (typeof n=="string") { - if (n.slice(0,2).toLowerCase() == "0x") { - v = bigInt(n.slice(2),16); - } else { - v = bigInt(n); - } - } else { - v = bigInt(n); - } - return v; -} - -function u32(n) { - const b = []; - const v = toNumber(n); - b.push(v.and(0xFF).toJSNumber()); - b.push(v.shiftRight(8).and(0xFF).toJSNumber()); - b.push(v.shiftRight(16).and(0xFF).toJSNumber()); - b.push(v.shiftRight(24).and(0xFF).toJSNumber()); - return b; -} - -function u64(n) { - const b = []; - const v = toNumber(n); - b.push(v.and(0xFF).toJSNumber()); - b.push(v.shiftRight(8).and(0xFF).toJSNumber()); - b.push(v.shiftRight(16).and(0xFF).toJSNumber()); - b.push(v.shiftRight(24).and(0xFF).toJSNumber()); - b.push(v.shiftRight(32).and(0xFF).toJSNumber()); - b.push(v.shiftRight(40).and(0xFF).toJSNumber()); - b.push(v.shiftRight(48).and(0xFF).toJSNumber()); - b.push(v.shiftRight(56).and(0xFF).toJSNumber()); - return b; -} - -function toUTF8Array(str) { - var utf8 = []; - for (var i=0; i < str.length; i++) { - var charcode = str.charCodeAt(i); - if (charcode < 0x80) utf8.push(charcode); - else if (charcode < 0x800) { - utf8.push(0xc0 | (charcode >> 6), - 0x80 | (charcode & 0x3f)); - } - else if (charcode < 0xd800 || charcode >= 0xe000) { - utf8.push(0xe0 | (charcode >> 12), - 0x80 | ((charcode>>6) & 0x3f), - 0x80 | (charcode & 0x3f)); - } - // surrogate pair - else { - i++; - // UTF-16 encodes 0x10000-0x10FFFF by - // subtracting 0x10000 and splitting the - // 20 bits of 0x0-0xFFFFF into two halves - charcode = 0x10000 + (((charcode & 0x3ff)<<10) - | (str.charCodeAt(i) & 0x3ff)); - utf8.push(0xf0 | (charcode >>18), - 0x80 | ((charcode>>12) & 0x3f), - 0x80 | ((charcode>>6) & 0x3f), - 0x80 | (charcode & 0x3f)); - } - } - return utf8; -} - -function string(str) { - const bytes = toUTF8Array(str); - return [ ...varuint32(bytes.length), ...bytes ]; -} - -function varuint(n) { - const code = []; - let v = toNumber(n); - if (v.isNegative()) throw new Error("Number cannot be negative"); - while (!v.isZero()) { - code.push(v.and(0x7F).toJSNumber()); - v = v.shiftRight(7); - } - if (code.length==0) code.push(0); - for (let i=0; i { + return prefix; +}; /* Copyright 2019 0KIMS association. @@ -111591,3285 +114393,78 @@ module.exports.ident = ident; along with wasmsnark. If not, see . */ - -// module.exports.bn128_wasm = require("./build/bn128_wasm.js"); -// module.exports.bls12381_wasm = require("./build/bls12381_wasm.js"); -// module.exports.mnt6753_wasm = require("./build/mnt6753_wasm.js"); - -module.exports.buildBn128 = __webpack_require__(23584); -module.exports.buildBls12381 = __webpack_require__(26920); -// module.exports.buildMnt6753 = require("./src/mnt6753/build_mnt7.js"); - - -/***/ }), - -/***/ 26920: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -const bigInt = __webpack_require__(92096); -const utils = __webpack_require__(12333); - -const buildF1m =__webpack_require__(70075); -const buildF1 =__webpack_require__(38138); -const buildF2m =__webpack_require__(15420); -const buildF3m =__webpack_require__(77173); -const buildCurve =__webpack_require__(15904); -const buildFFT = __webpack_require__(93911); -const buildPol = __webpack_require__(2896); -const buildQAP = __webpack_require__(10637); -const buildApplyKey = __webpack_require__(23320); - -// Definition here: https://electriccoin.co/blog/new-snark-curve/ - -module.exports = function buildBLS12381(module, _prefix) { - - const prefix = _prefix || "bls12381"; - - if (module.modules[prefix]) return prefix; // already builded - - const q = bigInt("1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab", 16); - const r = bigInt("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001", 16); - - const n64q = Math.floor((q.minus(1).bitLength() - 1)/64) +1; - const n8q = n64q*8; - const f1size = n8q; - const f2size = f1size * 2; - const f6size = f1size * 6; - const ftsize = f1size * 12; - - const n64r = Math.floor((r.minus(1).bitLength() - 1)/64) +1; - const n8r = n64r*8; - const frsize = n8r; - - - const pr = module.alloc(utils.bigInt2BytesLE( r, frsize )); - - const f1mPrefix = buildF1m(module, q, "f1m", "intq"); - buildF1(module, r, "fr", "frm", "intr"); - const pG1b = module.alloc(utils.bigInt2BytesLE( toMontgomery(bigInt(4)), f1size )); - const g1mPrefix = buildCurve(module, "g1m", "f1m", pG1b); - - buildFFT(module, "frm", "frm", "frm", "frm_mul"); - - buildPol(module, "pol", "frm"); - buildQAP(module, "qap", "frm"); - - const f2mPrefix = buildF2m(module, "f1m_neg", "f2m", "f1m"); - const pG2b = module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery(bigInt("4")), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(bigInt("4")), f1size ) - ]); - const g2mPrefix = buildCurve(module, "g2m", "f2m", pG2b); - - - function buildGTimesFr(fnName, opMul) { - const f = module.addFunction(fnName); - f.addParam("pG", "i32"); - f.addParam("pFr", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - const AUX = c.i32_const(module.alloc(n8r)); - - f.addCode( - c.call("frm_fromMontgomery", c.getLocal("pFr"), AUX), - c.call( - opMul, - c.getLocal("pG"), - AUX, - c.i32_const(n8r), - c.getLocal("pr") - ) - ); - - module.exportFunction(fnName); - } - buildGTimesFr("g1m_timesFr", "g1m_timesScalar"); - buildFFT(module, "g1m", "g1m", "frm", "g1m_timesFr"); - - buildGTimesFr("g2m_timesFr", "g2m_timesScalar"); - buildFFT(module, "g2m", "g2m", "frm", "g2m_timesFr"); - - buildGTimesFr("g1m_timesFrAffine", "g1m_timesScalarAffine"); - buildGTimesFr("g2m_timesFrAffine", "g2m_timesScalarAffine"); - - buildApplyKey(module, "frm_batchApplyKey", "fmr", "frm", n8r, n8r, n8r, "frm_mul"); - buildApplyKey(module, "g1m_batchApplyKey", "g1m", "frm", n8q*3, n8q*3, n8r, "g1m_timesFr"); - buildApplyKey(module, "g1m_batchApplyKeyMixed", "g1m", "frm", n8q*2, n8q*3, n8r, "g1m_timesFrAffine"); - buildApplyKey(module, "g2m_batchApplyKey", "g2m", "frm", n8q*2*3, n8q*3*2, n8r, "g2m_timesFr"); - buildApplyKey(module, "g2m_batchApplyKeyMixed", "g2m", "frm", n8q*2*2, n8q*3*2, n8r, "g2m_timesFrAffine"); - - - function toMontgomery(a) { - return bigInt(a).times( bigInt.one.shiftLeft(f1size*8)).mod(q); - } - - const G1gen = [ - bigInt("3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507"), - bigInt("1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569"), - bigInt.one - ]; - - const pG1gen = module.alloc( - [ - ...utils.bigInt2BytesLE( toMontgomery(G1gen[0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G1gen[1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G1gen[2]), f1size ), - ] - ); - - const G1zero = [ - bigInt.zero, - bigInt.one, - bigInt.zero - ]; - - const pG1zero = module.alloc( - [ - ...utils.bigInt2BytesLE( toMontgomery(G1zero[0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G1zero[1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G1zero[2]), f1size ) - ] - ); - - const G2gen = [ - [ - bigInt("352701069587466618187139116011060144890029952792775240219908644239793785735715026873347600343865175952761926303160"), - bigInt("3059144344244213709971259814753781636986470325476647558659373206291635324768958432433509563104347017837885763365758"), - ],[ - bigInt("1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905"), - bigInt("927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582"), - ],[ - bigInt.one, - bigInt.zero, - ] - ]; - - const pG2gen = module.alloc( - [ - ...utils.bigInt2BytesLE( toMontgomery(G2gen[0][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2gen[0][1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2gen[1][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2gen[1][1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2gen[2][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2gen[2][1]), f1size ), - ] - ); - - const G2zero = [ - [ - bigInt.zero, - bigInt.zero, - ],[ - bigInt.one, - bigInt.zero, - ],[ - bigInt.zero, - bigInt.zero, - ] - ]; - - const pG2zero = module.alloc( - [ - ...utils.bigInt2BytesLE( toMontgomery(G2zero[0][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2zero[0][1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2zero[1][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2zero[1][1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2zero[2][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2zero[2][1]), f1size ), - ] - ); - - const pOneT = module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery(1), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ]); - - const pTwoInv = module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery( bigInt(2).modInv(q)), f1size ), - ...utils.bigInt2BytesLE( bigInt(0), f1size ) - ]); - - const pBls12381Twist = module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery(1), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(1), f1size ), - ]); - - const pTwistCoefB = module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery("4"), f1size ), - ...utils.bigInt2BytesLE( toMontgomery("4"), f1size ), - ]); - - function build_mulNR2() { - const f = module.addFunction(f2mPrefix + "_mulNR"); - f.addParam("x", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - const x0c = c.i32_const(module.alloc(f1size)); - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1size)); - const r0 = c.getLocal("pr"); - const r1 = c.i32_add(c.getLocal("pr"), c.i32_const(f1size)); - - f.addCode( - c.call(f1mPrefix+"_copy", x0, x0c), - c.call(f1mPrefix+"_sub", x0, x1, r0), - c.call(f1mPrefix+"_add", x0c, x1, r1), - ); - } - build_mulNR2(); - - const f6mPrefix = buildF3m(module, f2mPrefix+"_mulNR", "f6m", "f2m"); - - function build_mulNR6() { - const f = module.addFunction(f6mPrefix + "_mulNR"); - f.addParam("x", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - const c0copy = c.i32_const(module.alloc(f1size*2)); - - f.addCode( - c.call( - f2mPrefix + "_copy", - c.getLocal("x"), - c0copy - ), - c.call( - f2mPrefix + "_mulNR", - c.i32_add(c.getLocal("x"), c.i32_const(n8q*4)), - c.getLocal("pr") - ), - c.call( - f2mPrefix + "_copy", - c.i32_add(c.getLocal("x"), c.i32_const(n8q*2)), - c.i32_add(c.getLocal("pr"), c.i32_const(n8q*4)), - ), - c.call( - f2mPrefix + "_copy", - c0copy, - c.i32_add(c.getLocal("pr"), c.i32_const(n8q*2)), - ), - ); - } - build_mulNR6(); - - const ftmPrefix = buildF2m(module, f6mPrefix+"_mulNR", "ftm", f6mPrefix); - - const ateLoopCount = bigInt("d201000000010000", 16); - const ateLoopBitBytes = bits(ateLoopCount); - const pAteLoopBitBytes = module.alloc(ateLoopBitBytes); - const isLoopNegative = true; - - const ateCoefSize = 3 * f2size; - const ateNDblCoefs = ateLoopBitBytes.length-1; - const ateNAddCoefs = ateLoopBitBytes.reduce((acc, b) => acc + ( b!=0 ? 1 : 0) ,0); - const ateNCoefs = ateNAddCoefs + ateNDblCoefs + 1; - const prePSize = 3*2*n8q; - const preQSize = 3*n8q*2 + ateNCoefs*ateCoefSize; - const finalExpIsNegative = true; - - const finalExpZ = bigInt("15132376222941642752"); - - - module.modules[prefix] = { - n64q: n64q, - n64r: n64r, - n8q: n8q, - n8r: n8r, - pG1gen: pG1gen, - pG1zero: pG1zero, - pG1b: pG1b, - pG2gen: pG2gen, - pG2zero: pG2zero, - pG2b: pG2b, - pq: module.modules["f1m"].pq, - pr: pr, - pOneT: pOneT, - r: r, - q: q, - prePSize: prePSize, - preQSize: preQSize - }; - - - function naf(n) { - let E = n; - const res = []; - while (E.gt(bigInt.zero)) { - if (E.isOdd()) { - const z = 2 - E.mod(4).toJSNumber(); - res.push( z ); - E = E.minus(z); - } else { - res.push( 0 ); - } - E = E.shiftRight(1); - } - return res; - } - - function bits(n) { - let E = n; - const res = []; - while (E.gt(bigInt.zero)) { - if (E.isOdd()) { - res.push( 1 ); - } else { - res.push( 0 ); - } - E = E.shiftRight(1); - } - return res; - } - - function buildPrepareG1() { - const f = module.addFunction(prefix+ "_prepareG1"); - f.addParam("pP", "i32"); - f.addParam("ppreP", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call(g1mPrefix + "_normalize", c.getLocal("pP"), c.getLocal("ppreP")), // TODO Remove if already in affine - ); - } - - - - function buildPrepDoubleStep() { - const f = module.addFunction(prefix+ "_prepDblStep"); - f.addParam("R", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const Rx = c.getLocal("R"); - const Ry = c.i32_add(c.getLocal("R"), c.i32_const(2*n8q)); - const Rz = c.i32_add(c.getLocal("R"), c.i32_const(4*n8q)); - - const t0 = c.getLocal("r"); - const t3 = c.i32_add(c.getLocal("r"), c.i32_const(2*n8q)); - const t6 = c.i32_add(c.getLocal("r"), c.i32_const(4*n8q)); - - - const zsquared = c.i32_const(module.alloc(f2size)); - const t1 = c.i32_const(module.alloc(f2size)); - const t2 = c.i32_const(module.alloc(f2size)); - const t4 = c.i32_const(module.alloc(f2size)); - const t5 = c.i32_const(module.alloc(f2size)); - - f.addCode( - - // tmp0 = r.x.square(); - c.call(f2mPrefix + "_square", Rx, t0), - - // tmp1 = r.y.square(); - c.call(f2mPrefix + "_square", Ry, t1), - - // tmp2 = tmp1.square(); - c.call(f2mPrefix + "_square", t1, t2), - - // tmp3 = (tmp1 + r.x).square() - tmp0 - tmp2; - c.call(f2mPrefix + "_add", t1, Rx, t3), - c.call(f2mPrefix + "_square", t3, t3), - c.call(f2mPrefix + "_sub", t3, t0, t3), - c.call(f2mPrefix + "_sub", t3, t2, t3), - - // tmp3 = tmp3 + tmp3; - c.call(f2mPrefix + "_add", t3, t3, t3), - - // tmp4 = tmp0 + tmp0 + tmp0; - c.call(f2mPrefix + "_add", t0, t0, t4), - c.call(f2mPrefix + "_add", t4, t0, t4), - - // tmp6 = r.x + tmp4; - c.call(f2mPrefix + "_add", Rx, t4, t6), - - // tmp5 = tmp4.square(); - c.call(f2mPrefix + "_square", t4, t5), - - // zsquared = r.z.square(); - c.call(f2mPrefix + "_square", Rz, zsquared), - - // r.x = tmp5 - tmp3 - tmp3; - c.call(f2mPrefix + "_sub", t5, t3, Rx), - c.call(f2mPrefix + "_sub", Rx, t3, Rx), - - // r.z = (r.z + r.y).square() - tmp1 - zsquared; - c.call(f2mPrefix + "_add", Rz, Ry, Rz), - c.call(f2mPrefix + "_square", Rz, Rz), - c.call(f2mPrefix + "_sub", Rz, t1, Rz), - c.call(f2mPrefix + "_sub", Rz, zsquared, Rz), - - // r.y = (tmp3 - r.x) * tmp4; - c.call(f2mPrefix + "_sub", t3, Rx, Ry), - c.call(f2mPrefix + "_mul", Ry, t4, Ry), - - // tmp2 = tmp2 + tmp2; - c.call(f2mPrefix + "_add", t2, t2, t2), - - // tmp2 = tmp2 + tmp2; - c.call(f2mPrefix + "_add", t2, t2, t2), - - // tmp2 = tmp2 + tmp2; - c.call(f2mPrefix + "_add", t2, t2, t2), - - // r.y -= tmp2; - c.call(f2mPrefix + "_sub", Ry, t2, Ry), - - // tmp3 = tmp4 * zsquared; - c.call(f2mPrefix + "_mul", t4, zsquared, t3), - - // tmp3 = tmp3 + tmp3; - c.call(f2mPrefix + "_add", t3, t3, t3), - - // tmp3 = -tmp3; - c.call(f2mPrefix + "_neg", t3, t3), - - // tmp6 = tmp6.square() - tmp0 - tmp5; - c.call(f2mPrefix + "_square", t6, t6), - c.call(f2mPrefix + "_sub", t6, t0, t6), - c.call(f2mPrefix + "_sub", t6, t5, t6), - - // tmp1 = tmp1 + tmp1; - c.call(f2mPrefix + "_add", t1, t1, t1), - - // tmp1 = tmp1 + tmp1; - c.call(f2mPrefix + "_add", t1, t1, t1), - - // tmp6 = tmp6 - tmp1; - c.call(f2mPrefix + "_sub", t6, t1, t6), - - // tmp0 = r.z * zsquared; - c.call(f2mPrefix + "_mul", Rz, zsquared, t0), - - // tmp0 = tmp0 + tmp0; - c.call(f2mPrefix + "_add", t0, t0, t0), - - ); - } - - function buildPrepAddStep() { - const f = module.addFunction(prefix+ "_prepAddStep"); - f.addParam("R", "i32"); - f.addParam("Q", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const Rx = c.getLocal("R"); - const Ry = c.i32_add(c.getLocal("R"), c.i32_const(2*n8q)); - const Rz = c.i32_add(c.getLocal("R"), c.i32_const(4*n8q)); - - const Qx = c.getLocal("Q"); - const Qy = c.i32_add(c.getLocal("Q"), c.i32_const(2*n8q)); - - const t10 = c.getLocal("r"); - const t1 = c.i32_add(c.getLocal("r"), c.i32_const(2*n8q)); - const t9 = c.i32_add(c.getLocal("r"), c.i32_const(4*n8q)); - - const zsquared = c.i32_const(module.alloc(f2size)); - const ysquared = c.i32_const(module.alloc(f2size)); - const ztsquared = c.i32_const(module.alloc(f2size)); - const t0 = c.i32_const(module.alloc(f2size)); - const t2 = c.i32_const(module.alloc(f2size)); - const t3 = c.i32_const(module.alloc(f2size)); - const t4 = c.i32_const(module.alloc(f2size)); - const t5 = c.i32_const(module.alloc(f2size)); - const t6 = c.i32_const(module.alloc(f2size)); - const t7 = c.i32_const(module.alloc(f2size)); - const t8 = c.i32_const(module.alloc(f2size)); - - f.addCode( - - // zsquared = r.z.square(); - c.call(f2mPrefix + "_square", Rz, zsquared), - - // ysquared = q.y.square(); - c.call(f2mPrefix + "_square", Qy, ysquared), - - // t0 = zsquared * q.x; - c.call(f2mPrefix + "_mul", zsquared, Qx, t0), - - // t1 = ((q.y + r.z).square() - ysquared - zsquared) * zsquared; - c.call(f2mPrefix + "_add", Qy, Rz, t1), - c.call(f2mPrefix + "_square", t1, t1), - c.call(f2mPrefix + "_sub", t1, ysquared, t1), - c.call(f2mPrefix + "_sub", t1, zsquared, t1), - c.call(f2mPrefix + "_mul", t1, zsquared, t1), - - // t2 = t0 - r.x; - c.call(f2mPrefix + "_sub", t0, Rx, t2), - - // t3 = t2.square(); - c.call(f2mPrefix + "_square", t2, t3), - - // t4 = t3 + t3; - c.call(f2mPrefix + "_add", t3, t3, t4), - - // t4 = t4 + t4; - c.call(f2mPrefix + "_add", t4, t4, t4), - - // t5 = t4 * t2; - c.call(f2mPrefix + "_mul", t4, t2, t5), - - // t6 = t1 - r.y - r.y; - c.call(f2mPrefix + "_sub", t1, Ry, t6), - c.call(f2mPrefix + "_sub", t6, Ry, t6), - - // t9 = t6 * q.x; - c.call(f2mPrefix + "_mul", t6, Qx, t9), - - // t7 = t4 * r.x; - c.call(f2mPrefix + "_mul", t4, Rx, t7), - - // r.x = t6.square() - t5 - t7 - t7; - c.call(f2mPrefix + "_square", t6, Rx), - c.call(f2mPrefix + "_sub", Rx, t5, Rx), - c.call(f2mPrefix + "_sub", Rx, t7, Rx), - c.call(f2mPrefix + "_sub", Rx, t7, Rx), - - // r.z = (r.z + t2).square() - zsquared - t3; - c.call(f2mPrefix + "_add", Rz, t2, Rz), - c.call(f2mPrefix + "_square", Rz, Rz), - c.call(f2mPrefix + "_sub", Rz, zsquared, Rz), - c.call(f2mPrefix + "_sub", Rz, t3, Rz), - - // t10 = q.y + r.z; - c.call(f2mPrefix + "_add", Qy, Rz, t10), - - // t8 = (t7 - r.x) * t6; - c.call(f2mPrefix + "_sub", t7, Rx, t8), - c.call(f2mPrefix + "_mul", t8, t6, t8), - - // t0 = r.y * t5; - c.call(f2mPrefix + "_mul", Ry, t5, t0), - - // t0 = t0 + t0; - c.call(f2mPrefix + "_add", t0, t0, t0), - - // r.y = t8 - t0; - c.call(f2mPrefix + "_sub", t8, t0, Ry), - - // t10 = t10.square() - ysquared; - c.call(f2mPrefix + "_square", t10, t10), - c.call(f2mPrefix + "_sub", t10, ysquared, t10), - - // ztsquared = r.z.square(); - c.call(f2mPrefix + "_square", Rz, ztsquared), - - // t10 = t10 - ztsquared; - c.call(f2mPrefix + "_sub", t10, ztsquared, t10), - - // t9 = t9 + t9 - t10; - c.call(f2mPrefix + "_add", t9, t9, t9), - c.call(f2mPrefix + "_sub", t9, t10, t9), - - // t10 = r.z + r.z; - c.call(f2mPrefix + "_add", Rz, Rz, t10), - - // t6 = -t6; - c.call(f2mPrefix + "_neg", t6, t6), - - // t1 = t6 + t6; - c.call(f2mPrefix + "_add", t6, t6, t1), - ); - } - - - function buildPrepareG2() { - const f = module.addFunction(prefix+ "_prepareG2"); - f.addParam("pQ", "i32"); - f.addParam("ppreQ", "i32"); - f.addLocal("pCoef", "i32"); - f.addLocal("i", "i32"); - - const c = f.getCodeBuilder(); - - - const Q = c.getLocal("pQ"); - - const pR = module.alloc(f2size*3); - const R = c.i32_const(pR); - - const base = c.getLocal("ppreQ"); - - f.addCode( - c.call(g2mPrefix + "_normalize", Q, base), - c.if( - c.call(g2mPrefix + "_isZero", base), - c.ret([]) - ), - c.call(g2mPrefix + "_copy", base, R), - c.setLocal("pCoef", c.i32_add(c.getLocal("ppreQ"), c.i32_const(f2size*3))), - ); - - f.addCode( - c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), - c.block(c.loop( - - c.call(prefix + "_prepDblStep", R, c.getLocal("pCoef")), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - c.if( - c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), - [ - ...c.call(prefix + "_prepAddStep", R, base, c.getLocal("pCoef")), - ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - ] - ), - c.br_if(1, c.i32_eqz ( c.getLocal("i") )), - c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - ); - } - - - function buildF6Mul1() { - const f = module.addFunction(f6mPrefix+ "_mul1"); - f.addParam("pA", "i32"); // F6 - f.addParam("pC1", "i32"); // F2 - f.addParam("pR", "i32"); // F6 - - const c = f.getCodeBuilder(); - - const A_c0 = c.getLocal("pA"); - const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*2)); - const A_c2 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*4)); - - const c1 = c.getLocal("pC1"); - - const t1 = c.getLocal("pR"); - const t2 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*2)); - const b_b = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*4)); - - const Ac0_Ac1 = c.i32_const(module.alloc(f1size*2)); - const Ac1_Ac2 = c.i32_const(module.alloc(f1size*2)); - - f.addCode( - - c.call(f2mPrefix + "_add", A_c0, A_c1, Ac0_Ac1), - c.call(f2mPrefix + "_add", A_c1, A_c2, Ac1_Ac2), - - // let b_b = self.c1 * c1; - c.call(f2mPrefix + "_mul", A_c1, c1, b_b), - - // let t1 = (self.c1 + self.c2) * c1 - b_b; - c.call(f2mPrefix + "_mul", Ac1_Ac2, c1, t1), - c.call(f2mPrefix + "_sub", t1, b_b, t1), - - // let t1 = t1.mul_by_nonresidue(); - c.call(f2mPrefix + "_mulNR", t1, t1), - - // let t2 = (self.c0 + self.c1) * c1 - b_b; - c.call(f2mPrefix + "_mul", Ac0_Ac1, c1, t2), - c.call(f2mPrefix + "_sub", t2, b_b, t2), - ); - } - buildF6Mul1(); - - function buildF6Mul01() { - const f = module.addFunction(f6mPrefix+ "_mul01"); - f.addParam("pA", "i32"); // F6 - f.addParam("pC0", "i32"); // F2 - f.addParam("pC1", "i32"); // F2 - f.addParam("pR", "i32"); // F6 - - const c = f.getCodeBuilder(); - - const A_c0 = c.getLocal("pA"); - const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*2)); - const A_c2 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*4)); - - const c0 = c.getLocal("pC0"); - const c1 = c.getLocal("pC1"); - - const t1 = c.getLocal("pR"); - const t2 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*2)); - const t3 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*4)); - - const a_a = c.i32_const(module.alloc(f1size*2)); - const b_b = c.i32_const(module.alloc(f1size*2)); - const Ac0_Ac1 = c.i32_const(module.alloc(f1size*2)); - const Ac0_Ac2 = c.i32_const(module.alloc(f1size*2)); - - f.addCode( - // let a_a = self.c0 * c0; - c.call(f2mPrefix + "_mul", A_c0, c0, a_a), - - // let b_b = self.c1 * c1; - c.call(f2mPrefix + "_mul", A_c1, c1, b_b), - - - c.call(f2mPrefix + "_add", A_c0, A_c1, Ac0_Ac1), - c.call(f2mPrefix + "_add", A_c0, A_c2, Ac0_Ac2), - - // let t1 = (self.c1 + self.c2) * c1 - b_b; - c.call(f2mPrefix + "_add", A_c1, A_c2, t1), - c.call(f2mPrefix + "_mul", t1, c1, t1), - c.call(f2mPrefix + "_sub", t1, b_b, t1), - - // let t1 = t1.mul_by_nonresidue() + a_a; - c.call(f2mPrefix + "_mulNR", t1, t1), - c.call(f2mPrefix + "_add", t1, a_a, t1), - - // let t2 = (c0 + c1) * (self.c0 + self.c1) - a_a - b_b; - c.call(f2mPrefix + "_add", c0, c1, t2), - c.call(f2mPrefix + "_mul", t2, Ac0_Ac1, t2), - c.call(f2mPrefix + "_sub", t2, a_a, t2), - c.call(f2mPrefix + "_sub", t2, b_b, t2), - - // let t3 = (self.c0 + self.c2) * c0 - a_a + b_b; - c.call(f2mPrefix + "_mul", Ac0_Ac2, c0, t3), - c.call(f2mPrefix + "_sub", t3, a_a, t3), - c.call(f2mPrefix + "_add", t3, b_b, t3), - - - ); - } - buildF6Mul01(); - - - function buildF12Mul014() { - - const f = module.addFunction(ftmPrefix+ "_mul014"); - f.addParam("pA", "i32"); // F12 - f.addParam("pC0", "i32"); // F2 - f.addParam("pC1", "i32"); // F2 - f.addParam("pC4", "i32"); // F2 - f.addParam("pR", "i32"); // F12 - - const c = f.getCodeBuilder(); - - - const A_c0 = c.getLocal("pA"); - const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*6)); - - const c0 = c.getLocal("pC0"); - const c1 = c.getLocal("pC1"); - const c4 = c.getLocal("pC4"); - - const aa = c.i32_const(module.alloc(f1size*6)); - const bb = c.i32_const(module.alloc(f1size*6)); - const o = c.i32_const(module.alloc(f1size*2)); - - const R_c0 = c.getLocal("pR"); - const R_c1 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*6)); - - f.addCode( - // let aa = self.c0.mul_by_01(c0, c1); - c.call(f6mPrefix + "_mul01", A_c0, c0, c1, aa), - - // let bb = self.c1.mul_by_1(c4); - c.call(f6mPrefix + "_mul1", A_c1, c4, bb), - - // let o = c1 + c4; - c.call(f2mPrefix + "_add", c1, c4, o), - - // let c1 = self.c1 + self.c0; - c.call(f6mPrefix + "_add", A_c1, A_c0, R_c1), - - // let c1 = c1.mul_by_01(c0, &o); - c.call(f6mPrefix + "_mul01", R_c1, c0, o, R_c1), - - // let c1 = c1 - aa - bb; - c.call(f6mPrefix + "_sub", R_c1, aa, R_c1), - c.call(f6mPrefix + "_sub", R_c1, bb, R_c1), - - // let c0 = bb; - c.call(f6mPrefix + "_copy", bb, R_c0), - - // let c0 = c0.mul_by_nonresidue(); - c.call(f6mPrefix + "_mulNR", R_c0, R_c0), - - // let c0 = c0 + aa; - c.call(f6mPrefix + "_add", R_c0, aa, R_c0), - ); - } - buildF12Mul014(); - - - function buildELL() { - const f = module.addFunction(prefix+ "_ell"); - f.addParam("pP", "i32"); - f.addParam("pCoefs", "i32"); - f.addParam("pF", "i32"); - - const c = f.getCodeBuilder(); - - const Px = c.getLocal("pP"); - const Py = c.i32_add(c.getLocal("pP"), c.i32_const(n8q)); - - const F = c.getLocal("pF"); - - const coef0_0 = c.getLocal("pCoefs"); - const coef0_1 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size)); - const coef1_0 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*2)); - const coef1_1 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*3)); - const coef2 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*4)); - - const pc0 = module.alloc(f1size*2); - const c0 = c.i32_const(pc0); - const c0_c0 = c.i32_const(pc0); - const c0_c1 = c.i32_const(pc0+f1size); - - const pc1 = module.alloc(f1size*2); - const c1 = c.i32_const(pc1); - const c1_c0 = c.i32_const(pc1); - const c1_c1 = c.i32_const(pc1+f1size); - f.addCode( - // let mut c0 = coeffs.0; - // let mut c1 = coeffs.1; - // - // c0.c0 *= p.y; - // c0.c1 *= p.y; - // - // c1.c0 *= p.x; - // c1.c1 *= p.x; - // - // f.mul_by_014(&coeffs.2, &c1, &c0) - - c.call(f1mPrefix + "_mul", coef0_0, Py, c0_c0), - c.call(f1mPrefix + "_mul", coef0_1, Py, c0_c1), - c.call(f1mPrefix + "_mul", coef1_0, Px, c1_c0), - c.call(f1mPrefix + "_mul", coef1_1, Px, c1_c1), - - c.call(ftmPrefix + "_mul014", F, coef2, c1, c0, F), - - ); - - } - buildELL(); - - function buildMillerLoop() { - const f = module.addFunction(prefix+ "_millerLoop"); - f.addParam("ppreP", "i32"); - f.addParam("ppreQ", "i32"); - f.addParam("r", "i32"); - f.addLocal("pCoef", "i32"); - f.addLocal("i", "i32"); - - const c = f.getCodeBuilder(); - - const preP = c.getLocal("ppreP"); - const preQ = c.getLocal("ppreQ"); - - const coefs = c.getLocal("pCoef"); - - const F = c.getLocal("r"); - - - f.addCode( - c.call(ftmPrefix + "_one", F), - - c.if( - c.call(g1mPrefix + "_isZero", preP), - c.ret([]) - ), - c.if( - c.call(g1mPrefix + "_isZero", c.getLocal("ppreQ")), - c.ret([]) - ), - c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), - - c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), - c.block(c.loop( - - - c.call(prefix + "_ell", preP, coefs, F), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - c.if( - c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), - [ - ...c.call(prefix + "_ell", preP, coefs, F), - ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - ] - ), - c.call(ftmPrefix + "_square", F, F), - - c.br_if(1, c.i32_eq ( c.getLocal("i"), c.i32_const(1) )), - c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )), - c.call(prefix + "_ell", preP, coefs, F), - - ); - - - if (isLoopNegative) { - f.addCode( - c.call(ftmPrefix + "_conjugate", F, F), - ); - } - } - - - function buildFrobeniusMap(n) { - const F12 = [ - [ - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - ], - [ - [bigInt("1"), bigInt("0")], - [bigInt("3850754370037169011952147076051364057158807420970682438676050522613628423219637725072182697113062777891589506424760"), bigInt("151655185184498381465642749684540099398075398968325446656007613510403227271200139370504932015952886146304766135027")], - [bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620351"), bigInt("0")], - [bigInt("2973677408986561043442465346520108879172042883009249989176415018091420807192182638567116318576472649347015917690530"), bigInt("1028732146235106349975324479215795277384839936929757896155643118032610843298655225875571310552543014690878354869257")], - [bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350"), bigInt("0")], - [bigInt("3125332594171059424908108096204648978570118281977575435832422631601824034463382777937621250592425535493320683825557"), bigInt("877076961050607968509681729531255177986764537961432449499635504522207616027455086505066378536590128544573588734230")], - [bigInt("4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786"), bigInt("0")], - [bigInt("151655185184498381465642749684540099398075398968325446656007613510403227271200139370504932015952886146304766135027"), bigInt("3850754370037169011952147076051364057158807420970682438676050522613628423219637725072182697113062777891589506424760")], - [bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436"), bigInt("0")], - [bigInt("1028732146235106349975324479215795277384839936929757896155643118032610843298655225875571310552543014690878354869257"), bigInt("2973677408986561043442465346520108879172042883009249989176415018091420807192182638567116318576472649347015917690530")], - [bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939437"), bigInt("0")], - [bigInt("877076961050607968509681729531255177986764537961432449499635504522207616027455086505066378536590128544573588734230"), bigInt("3125332594171059424908108096204648978570118281977575435832422631601824034463382777937621250592425535493320683825557")], - ] - ]; - - const F6 = [ - [ - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - ], - [ - [bigInt("1"), bigInt("0")], - [bigInt("0"), bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436")], - [bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350"), bigInt("0")], - [bigInt("0"), bigInt("1")], - [bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436"), bigInt("0")], - [bigInt("0"), bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350")], - ], - [ - [bigInt("1"), bigInt("0")], - [bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939437"), bigInt("0")], - [bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436"), bigInt("0")], - [bigInt("4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786"), bigInt("0")], - [bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350"), bigInt("0")], - [bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620351"), bigInt("0")], - ] - ]; - - const f = module.addFunction(ftmPrefix + "_frobeniusMap"+n); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - for (let i=0; i<6; i++) { - const X = (i==0) ? c.getLocal("x") : c.i32_add(c.getLocal("x"), c.i32_const(i*f2size)); - const Xc0 = X; - const Xc1 = c.i32_add(c.getLocal("x"), c.i32_const(i*f2size + f1size)); - const R = (i==0) ? c.getLocal("r") : c.i32_add(c.getLocal("r"), c.i32_const(i*f2size)); - const Rc0 = R; - const Rc1 = c.i32_add(c.getLocal("r"), c.i32_const(i*f2size + f1size)); - const coef = mul2(F12[Math.floor(i/3)][n%12] , F6[i%3][n%6]); - const pCoef = module.alloc([ - ...utils.bigInt2BytesLE(toMontgomery(coef[0]), n8q), - ...utils.bigInt2BytesLE(toMontgomery(coef[1]), n8q), - ]); - if (n%2 == 1) { - f.addCode( - c.call(f1mPrefix + "_copy", Xc0, Rc0), - c.call(f1mPrefix + "_neg", Xc1, Rc1), - c.call(f2mPrefix + "_mul", R, c.i32_const(pCoef), R), - ); - } else { - f.addCode(c.call(f2mPrefix + "_mul", X, c.i32_const(pCoef), R)); - } - } - - function mul2(a, b) { - const ac0 = bigInt(a[0]); - const ac1 = bigInt(a[1]); - const bc0 = bigInt(b[0]); - const bc1 = bigInt(b[1]); - const res = [ - ac0.times(bc0).minus( ac1.times(bc1) ).mod(q), - ac0.times(bc1).add( ac1.times(bc0) ).mod(q), - ]; - if (res[0].isNegative()) res[0] = res[0].add(q); - return res; - } - - } - - - function buildCyclotomicSquare() { - const f = module.addFunction(prefix+ "__cyclotomicSquare"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x4 = c.i32_add(c.getLocal("x"), c.i32_const(f2size)); - const x3 = c.i32_add(c.getLocal("x"), c.i32_const(2*f2size)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(3*f2size)); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(4*f2size)); - const x5 = c.i32_add(c.getLocal("x"), c.i32_const(5*f2size)); - - const r0 = c.getLocal("r"); - const r4 = c.i32_add(c.getLocal("r"), c.i32_const(f2size)); - const r3 = c.i32_add(c.getLocal("r"), c.i32_const(2*f2size)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(3*f2size)); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(4*f2size)); - const r5 = c.i32_add(c.getLocal("r"), c.i32_const(5*f2size)); - - const t0 = c.i32_const(module.alloc(f2size)); - const t1 = c.i32_const(module.alloc(f2size)); - const t2 = c.i32_const(module.alloc(f2size)); - const t3 = c.i32_const(module.alloc(f2size)); - const t4 = c.i32_const(module.alloc(f2size)); - const t5 = c.i32_const(module.alloc(f2size)); - const tmp = c.i32_const(module.alloc(f2size)); - const AUX = c.i32_const(module.alloc(f2size)); - - - f.addCode( - -// c.call(ftmPrefix + "_square", x0, r0), - - // // t0 + t1*y = (z0 + z1*y)^2 = a^2 - // tmp = z0 * z1; - // t0 = (z0 + z1) * (z0 + my_Fp6::non_residue * z1) - tmp - my_Fp6::non_residue * tmp; - // t1 = tmp + tmp; - c.call(f2mPrefix + "_mul", x0, x1, tmp), - c.call(f2mPrefix + "_mulNR", x1, t0), - c.call(f2mPrefix + "_add", x0, t0, t0), - c.call(f2mPrefix + "_add", x0, x1, AUX), - c.call(f2mPrefix + "_mul", AUX, t0, t0), - c.call(f2mPrefix + "_mulNR", tmp, AUX), - c.call(f2mPrefix + "_add", tmp, AUX, AUX), - c.call(f2mPrefix + "_sub", t0, AUX, t0), - c.call(f2mPrefix + "_add", tmp, tmp, t1), - - // // t2 + t3*y = (z2 + z3*y)^2 = b^2 - // tmp = z2 * z3; - // t2 = (z2 + z3) * (z2 + my_Fp6::non_residue * z3) - tmp - my_Fp6::non_residue * tmp; - // t3 = tmp + tmp; - c.call(f2mPrefix + "_mul", x2, x3, tmp), - c.call(f2mPrefix + "_mulNR", x3, t2), - c.call(f2mPrefix + "_add", x2, t2, t2), - c.call(f2mPrefix + "_add", x2, x3, AUX), - c.call(f2mPrefix + "_mul", AUX, t2, t2), - c.call(f2mPrefix + "_mulNR", tmp, AUX), - c.call(f2mPrefix + "_add", tmp, AUX, AUX), - c.call(f2mPrefix + "_sub", t2, AUX, t2), - c.call(f2mPrefix + "_add", tmp, tmp, t3), - - // // t4 + t5*y = (z4 + z5*y)^2 = c^2 - // tmp = z4 * z5; - // t4 = (z4 + z5) * (z4 + my_Fp6::non_residue * z5) - tmp - my_Fp6::non_residue * tmp; - // t5 = tmp + tmp; - c.call(f2mPrefix + "_mul", x4, x5, tmp), - c.call(f2mPrefix + "_mulNR", x5, t4), - c.call(f2mPrefix + "_add", x4, t4, t4), - c.call(f2mPrefix + "_add", x4, x5, AUX), - c.call(f2mPrefix + "_mul", AUX, t4, t4), - c.call(f2mPrefix + "_mulNR", tmp, AUX), - c.call(f2mPrefix + "_add", tmp, AUX, AUX), - c.call(f2mPrefix + "_sub", t4, AUX, t4), - c.call(f2mPrefix + "_add", tmp, tmp, t5), - - // For A - // z0 = 3 * t0 - 2 * z0 - c.call(f2mPrefix + "_sub", t0, x0, r0), - c.call(f2mPrefix + "_add", r0, r0, r0), - c.call(f2mPrefix + "_add", t0, r0, r0), - // z1 = 3 * t1 + 2 * z1 - c.call(f2mPrefix + "_add", t1, x1, r1), - c.call(f2mPrefix + "_add", r1, r1, r1), - c.call(f2mPrefix + "_add", t1, r1, r1), - - // For B - // z2 = 3 * (xi * t5) + 2 * z2 - c.call(f2mPrefix + "_mul", t5, c.i32_const(pBls12381Twist), AUX), - c.call(f2mPrefix + "_add", AUX, x2, r2), - c.call(f2mPrefix + "_add", r2, r2, r2), - c.call(f2mPrefix + "_add", AUX, r2, r2), - // z3 = 3 * t4 - 2 * z3 - c.call(f2mPrefix + "_sub", t4, x3, r3), - c.call(f2mPrefix + "_add", r3, r3, r3), - c.call(f2mPrefix + "_add", t4, r3, r3), - - // For C - // z4 = 3 * t2 - 2 * z4 - c.call(f2mPrefix + "_sub", t2, x4, r4), - c.call(f2mPrefix + "_add", r4, r4, r4), - c.call(f2mPrefix + "_add", t2, r4, r4), - // z5 = 3 * t3 + 2 * z5 - c.call(f2mPrefix + "_add", t3, x5, r5), - c.call(f2mPrefix + "_add", r5, r5, r5), - c.call(f2mPrefix + "_add", t3, r5, r5), - - ); - } - - - function buildCyclotomicExp(exponent, isExpNegative, fnName) { - const exponentNafBytes = naf(exponent).map( (b) => (b==-1 ? 0xFF: b) ); - const pExponentNafBytes = module.alloc(exponentNafBytes); - // const pExponent = module.alloc(utils.bigInt2BytesLE(exponent, n8)); - - const f = module.addFunction(prefix+ "__cyclotomicExp_"+fnName); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - f.addLocal("bit", "i32"); - f.addLocal("i", "i32"); - - const c = f.getCodeBuilder(); - - const x = c.getLocal("x"); - - const res = c.getLocal("r"); - - const inverse = c.i32_const(module.alloc(ftsize)); - - - f.addCode( -// c.call(ftmPrefix + "_exp", x, c.i32_const(pExponent), c.i32_const(32), res), - - c.call(ftmPrefix + "_conjugate", x, inverse), - c.call(ftmPrefix + "_one", res), - - c.if( - c.teeLocal("bit", c.i32_load8_s(c.i32_const(exponentNafBytes.length-1), pExponentNafBytes)), - c.if( - c.i32_eq( - c.getLocal("bit"), - c.i32_const(1) - ), - c.call(ftmPrefix + "_mul", res, x, res), - c.call(ftmPrefix + "_mul", res, inverse, res), - ) - ), - - c.setLocal("i", c.i32_const(exponentNafBytes.length-2)), - c.block(c.loop( -// c.call(ftmPrefix + "_square", res, res), - c.call(prefix + "__cyclotomicSquare", res, res), - c.if( - c.teeLocal("bit", c.i32_load8_s(c.getLocal("i"), pExponentNafBytes)), - c.if( - c.i32_eq( - c.getLocal("bit"), - c.i32_const(1) - ), - c.call(ftmPrefix + "_mul", res, x, res), - c.call(ftmPrefix + "_mul", res, inverse, res), - ) - ), - c.br_if(1, c.i32_eqz ( c.getLocal("i") )), - c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - ); - - if (isExpNegative) { - f.addCode( - c.call(ftmPrefix + "_conjugate", res, res), - ); - } - - } - - function buildFinalExponentiation() { - buildCyclotomicSquare(); - buildCyclotomicExp(finalExpZ, finalExpIsNegative, "w0"); - - const f = module.addFunction(prefix+ "_finalExponentiation"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const elt = c.getLocal("x"); - const res = c.getLocal("r"); - const t0 = c.i32_const(module.alloc(ftsize)); - const t1 = c.i32_const(module.alloc(ftsize)); - const t2 = c.i32_const(module.alloc(ftsize)); - const t3 = c.i32_const(module.alloc(ftsize)); - const t4 = c.i32_const(module.alloc(ftsize)); - const t5 = c.i32_const(module.alloc(ftsize)); - const t6 = c.i32_const(module.alloc(ftsize)); - - f.addCode( - - // let mut t0 = f.frobenius_map(6) - c.call(ftmPrefix + "_frobeniusMap6", elt, t0), - - // let t1 = f.invert() - c.call(ftmPrefix + "_inverse", elt, t1), - - // let mut t2 = t0 * t1; - c.call(ftmPrefix + "_mul", t0, t1, t2), - - // t1 = t2.clone(); - c.call(ftmPrefix + "_copy", t2, t1), - - // t2 = t2.frobenius_map().frobenius_map(); - c.call(ftmPrefix + "_frobeniusMap2", t2, t2), - - // t2 *= t1; - c.call(ftmPrefix + "_mul", t2, t1, t2), - - - // t1 = cyclotomic_square(t2).conjugate(); - c.call(prefix + "__cyclotomicSquare", t2, t1), - c.call(ftmPrefix + "_conjugate", t1, t1), - - // let mut t3 = cycolotomic_exp(t2); - c.call(prefix + "__cyclotomicExp_w0", t2, t3), - - // let mut t4 = cyclotomic_square(t3); - c.call(prefix + "__cyclotomicSquare", t3, t4), - - // let mut t5 = t1 * t3; - c.call(ftmPrefix + "_mul", t1, t3, t5), - - // t1 = cycolotomic_exp(t5); - c.call(prefix + "__cyclotomicExp_w0", t5, t1), - - // t0 = cycolotomic_exp(t1); - c.call(prefix + "__cyclotomicExp_w0", t1, t0), - - // let mut t6 = cycolotomic_exp(t0); - c.call(prefix + "__cyclotomicExp_w0", t0, t6), - - // t6 *= t4; - c.call(ftmPrefix + "_mul", t6, t4, t6), - - // t4 = cycolotomic_exp(t6); - c.call(prefix + "__cyclotomicExp_w0", t6, t4), - - // t5 = t5.conjugate(); - c.call(ftmPrefix + "_conjugate", t5, t5), - - // t4 *= t5 * t2; - c.call(ftmPrefix + "_mul", t4, t5, t4), - c.call(ftmPrefix + "_mul", t4, t2, t4), - - // t5 = t2.conjugate(); - c.call(ftmPrefix + "_conjugate", t2, t5), - - // t1 *= t2; - c.call(ftmPrefix + "_mul", t1, t2, t1), - - // t1 = t1.frobenius_map().frobenius_map().frobenius_map(); - c.call(ftmPrefix + "_frobeniusMap3", t1, t1), - - // t6 *= t5; - c.call(ftmPrefix + "_mul", t6, t5, t6), - - // t6 = t6.frobenius_map(); - c.call(ftmPrefix + "_frobeniusMap1", t6, t6), - - // t3 *= t0; - c.call(ftmPrefix + "_mul", t3, t0, t3), - - // t3 = t3.frobenius_map().frobenius_map(); - c.call(ftmPrefix + "_frobeniusMap2", t3, t3), - - // t3 *= t1; - c.call(ftmPrefix + "_mul", t3, t1, t3), - - // t3 *= t6; - c.call(ftmPrefix + "_mul", t3, t6, t3), - - // f = t3 * t4; - c.call(ftmPrefix + "_mul", t3, t4, res), - - ); - } - - - function buildFinalExponentiationOld() { - const f = module.addFunction(prefix+ "_finalExponentiationOld"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const exponent = bigInt("322277361516934140462891564586510139908379969514828494218366688025288661041104682794998680497580008899973249814104447692778988208376779573819485263026159588510513834876303014016798809919343532899164848730280942609956670917565618115867287399623286813270357901731510188149934363360381614501334086825442271920079363289954510565375378443704372994881406797882676971082200626541916413184642520269678897559532260949334760604962086348898118982248842634379637598665468817769075878555493752214492790122785850202957575200176084204422751485957336465472324810982833638490904279282696134323072515220044451592646885410572234451732790590013479358343841220074174848221722017083597872017638514103174122784843925578370430843522959600095676285723737049438346544753168912974976791528535276317256904336520179281145394686565050419250614107803233314658825463117900250701199181529205942363159325765991819433914303908860460720581408201373164047773794825411011922305820065611121544561808414055302212057471395719432072209245600258134364584636810093520285711072578721435517884103526483832733289802426157301542744476740008494780363354305116978805620671467071400711358839553375340724899735460480144599782014906586543813292157922220645089192130209334926661588737007768565838519456601560804957985667880395221049249803753582637708560"); - - const pExponent = module.alloc(utils.bigInt2BytesLE( exponent, 544 )); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call(ftmPrefix + "_exp", c.getLocal("x"), c.i32_const(pExponent), c.i32_const(544), c.getLocal("r")), - ); - } - - - const pPreP = module.alloc(prePSize); - const pPreQ = module.alloc(preQSize); - - function buildPairingEquation(nPairings) { - - const f = module.addFunction(prefix+ "_pairingEq"+nPairings); - for (let i=0; i { - -const bigInt = __webpack_require__(92096); -const utils = __webpack_require__(12333); - -const buildF1m =__webpack_require__(70075); -const buildF1 =__webpack_require__(38138); -const buildF2m =__webpack_require__(15420); -const buildF3m =__webpack_require__(77173); -const buildCurve =__webpack_require__(15904); -const buildFFT = __webpack_require__(93911); -const buildPol = __webpack_require__(2896); -const buildQAP = __webpack_require__(10637); -const buildApplyKey = __webpack_require__(23320); - -module.exports = function buildBN128(module, _prefix) { - - const prefix = _prefix || "bn128"; - - if (module.modules[prefix]) return prefix; // already builded - - const q = bigInt("21888242871839275222246405745257275088696311157297823662689037894645226208583"); - const r = bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"); - - - const n64 = Math.floor((q.minus(1).bitLength() - 1)/64) +1; - const n8 = n64*8; - const frsize = n8; - const f1size = n8; - const f2size = f1size * 2; - const f6size = f1size * 6; - const ftsize = f1size * 12; - - const pr = module.alloc(utils.bigInt2BytesLE( r, frsize )); - - const f1mPrefix = buildF1m(module, q, "f1m"); - buildF1(module, r, "fr", "frm"); - - const pG1b = module.alloc(utils.bigInt2BytesLE( toMontgomery(bigInt(3)), f1size )); - const g1mPrefix = buildCurve(module, "g1m", "f1m", pG1b); - - buildFFT(module, "frm", "frm", "frm", "frm_mul"); - - buildPol(module, "pol", "frm"); - buildQAP(module, "qap", "frm"); - - const f2mPrefix = buildF2m(module, "f1m_neg", "f2m", "f1m"); - const pG2b = module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery(bigInt("19485874751759354771024239261021720505790618469301721065564631296452457478373")), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(bigInt("266929791119991161246907387137283842545076965332900288569378510910307636690")), f1size ) - ]); - const g2mPrefix = buildCurve(module, "g2m", "f2m", pG2b); - - - function buildGTimesFr(fnName, opMul) { - const f = module.addFunction(fnName); - f.addParam("pG", "i32"); - f.addParam("pFr", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - const AUX = c.i32_const(module.alloc(n8)); - - f.addCode( - c.call("frm_fromMontgomery", c.getLocal("pFr"), AUX), - c.call( - opMul, - c.getLocal("pG"), - AUX, - c.i32_const(n8), - c.getLocal("pr") - ) - ); - - module.exportFunction(fnName); - } - buildGTimesFr("g1m_timesFr", "g1m_timesScalar"); - buildFFT(module, "g1m", "g1m", "frm", "g1m_timesFr"); - - buildGTimesFr("g2m_timesFr", "g2m_timesScalar"); - buildFFT(module, "g2m", "g2m", "frm", "g2m_timesFr"); - - buildGTimesFr("g1m_timesFrAffine", "g1m_timesScalarAffine"); - buildGTimesFr("g2m_timesFrAffine", "g2m_timesScalarAffine"); - - buildApplyKey(module, "frm_batchApplyKey", "fmr", "frm", n8, n8, n8, "frm_mul"); - buildApplyKey(module, "g1m_batchApplyKey", "g1m", "frm", n8*3, n8*3, n8, "g1m_timesFr"); - buildApplyKey(module, "g1m_batchApplyKeyMixed", "g1m", "frm", n8*2, n8*3, n8, "g1m_timesFrAffine"); - buildApplyKey(module, "g2m_batchApplyKey", "g2m", "frm", n8*2*3, n8*3*2, n8, "g2m_timesFr"); - buildApplyKey(module, "g2m_batchApplyKeyMixed", "g2m", "frm", n8*2*2, n8*3*2, n8, "g2m_timesFrAffine"); - - function toMontgomery(a) { - return bigInt(a).times( bigInt.one.shiftLeft(f1size*8)).mod(q); - } - - const G1gen = [ - bigInt("1"), - bigInt("2"), - bigInt.one - ]; - - const pG1gen = module.alloc( - [ - ...utils.bigInt2BytesLE( toMontgomery(G1gen[0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G1gen[1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G1gen[2]), f1size ), - ] - ); - - const G1zero = [ - bigInt.zero, - bigInt.one, - bigInt.zero - ]; - - const pG1zero = module.alloc( - [ - ...utils.bigInt2BytesLE( toMontgomery(G1zero[0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G1zero[1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G1zero[2]), f1size ) - ] - ); - - const G2gen = [ - [ - bigInt("10857046999023057135944570762232829481370756359578518086990519993285655852781"), - bigInt("11559732032986387107991004021392285783925812861821192530917403151452391805634"), - ],[ - bigInt("8495653923123431417604973247489272438418190587263600148770280649306958101930"), - bigInt("4082367875863433681332203403145435568316851327593401208105741076214120093531"), - ],[ - bigInt.one, - bigInt.zero, - ] - ]; - - const pG2gen = module.alloc( - [ - ...utils.bigInt2BytesLE( toMontgomery(G2gen[0][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2gen[0][1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2gen[1][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2gen[1][1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2gen[2][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2gen[2][1]), f1size ), - ] - ); - - const G2zero = [ - [ - bigInt.zero, - bigInt.zero, - ],[ - bigInt.one, - bigInt.zero, - ],[ - bigInt.zero, - bigInt.zero, - ] - ]; - - const pG2zero = module.alloc( - [ - ...utils.bigInt2BytesLE( toMontgomery(G2zero[0][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2zero[0][1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2zero[1][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2zero[1][1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2zero[2][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2zero[2][1]), f1size ), - ] - ); - - const pOneT = module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery(1), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ]); - - const pNonResidueF6 = module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery(9), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(1), f1size ), - ]); - - const pTwoInv = module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery( bigInt(2).modInv(q)), f1size ), - ...utils.bigInt2BytesLE( bigInt(0), f1size ) - ]); - - const pAltBn128Twist = pNonResidueF6; - - const pTwistCoefB = module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery("19485874751759354771024239261021720505790618469301721065564631296452457478373"), f1size ), - ...utils.bigInt2BytesLE( toMontgomery("266929791119991161246907387137283842545076965332900288569378510910307636690"), f1size ), - ]); - - function build_mulNR6() { - const f = module.addFunction(prefix + "_mulNR6"); - f.addParam("x", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call( - f2mPrefix + "_mul", - c.i32_const(pNonResidueF6), - c.getLocal("x"), - c.getLocal("pr") - ) - ); - } - build_mulNR6(); - - const f6mPrefix = buildF3m(module, prefix+"_mulNR6", "f6m", "f2m"); - - function build_mulNR12() { - const f = module.addFunction(prefix + "_mulNR12"); - f.addParam("x", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call( - f2mPrefix + "_mul", - c.i32_const(pNonResidueF6), - c.i32_add(c.getLocal("x"), c.i32_const(n8*4)), - c.getLocal("pr") - ), - c.call( - f2mPrefix + "_copy", - c.getLocal("x"), - c.i32_add(c.getLocal("pr"), c.i32_const(n8*2)), - ), - c.call( - f2mPrefix + "_copy", - c.i32_add(c.getLocal("x"), c.i32_const(n8*2)), - c.i32_add(c.getLocal("pr"), c.i32_const(n8*4)), - ) - ); - } - build_mulNR12(); - - const ftmPrefix = buildF2m(module, prefix+"_mulNR12", "ftm", f6mPrefix); - - - const ateLoopCount = bigInt("29793968203157093288"); - const ateLoopBitBytes = bits(ateLoopCount); - const pAteLoopBitBytes = module.alloc(ateLoopBitBytes); - const isLoopNegative = false; - - const ateCoefSize = 3 * f2size; - const ateNDblCoefs = ateLoopBitBytes.length-1; - const ateNAddCoefs = ateLoopBitBytes.reduce((acc, b) => acc + ( b!=0 ? 1 : 0) ,0); - const ateNCoefs = ateNAddCoefs + ateNDblCoefs + 1; - const prePSize = 3*2*n8; - const preQSize = 3*n8*2 + ateNCoefs*ateCoefSize; - const finalExpIsNegative = false; - - - module.modules[prefix] = { - n64: n64, - pG1gen: pG1gen, - pG1zero: pG1zero, - pG1b: pG1b, - pG2gen: pG2gen, - pG2zero: pG2zero, - pG2b: pG2b, - pq: module.modules["f1m"].pq, - pr: pr, - pOneT: pOneT, - prePSize: prePSize, - preQSize: preQSize, - r: r.toString(), - q: q.toString() - }; - - // console.log("PrePSize: " +prePSize); - // console.log("PreQSize: " +preQSize); - - const finalExpZ = bigInt("4965661367192848881"); - - function naf(n) { - let E = n; - const res = []; - while (E.gt(bigInt.zero)) { - if (E.isOdd()) { - const z = 2 - E.mod(4).toJSNumber(); - res.push( z ); - E = E.minus(z); - } else { - res.push( 0 ); - } - E = E.shiftRight(1); - } - return res; - } - - function bits(n) { - let E = n; - const res = []; - while (E.gt(bigInt.zero)) { - if (E.isOdd()) { - res.push( 1 ); - } else { - res.push( 0 ); - } - E = E.shiftRight(1); - } - return res; - } - - function buildPrepareG1() { - const f = module.addFunction(prefix+ "_prepareG1"); - f.addParam("pP", "i32"); - f.addParam("ppreP", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call(g1mPrefix + "_normalize", c.getLocal("pP"), c.getLocal("ppreP")), // TODO Remove if already in affine - ); - } - - function buildPrepAddStep() { - const f = module.addFunction(prefix+ "_prepAddStep"); - f.addParam("pQ", "i32"); - f.addParam("pR", "i32"); - f.addParam("pCoef", "i32"); - - const c = f.getCodeBuilder(); - - const X2 = c.getLocal("pQ"); - const Y2 = c.i32_add(c.getLocal("pQ"), c.i32_const(f2size)); - - const X1 = c.getLocal("pR"); - const Y1 = c.i32_add(c.getLocal("pR"), c.i32_const(f2size)); - const Z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*f2size)); - - const ELL_0 = c.getLocal("pCoef"); - const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); - const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); - - const D = ELL_VW; - const E = c.i32_const(module.alloc(f2size)); - const F = c.i32_const(module.alloc(f2size)); - const G = c.i32_const(module.alloc(f2size)); - const H = c.i32_const(module.alloc(f2size)); - const I = c.i32_const(module.alloc(f2size)); - const J = c.i32_const(module.alloc(f2size)); - const AUX = c.i32_const(module.alloc(f2size)); - - f.addCode( - // D = X1 - X2*Z1 - c.call(f2mPrefix + "_mul", X2, Z1, D), - c.call(f2mPrefix + "_sub", X1, D, D), - - // E = Y1 - Y2*Z1 - c.call(f2mPrefix + "_mul", Y2, Z1, E), - c.call(f2mPrefix + "_sub", Y1, E, E), - - // F = D^2 - c.call(f2mPrefix + "_square", D, F), - - // G = E^2 - c.call(f2mPrefix + "_square", E, G), - - // H = D*F - c.call(f2mPrefix + "_mul", D, F, H), - - // I = X1 * F - c.call(f2mPrefix + "_mul", X1, F, I), - - // J = H + Z1*G - (I+I) - c.call(f2mPrefix + "_add", I, I, AUX), - c.call(f2mPrefix + "_mul", Z1, G, J), - c.call(f2mPrefix + "_add", H, J, J), - c.call(f2mPrefix + "_sub", J, AUX, J), - - - // X3 (X1) = D*J - c.call(f2mPrefix + "_mul", D, J, X1), - - // Y3 (Y1) = E*(I-J)-(H*Y1) - c.call(f2mPrefix + "_mul", H, Y1, Y1), - c.call(f2mPrefix + "_sub", I, J, AUX), - c.call(f2mPrefix + "_mul", E, AUX, AUX), - c.call(f2mPrefix + "_sub", AUX, Y1, Y1), - - // Z3 (Z1) = Z1*H - c.call(f2mPrefix + "_mul", Z1, H, Z1), - - // ell_0 = xi * (E * X2 - D * Y2) - c.call(f2mPrefix + "_mul", D, Y2, AUX), - c.call(f2mPrefix + "_mul", E, X2, ELL_0), - c.call(f2mPrefix + "_sub", ELL_0, AUX, ELL_0), - c.call(f2mPrefix + "_mul", ELL_0, c.i32_const(pAltBn128Twist), ELL_0), - - - // ell_VV = - E (later: * xP) - c.call(f2mPrefix + "_neg", E, ELL_VV), - - // ell_VW = D (later: * yP ) - // Already assigned - - ); - } - - - - function buildPrepDoubleStep() { - const f = module.addFunction(prefix+ "_prepDblStep"); - f.addParam("pR", "i32"); - f.addParam("pCoef", "i32"); - - const c = f.getCodeBuilder(); - - const X1 = c.getLocal("pR"); - const Y1 = c.i32_add(c.getLocal("pR"), c.i32_const(f2size)); - const Z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*f2size)); - - const ELL_0 = c.getLocal("pCoef"); - const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); - const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); - - const A = c.i32_const(module.alloc(f2size)); - const B = c.i32_const(module.alloc(f2size)); - const C = c.i32_const(module.alloc(f2size)); - const D = c.i32_const(module.alloc(f2size)); - const E = c.i32_const(module.alloc(f2size)); - const F = c.i32_const(module.alloc(f2size)); - const G = c.i32_const(module.alloc(f2size)); - const H = c.i32_const(module.alloc(f2size)); - const I = c.i32_const(module.alloc(f2size)); - const J = c.i32_const(module.alloc(f2size)); - const E2 = c.i32_const(module.alloc(f2size)); - const AUX = c.i32_const(module.alloc(f2size)); - - f.addCode( - - // A = X1 * Y1 / 2 - c.call(f2mPrefix + "_mul", Y1, c.i32_const(pTwoInv), A), - c.call(f2mPrefix + "_mul", X1, A, A), - - // B = Y1^2 - c.call(f2mPrefix + "_square", Y1, B), - - // C = Z1^2 - c.call(f2mPrefix + "_square", Z1, C), - - // D = 3 * C - c.call(f2mPrefix + "_add", C, C, D), - c.call(f2mPrefix + "_add", D, C, D), - - // E = twist_b * D - c.call(f2mPrefix + "_mul", c.i32_const(pTwistCoefB), D, E), - - // F = 3 * E - c.call(f2mPrefix + "_add", E, E, F), - c.call(f2mPrefix + "_add", E, F, F), - - // G = (B+F)/2 - c.call(f2mPrefix + "_add", B, F, G), - c.call(f2mPrefix + "_mul", G, c.i32_const(pTwoInv), G), - - // H = (Y1+Z1)^2-(B+C) - c.call(f2mPrefix + "_add", B, C, AUX), - c.call(f2mPrefix + "_add", Y1, Z1, H), - c.call(f2mPrefix + "_square", H, H), - c.call(f2mPrefix + "_sub", H, AUX, H), - - // I = E-B - c.call(f2mPrefix + "_sub", E, B, I), - - // J = X1^2 - c.call(f2mPrefix + "_square", X1, J), - - // E_squared = E^2 - c.call(f2mPrefix + "_square", E, E2), - - // X3 (X1) = A * (B-F) - c.call(f2mPrefix + "_sub", B, F, AUX), - c.call(f2mPrefix + "_mul", A, AUX, X1), - - // Y3 (Y1) = G^2 - 3*E^2 - c.call(f2mPrefix + "_add", E2, E2, AUX), - c.call(f2mPrefix + "_add", E2, AUX, AUX), - c.call(f2mPrefix + "_square", G, Y1), - c.call(f2mPrefix + "_sub", Y1, AUX, Y1), - - // Z3 (Z1) = B * H - c.call(f2mPrefix + "_mul", B, H, Z1), - - // ell_0 = xi * I - c.call(f2mPrefix + "_mul", c.i32_const(pAltBn128Twist), I, ELL_0), - - // ell_VW = - H (later: * yP) - c.call(f2mPrefix + "_neg", H, ELL_VW), - - // ell_VV = 3*J (later: * xP) - c.call(f2mPrefix + "_add", J, J, ELL_VV), - c.call(f2mPrefix + "_add", J, ELL_VV, ELL_VV), - - ); - } - - function buildMulByQ() { - const f = module.addFunction(prefix + "_mulByQ"); - f.addParam("p1", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - const x = c.getLocal("p1"); - const y = c.i32_add(c.getLocal("p1"), c.i32_const(f2size)); - const z = c.i32_add(c.getLocal("p1"), c.i32_const(f2size*2)); - const x3 = c.getLocal("pr"); - const y3 = c.i32_add(c.getLocal("pr"), c.i32_const(f2size)); - const z3 = c.i32_add(c.getLocal("pr"), c.i32_const(f2size*2)); - - const MulByQX = c.i32_const(module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery("21575463638280843010398324269430826099269044274347216827212613867836435027261"), f1size ), - ...utils.bigInt2BytesLE( toMontgomery("10307601595873709700152284273816112264069230130616436755625194854815875713954"), f1size ), - ])); - - const MulByQY = c.i32_const(module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery("2821565182194536844548159561693502659359617185244120367078079554186484126554"), f1size ), - ...utils.bigInt2BytesLE( toMontgomery("3505843767911556378687030309984248845540243509899259641013678093033130930403"), f1size ), - ])); - - f.addCode( - // The frobeniusMap(1) in this field, is the conjugate - c.call(f2mPrefix + "_conjugate", x, x3), - c.call(f2mPrefix + "_mul", MulByQX, x3, x3), - c.call(f2mPrefix + "_conjugate", y, y3), - c.call(f2mPrefix + "_mul", MulByQY, y3, y3), - c.call(f2mPrefix + "_conjugate", z, z3), - ); - } - - - function buildPrepareG2() { - buildMulByQ(); - const f = module.addFunction(prefix+ "_prepareG2"); - f.addParam("pQ", "i32"); - f.addParam("ppreQ", "i32"); - f.addLocal("pCoef", "i32"); - f.addLocal("i", "i32"); - - const c = f.getCodeBuilder(); - - const QX = c.getLocal("pQ"); - const QY = c.i32_add( c.getLocal("pQ"), c.i32_const(f2size)); - const QZ = c.i32_add( c.getLocal("pQ"), c.i32_const(f2size*2)); - - const pR = module.alloc(f2size*3); - const R = c.i32_const(pR); - const RX = c.i32_const(pR); - const RY = c.i32_const(pR+f2size); - const RZ = c.i32_const(pR+2*f2size); - - const cQX = c.i32_add( c.getLocal("ppreQ"), c.i32_const(0)); - const cQY = c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size)); - const cQZ = c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*2)); - - const pQ1 = module.alloc(f2size*3); - const Q1 = c.i32_const(pQ1); - - const pQ2 = module.alloc(f2size*3); - const Q2 = c.i32_const(pQ2); - const Q2X = c.i32_const(pQ2); - const Q2Y = c.i32_const(pQ2 + f2size); - const Q2Z = c.i32_const(pQ2 + f2size*2); - - f.addCode( - c.call(g2mPrefix + "_normalize", QX, cQX), // TODO Remove if already in affine - c.call(f2mPrefix + "_copy", cQX, RX), - c.call(f2mPrefix + "_copy", cQY, RY), - c.call(f2mPrefix + "_one", RZ), - ); - - f.addCode( - c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), - c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), - c.block(c.loop( - - c.call(prefix + "_prepDblStep", R, c.getLocal("pCoef")), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - c.if( - c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), - [ - ...c.call(prefix + "_prepAddStep", cQX, R, c.getLocal("pCoef")), - ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - ] - ), - c.br_if(1, c.i32_eqz ( c.getLocal("i") )), - c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - ); - - f.addCode( - c.call(prefix + "_mulByQ", cQX, Q1), - c.call(prefix + "_mulByQ", Q1, Q2) - ); - - if (isLoopNegative) { - f.addCode( - c.call(f2mPrefix + "_neg", RY, RY), - ); - } - - f.addCode( - c.call(f2mPrefix + "_neg", Q2Y, Q2Y), - - c.call(prefix + "_prepAddStep", Q1, R, c.getLocal("pCoef")), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - c.call(prefix + "_prepAddStep", Q2, R, c.getLocal("pCoef")), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - ); - } - - function buildMulBy024Old() { - const f = module.addFunction(prefix+ "__mulBy024Old"); - f.addParam("pEll0", "i32"); - f.addParam("pEllVW", "i32"); - f.addParam("pEllVV", "i32"); - f.addParam("pR", "i32"); // Result in F12 - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("pEll0"); - const x2 = c.getLocal("pEllVV"); - const x4 = c.getLocal("pEllVW"); - - const z0 = c.getLocal("pR"); - - const pAUX12 = module.alloc(ftsize); - const AUX12 = c.i32_const(pAUX12); - const AUX12_0 = c.i32_const(pAUX12); - const AUX12_2 = c.i32_const(pAUX12+f2size); - const AUX12_4 = c.i32_const(pAUX12+f2size*2); - const AUX12_6 = c.i32_const(pAUX12+f2size*3); - const AUX12_8 = c.i32_const(pAUX12+f2size*4); - const AUX12_10 = c.i32_const(pAUX12+f2size*5); - - f.addCode( - - c.call(f2mPrefix + "_copy", x0, AUX12_0), - c.call(f2mPrefix + "_zero", AUX12_2), - c.call(f2mPrefix + "_copy", x2, AUX12_4), - c.call(f2mPrefix + "_zero", AUX12_6), - c.call(f2mPrefix + "_copy", x4, AUX12_8), - c.call(f2mPrefix + "_zero", AUX12_10), - c.call(ftmPrefix + "_mul", AUX12, z0, z0), - ); - } - - function buildMulBy024() { - const f = module.addFunction(prefix+ "__mulBy024"); - f.addParam("pEll0", "i32"); - f.addParam("pEllVW", "i32"); - f.addParam("pEllVV", "i32"); - f.addParam("pR", "i32"); // Result in F12 - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("pEll0"); - const x2 = c.getLocal("pEllVV"); - const x4 = c.getLocal("pEllVW"); - - const z0 = c.getLocal("pR"); - const z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*n8)); - const z2 = c.i32_add(c.getLocal("pR"), c.i32_const(4*n8)); - const z3 = c.i32_add(c.getLocal("pR"), c.i32_const(6*n8)); - const z4 = c.i32_add(c.getLocal("pR"), c.i32_const(8*n8)); - const z5 = c.i32_add(c.getLocal("pR"), c.i32_const(10*n8)); - - const t0 = c.i32_const(module.alloc(f2size)); - const t1 = c.i32_const(module.alloc(f2size)); - const t2 = c.i32_const(module.alloc(f2size)); - const s0 = c.i32_const(module.alloc(f2size)); - const T3 = c.i32_const(module.alloc(f2size)); - const T4 = c.i32_const(module.alloc(f2size)); - const D0 = c.i32_const(module.alloc(f2size)); - const D2 = c.i32_const(module.alloc(f2size)); - const D4 = c.i32_const(module.alloc(f2size)); - const S1 = c.i32_const(module.alloc(f2size)); - const AUX = c.i32_const(module.alloc(f2size)); - - f.addCode( - - // D0 = z0 * x0; - c.call(f2mPrefix + "_mul", z0, x0, D0), - // D2 = z2 * x2; - c.call(f2mPrefix + "_mul", z2, x2, D2), - // D4 = z4 * x4; - c.call(f2mPrefix + "_mul", z4, x4, D4), - // t2 = z0 + z4; - c.call(f2mPrefix + "_add", z0, z4, t2), - // t1 = z0 + z2; - c.call(f2mPrefix + "_add", z0, z2, t1), - // s0 = z1 + z3 + z5; - c.call(f2mPrefix + "_add", z1, z3, s0), - c.call(f2mPrefix + "_add", s0, z5, s0), - - - // For z.a_.a_ = z0. - // S1 = z1 * x2; - c.call(f2mPrefix + "_mul", z1, x2, S1), - // T3 = S1 + D4; - c.call(f2mPrefix + "_add", S1, D4, T3), - // T4 = my_Fp6::non_residue * T3 + D0; - c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), - c.call(f2mPrefix + "_add", T4, D0, z0), - // z0 = T4; - - // For z.a_.b_ = z1 - // T3 = z5 * x4; - c.call(f2mPrefix + "_mul", z5, x4, T3), - // S1 = S1 + T3; - c.call(f2mPrefix + "_add", S1, T3, S1), - // T3 = T3 + D2; - c.call(f2mPrefix + "_add", T3, D2, T3), - // T4 = my_Fp6::non_residue * T3; - c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), - // T3 = z1 * x0; - c.call(f2mPrefix + "_mul", z1, x0, T3), - // S1 = S1 + T3; - c.call(f2mPrefix + "_add", S1, T3, S1), - // T4 = T4 + T3; - c.call(f2mPrefix + "_add", T4, T3, z1), - // z1 = T4; - - - - // For z.a_.c_ = z2 - // t0 = x0 + x2; - c.call(f2mPrefix + "_add", x0, x2, t0), - // T3 = t1 * t0 - D0 - D2; - c.call(f2mPrefix + "_mul", t1, t0, T3), - c.call(f2mPrefix + "_add", D0, D2, AUX), - c.call(f2mPrefix + "_sub", T3, AUX, T3), - // T4 = z3 * x4; - c.call(f2mPrefix + "_mul", z3, x4, T4), - // S1 = S1 + T4; - c.call(f2mPrefix + "_add", S1, T4, S1), - - - // For z.b_.a_ = z3 (z3 needs z2) - // t0 = z2 + z4; - c.call(f2mPrefix + "_add", z2, z4, t0), - // T3 = T3 + T4; - // z2 = T3; - c.call(f2mPrefix + "_add", T3, T4, z2), - // t1 = x2 + x4; - c.call(f2mPrefix + "_add", x2, x4, t1), - // T3 = t0 * t1 - D2 - D4; - c.call(f2mPrefix + "_mul", t1, t0, T3), - c.call(f2mPrefix + "_add", D2, D4, AUX), - c.call(f2mPrefix + "_sub", T3, AUX, T3), - // T4 = my_Fp6::non_residue * T3; - c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), - // T3 = z3 * x0; - c.call(f2mPrefix + "_mul", z3, x0, T3), - // S1 = S1 + T3; - c.call(f2mPrefix + "_add", S1, T3, S1), - // T4 = T4 + T3; - c.call(f2mPrefix + "_add", T4, T3, z3), - // z3 = T4; - - // For z.b_.b_ = z4 - // T3 = z5 * x2; - c.call(f2mPrefix + "_mul", z5, x2, T3), - // S1 = S1 + T3; - c.call(f2mPrefix + "_add", S1, T3, S1), - // T4 = my_Fp6::non_residue * T3; - c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), - // t0 = x0 + x4; - c.call(f2mPrefix + "_add", x0, x4, t0), - // T3 = t2 * t0 - D0 - D4; - c.call(f2mPrefix + "_mul", t2, t0, T3), - c.call(f2mPrefix + "_add", D0, D4, AUX), - c.call(f2mPrefix + "_sub", T3, AUX, T3), - // T4 = T4 + T3; - c.call(f2mPrefix + "_add", T4, T3, z4), - // z4 = T4; - - // For z.b_.c_ = z5. - // t0 = x0 + x2 + x4; - c.call(f2mPrefix + "_add", x0, x2, t0), - c.call(f2mPrefix + "_add", t0, x4, t0), - // T3 = s0 * t0 - S1; - c.call(f2mPrefix + "_mul", s0, t0, T3), - c.call(f2mPrefix + "_sub", T3, S1, z5), - // z5 = T3; - - ); - } - - - function buildMillerLoop() { - const f = module.addFunction(prefix+ "_millerLoop"); - f.addParam("ppreP", "i32"); - f.addParam("ppreQ", "i32"); - f.addParam("r", "i32"); - f.addLocal("pCoef", "i32"); - f.addLocal("i", "i32"); - - const c = f.getCodeBuilder(); - - const preP_PX = c.getLocal("ppreP"); - const preP_PY = c.i32_add(c.getLocal("ppreP"), c.i32_const(f1size)); - - const ELL_0 = c.getLocal("pCoef"); - const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); - const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); - - - const pVW = module.alloc(f2size); - const VW = c.i32_const(pVW); - const pVV = module.alloc(f2size); - const VV = c.i32_const(pVV); - - const F = c.getLocal("r"); - - - f.addCode( - c.call(ftmPrefix + "_one", F), - - c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), - - c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), - c.block(c.loop( - - - c.call(ftmPrefix + "_square", F, F), - - c.call(f2mPrefix + "_mul1", ELL_VW,preP_PY, VW), - c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), - c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - c.if( - c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), - [ - ...c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), - ...c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), - - ...c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), - ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - ] - ), - c.br_if(1, c.i32_eqz ( c.getLocal("i") )), - c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - - ); - - if (isLoopNegative) { - f.addCode( - c.call(ftmPrefix + "_inverse", F, F), - ); - } - - f.addCode( - c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), - c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), - c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), - c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), - c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - ); - - } - - - function buildFrobeniusMap(n) { - const F12 = [ - [ - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - ], - [ - [bigInt("1"), bigInt("0")], - [bigInt("8376118865763821496583973867626364092589906065868298776909617916018768340080"), bigInt("16469823323077808223889137241176536799009286646108169935659301613961712198316")], - [bigInt("21888242871839275220042445260109153167277707414472061641714758635765020556617"), bigInt("0")], - [bigInt("11697423496358154304825782922584725312912383441159505038794027105778954184319"), bigInt("303847389135065887422783454877609941456349188919719272345083954437860409601")], - [bigInt("21888242871839275220042445260109153167277707414472061641714758635765020556616"), bigInt("0")], - [bigInt("3321304630594332808241809054958361220322477375291206261884409189760185844239"), bigInt("5722266937896532885780051958958348231143373700109372999374820235121374419868")], - [bigInt("21888242871839275222246405745257275088696311157297823662689037894645226208582"), bigInt("0")], - [bigInt("13512124006075453725662431877630910996106405091429524885779419978626457868503"), bigInt("5418419548761466998357268504080738289687024511189653727029736280683514010267")], - [bigInt("2203960485148121921418603742825762020974279258880205651966"), bigInt("0")], - [bigInt("10190819375481120917420622822672549775783927716138318623895010788866272024264"), bigInt("21584395482704209334823622290379665147239961968378104390343953940207365798982")], - [bigInt("2203960485148121921418603742825762020974279258880205651967"), bigInt("0")], - [bigInt("18566938241244942414004596690298913868373833782006617400804628704885040364344"), bigInt("16165975933942742336466353786298926857552937457188450663314217659523851788715")], - ] - ]; - - const F6 = [ - [ - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - ], - [ - [bigInt("1"), bigInt("0")], - [bigInt("21575463638280843010398324269430826099269044274347216827212613867836435027261"), bigInt("10307601595873709700152284273816112264069230130616436755625194854815875713954")], - [bigInt("21888242871839275220042445260109153167277707414472061641714758635765020556616"), bigInt("0")], - [bigInt("3772000881919853776433695186713858239009073593817195771773381919316419345261"), bigInt("2236595495967245188281701248203181795121068902605861227855261137820944008926")], - [bigInt("2203960485148121921418603742825762020974279258880205651966"), bigInt("0")], - [bigInt("18429021223477853657660792034369865839114504446431234726392080002137598044644"), bigInt("9344045779998320333812420223237981029506012124075525679208581902008406485703")], - ], - [ - [bigInt("1"), bigInt("0")], - [bigInt("2581911344467009335267311115468803099551665605076196740867805258568234346338"), bigInt("19937756971775647987995932169929341994314640652964949448313374472400716661030")], - [bigInt("2203960485148121921418603742825762020974279258880205651966"), bigInt("0")], - [bigInt("5324479202449903542726783395506214481928257762400643279780343368557297135718"), bigInt("16208900380737693084919495127334387981393726419856888799917914180988844123039")], - [bigInt("21888242871839275220042445260109153167277707414472061641714758635765020556616"), bigInt("0")], - [bigInt("13981852324922362344252311234282257507216387789820983642040889267519694726527"), bigInt("7629828391165209371577384193250820201684255241773809077146787135900891633097")], - ] - ]; - - const f = module.addFunction(prefix+ "__frobeniusMap"+n); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - for (let i=0; i<6; i++) { - const X = (i==0) ? c.getLocal("x") : c.i32_add(c.getLocal("x"), c.i32_const(i*f2size)); - const Xc0 = X; - const Xc1 = c.i32_add(c.getLocal("x"), c.i32_const(i*f2size + f1size)); - const R = (i==0) ? c.getLocal("r") : c.i32_add(c.getLocal("r"), c.i32_const(i*f2size)); - const Rc0 = R; - const Rc1 = c.i32_add(c.getLocal("r"), c.i32_const(i*f2size + f1size)); - const coef = mul2(F12[Math.floor(i/3)][n%12] , F6[i%3][n%6]); - const pCoef = module.alloc([ - ...utils.bigInt2BytesLE(toMontgomery(coef[0]), 32), - ...utils.bigInt2BytesLE(toMontgomery(coef[1]), 32), - ]); - if (n%2 == 1) { - f.addCode( - c.call(f1mPrefix + "_copy", Xc0, Rc0), - c.call(f1mPrefix + "_neg", Xc1, Rc1), - c.call(f2mPrefix + "_mul", R, c.i32_const(pCoef), R), - ); - } else { - f.addCode(c.call(f2mPrefix + "_mul", X, c.i32_const(pCoef), R)); - } - } - - function mul2(a, b) { - const ac0 = bigInt(a[0]); - const ac1 = bigInt(a[1]); - const bc0 = bigInt(b[0]); - const bc1 = bigInt(b[1]); - const res = [ - ac0.times(bc0).minus( ac1.times(bc1) ).mod(q), - ac0.times(bc1).add( ac1.times(bc0) ).mod(q), - ]; - if (res[0].isNegative()) res[0] = res[0].add(q); - return res; - } - - } - - - - function buildFinalExponentiationFirstChunk() { - - const f = module.addFunction(prefix+ "__finalExponentiationFirstChunk"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const elt = c.getLocal("x"); - const eltC0 = elt; - const eltC1 = c.i32_add(elt, c.i32_const(n8*6)); - const r = c.getLocal("r"); - const pA = module.alloc(ftsize); - const A = c.i32_const(pA); - const Ac0 = A; - const Ac1 = c.i32_const(pA + n8*6); - const B = c.i32_const(module.alloc(ftsize)); - const C = c.i32_const(module.alloc(ftsize)); - const D = c.i32_const(module.alloc(ftsize)); - - f.addCode( - // const alt_bn128_Fq12 A = alt_bn128_Fq12(elt.c0,-elt.c1); - c.call(f6mPrefix + "_copy", eltC0, Ac0), - c.call(f6mPrefix + "_neg", eltC1, Ac1), - - // const alt_bn128_Fq12 B = elt.inverse(); - c.call(ftmPrefix + "_inverse", elt, B), - - // const alt_bn128_Fq12 C = A * B; - c.call(ftmPrefix + "_mul", A, B, C), - // const alt_bn128_Fq12 D = C.Frobenius_map(2); - c.call(prefix + "__frobeniusMap2", C, D), - // const alt_bn128_Fq12 result = D * C; - c.call(ftmPrefix + "_mul", C, D, r), - ); - } - - function buildCyclotomicSquare() { - const f = module.addFunction(prefix+ "__cyclotomicSquare"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x4 = c.i32_add(c.getLocal("x"), c.i32_const(f2size)); - const x3 = c.i32_add(c.getLocal("x"), c.i32_const(2*f2size)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(3*f2size)); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(4*f2size)); - const x5 = c.i32_add(c.getLocal("x"), c.i32_const(5*f2size)); - - const r0 = c.getLocal("r"); - const r4 = c.i32_add(c.getLocal("r"), c.i32_const(f2size)); - const r3 = c.i32_add(c.getLocal("r"), c.i32_const(2*f2size)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(3*f2size)); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(4*f2size)); - const r5 = c.i32_add(c.getLocal("r"), c.i32_const(5*f2size)); - - const t0 = c.i32_const(module.alloc(f2size)); - const t1 = c.i32_const(module.alloc(f2size)); - const t2 = c.i32_const(module.alloc(f2size)); - const t3 = c.i32_const(module.alloc(f2size)); - const t4 = c.i32_const(module.alloc(f2size)); - const t5 = c.i32_const(module.alloc(f2size)); - const tmp = c.i32_const(module.alloc(f2size)); - const AUX = c.i32_const(module.alloc(f2size)); - - - f.addCode( - -// c.call(ftmPrefix + "_square", x0, r0), - - // // t0 + t1*y = (z0 + z1*y)^2 = a^2 - // tmp = z0 * z1; - // t0 = (z0 + z1) * (z0 + my_Fp6::non_residue * z1) - tmp - my_Fp6::non_residue * tmp; - // t1 = tmp + tmp; - c.call(f2mPrefix + "_mul", x0, x1, tmp), - c.call(f2mPrefix + "_mul", x1, c.i32_const(pNonResidueF6), t0), - c.call(f2mPrefix + "_add", x0, t0, t0), - c.call(f2mPrefix + "_add", x0, x1, AUX), - c.call(f2mPrefix + "_mul", AUX, t0, t0), - c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), - c.call(f2mPrefix + "_add", tmp, AUX, AUX), - c.call(f2mPrefix + "_sub", t0, AUX, t0), - c.call(f2mPrefix + "_add", tmp, tmp, t1), - - // // t2 + t3*y = (z2 + z3*y)^2 = b^2 - // tmp = z2 * z3; - // t2 = (z2 + z3) * (z2 + my_Fp6::non_residue * z3) - tmp - my_Fp6::non_residue * tmp; - // t3 = tmp + tmp; - c.call(f2mPrefix + "_mul", x2, x3, tmp), - c.call(f2mPrefix + "_mul", x3, c.i32_const(pNonResidueF6), t2), - c.call(f2mPrefix + "_add", x2, t2, t2), - c.call(f2mPrefix + "_add", x2, x3, AUX), - c.call(f2mPrefix + "_mul", AUX, t2, t2), - c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), - c.call(f2mPrefix + "_add", tmp, AUX, AUX), - c.call(f2mPrefix + "_sub", t2, AUX, t2), - c.call(f2mPrefix + "_add", tmp, tmp, t3), - - // // t4 + t5*y = (z4 + z5*y)^2 = c^2 - // tmp = z4 * z5; - // t4 = (z4 + z5) * (z4 + my_Fp6::non_residue * z5) - tmp - my_Fp6::non_residue * tmp; - // t5 = tmp + tmp; - c.call(f2mPrefix + "_mul", x4, x5, tmp), - c.call(f2mPrefix + "_mul", x5, c.i32_const(pNonResidueF6), t4), - c.call(f2mPrefix + "_add", x4, t4, t4), - c.call(f2mPrefix + "_add", x4, x5, AUX), - c.call(f2mPrefix + "_mul", AUX, t4, t4), - c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), - c.call(f2mPrefix + "_add", tmp, AUX, AUX), - c.call(f2mPrefix + "_sub", t4, AUX, t4), - c.call(f2mPrefix + "_add", tmp, tmp, t5), - - // For A - // z0 = 3 * t0 - 2 * z0 - c.call(f2mPrefix + "_sub", t0, x0, r0), - c.call(f2mPrefix + "_add", r0, r0, r0), - c.call(f2mPrefix + "_add", t0, r0, r0), - // z1 = 3 * t1 + 2 * z1 - c.call(f2mPrefix + "_add", t1, x1, r1), - c.call(f2mPrefix + "_add", r1, r1, r1), - c.call(f2mPrefix + "_add", t1, r1, r1), - - // For B - // z2 = 3 * (xi * t5) + 2 * z2 - c.call(f2mPrefix + "_mul", t5, c.i32_const(pAltBn128Twist), AUX), - c.call(f2mPrefix + "_add", AUX, x2, r2), - c.call(f2mPrefix + "_add", r2, r2, r2), - c.call(f2mPrefix + "_add", AUX, r2, r2), - // z3 = 3 * t4 - 2 * z3 - c.call(f2mPrefix + "_sub", t4, x3, r3), - c.call(f2mPrefix + "_add", r3, r3, r3), - c.call(f2mPrefix + "_add", t4, r3, r3), - - // For C - // z4 = 3 * t2 - 2 * z4 - c.call(f2mPrefix + "_sub", t2, x4, r4), - c.call(f2mPrefix + "_add", r4, r4, r4), - c.call(f2mPrefix + "_add", t2, r4, r4), - // z5 = 3 * t3 + 2 * z5 - c.call(f2mPrefix + "_add", t3, x5, r5), - c.call(f2mPrefix + "_add", r5, r5, r5), - c.call(f2mPrefix + "_add", t3, r5, r5), - - ); - } - - - function buildCyclotomicExp(exponent, fnName) { - const exponentNafBytes = naf(exponent).map( (b) => (b==-1 ? 0xFF: b) ); - const pExponentNafBytes = module.alloc(exponentNafBytes); - const pExponent = module.alloc(utils.bigInt2BytesLE(exponent, 32)); - - const f = module.addFunction(prefix+ "__cyclotomicExp_"+fnName); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - f.addLocal("bit", "i32"); - f.addLocal("i", "i32"); - - const c = f.getCodeBuilder(); - - const x = c.getLocal("x"); - - const res = c.getLocal("r"); - - const inverse = c.i32_const(module.alloc(ftsize)); - - - f.addCode( -// c.call(ftmPrefix + "_exp", x, c.i32_const(pExponent), c.i32_const(32), res), - - c.call(ftmPrefix + "_conjugate", x, inverse), - c.call(ftmPrefix + "_one", res), - - c.if( - c.teeLocal("bit", c.i32_load8_s(c.i32_const(exponentNafBytes.length-1), pExponentNafBytes)), - c.if( - c.i32_eq( - c.getLocal("bit"), - c.i32_const(1) - ), - c.call(ftmPrefix + "_mul", res, x, res), - c.call(ftmPrefix + "_mul", res, inverse, res), - ) - ), - - c.setLocal("i", c.i32_const(exponentNafBytes.length-2)), - c.block(c.loop( -// c.call(ftmPrefix + "_square", res, res), - c.call(prefix + "__cyclotomicSquare", res, res), - c.if( - c.teeLocal("bit", c.i32_load8_s(c.getLocal("i"), pExponentNafBytes)), - c.if( - c.i32_eq( - c.getLocal("bit"), - c.i32_const(1) - ), - c.call(ftmPrefix + "_mul", res, x, res), - c.call(ftmPrefix + "_mul", res, inverse, res), - ) - ), - c.br_if(1, c.i32_eqz ( c.getLocal("i") )), - c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - ); - } - - - - function buildFinalExponentiationLastChunk() { - buildCyclotomicSquare(); - buildCyclotomicExp(finalExpZ, "w0"); - - const f = module.addFunction(prefix+ "__finalExponentiationLastChunk"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const elt = c.getLocal("x"); - const result = c.getLocal("r"); - const A = c.i32_const(module.alloc(ftsize)); - const B = c.i32_const(module.alloc(ftsize)); - const C = c.i32_const(module.alloc(ftsize)); - const D = c.i32_const(module.alloc(ftsize)); - const E = c.i32_const(module.alloc(ftsize)); - const F = c.i32_const(module.alloc(ftsize)); - const G = c.i32_const(module.alloc(ftsize)); - const H = c.i32_const(module.alloc(ftsize)); - const I = c.i32_const(module.alloc(ftsize)); - const J = c.i32_const(module.alloc(ftsize)); - const K = c.i32_const(module.alloc(ftsize)); - const L = c.i32_const(module.alloc(ftsize)); - const M = c.i32_const(module.alloc(ftsize)); - const N = c.i32_const(module.alloc(ftsize)); - const O = c.i32_const(module.alloc(ftsize)); - const P = c.i32_const(module.alloc(ftsize)); - const Q = c.i32_const(module.alloc(ftsize)); - const R = c.i32_const(module.alloc(ftsize)); - const S = c.i32_const(module.alloc(ftsize)); - const T = c.i32_const(module.alloc(ftsize)); - const U = c.i32_const(module.alloc(ftsize)); - - f.addCode( - - - // A = exp_by_neg_z(elt) // = elt^(-z) - c.call(prefix + "__cyclotomicExp_w0", elt, A), - finalExpIsNegative ? [] : c.call(ftmPrefix + "_conjugate", A, A), - // B = A^2 // = elt^(-2*z) - c.call(prefix + "__cyclotomicSquare", A, B), - // C = B^2 // = elt^(-4*z) - c.call(prefix + "__cyclotomicSquare", B, C), - // D = C * B // = elt^(-6*z) - c.call(ftmPrefix + "_mul", C, B, D), - // E = exp_by_neg_z(D) // = elt^(6*z^2) - c.call(prefix + "__cyclotomicExp_w0", D, E), - finalExpIsNegative ? [] : c.call(ftmPrefix + "_conjugate", E, E), - // F = E^2 // = elt^(12*z^2) - c.call(prefix + "__cyclotomicSquare", E, F), - // G = epx_by_neg_z(F) // = elt^(-12*z^3) - c.call(prefix + "__cyclotomicExp_w0", F, G), - finalExpIsNegative ? [] : c.call(ftmPrefix + "_conjugate", G, G), - // H = conj(D) // = elt^(6*z) - c.call(ftmPrefix + "_conjugate", D, H), - // I = conj(G) // = elt^(12*z^3) - c.call(ftmPrefix + "_conjugate", G, I), - // J = I * E // = elt^(12*z^3 + 6*z^2) - c.call(ftmPrefix + "_mul", I, E, J), - // K = J * H // = elt^(12*z^3 + 6*z^2 + 6*z) - c.call(ftmPrefix + "_mul", J, H, K), - // L = K * B // = elt^(12*z^3 + 6*z^2 + 4*z) - c.call(ftmPrefix + "_mul", K, B, L), - // M = K * E // = elt^(12*z^3 + 12*z^2 + 6*z) - c.call(ftmPrefix + "_mul", K, E, M), - - // N = M * elt // = elt^(12*z^3 + 12*z^2 + 6*z + 1) - c.call(ftmPrefix + "_mul", M, elt, N), - - // O = L.Frobenius_map(1) // = elt^(q*(12*z^3 + 6*z^2 + 4*z)) - c.call(prefix + "__frobeniusMap1", L, O), - // P = O * N // = elt^(q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) - c.call(ftmPrefix + "_mul", O, N, P), - // Q = K.Frobenius_map(2) // = elt^(q^2 * (12*z^3 + 6*z^2 + 6*z)) - c.call(prefix + "__frobeniusMap2", K, Q), - // R = Q * P // = elt^(q^2 * (12*z^3 + 6*z^2 + 6*z) + q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) - c.call(ftmPrefix + "_mul", Q, P, R), - // S = conj(elt) // = elt^(-1) - c.call(ftmPrefix + "_conjugate", elt, S), - // T = S * L // = elt^(12*z^3 + 6*z^2 + 4*z - 1) - c.call(ftmPrefix + "_mul", S, L, T), - // U = T.Frobenius_map(3) // = elt^(q^3(12*z^3 + 6*z^2 + 4*z - 1)) - c.call(prefix + "__frobeniusMap3", T, U), - // V = U * R // = elt^(q^3(12*z^3 + 6*z^2 + 4*z - 1) + q^2 * (12*z^3 + 6*z^2 + 6*z) + q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) - c.call(ftmPrefix + "_mul", U, R, result), - // result = V - ); - } - - - function buildFinalExponentiation() { - buildFinalExponentiationFirstChunk(); - buildFinalExponentiationLastChunk(); - const f = module.addFunction(prefix+ "_finalExponentiation"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const elt = c.getLocal("x"); - const result = c.getLocal("r"); - const eltToFirstChunk = c.i32_const(module.alloc(ftsize)); - - f.addCode( - c.call(prefix + "__finalExponentiationFirstChunk", elt, eltToFirstChunk ), - c.call(prefix + "__finalExponentiationLastChunk", eltToFirstChunk, result ) - ); - } - - - function buildFinalExponentiationOld() { - const f = module.addFunction(prefix+ "_finalExponentiationOld"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const exponent = bigInt("552484233613224096312617126783173147097382103762957654188882734314196910839907541213974502761540629817009608548654680343627701153829446747810907373256841551006201639677726139946029199968412598804882391702273019083653272047566316584365559776493027495458238373902875937659943504873220554161550525926302303331747463515644711876653177129578303191095900909191624817826566688241804408081892785725967931714097716709526092261278071952560171111444072049229123565057483750161460024353346284167282452756217662335528813519139808291170539072125381230815729071544861602750936964829313608137325426383735122175229541155376346436093930287402089517426973178917569713384748081827255472576937471496195752727188261435633271238710131736096299798168852925540549342330775279877006784354801422249722573783561685179618816480037695005515426162362431072245638324744480"); - - const pExponent = module.alloc(utils.bigInt2BytesLE( exponent, 352 )); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call(ftmPrefix + "_exp", c.getLocal("x"), c.i32_const(pExponent), c.i32_const(352), c.getLocal("r")), - ); - } - - - - - const pPreP = module.alloc(prePSize); - const pPreQ = module.alloc(preQSize); - - function buildPairingEquation(nPairings) { - - const f = module.addFunction(prefix+ "_pairingEq"+nPairings); - for (let i=0; i { - - - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -module.exports = function buildApplyKey(module, fnName, gPrefix, frPrefix, sizeGIn, sizeGOut, sizeF, opGtimesF) { +var build_timesscalar = function buildTimesScalar(module, fnName, elementLen, opAB, opAA, opCopy, opInit) { const f = module.addFunction(fnName); - f.addParam("pIn", "i32"); - f.addParam("n", "i32"); - f.addParam("pFirst", "i32"); - f.addParam("pInc", "i32"); - f.addParam("pOut", "i32"); - f.addLocal("pOldFree", "i32"); + f.addParam("base", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLength", "i32"); + f.addParam("r", "i32"); f.addLocal("i", "i32"); - f.addLocal("pFrom", "i32"); - f.addLocal("pTo", "i32"); + f.addLocal("b", "i32"); const c = f.getCodeBuilder(); - const t = c.i32_const(module.alloc(sizeF)); + const aux = c.i32_const(module.alloc(elementLen)); f.addCode( - c.setLocal("pFrom", c.getLocal("pIn")), - c.setLocal("pTo", c.getLocal("pOut")), - ); - - // t = first - f.addCode( - c.call( - frPrefix + "_copy", - c.getLocal("pFirst"), - t + c.if( + c.i32_eqz(c.getLocal("scalarLength")), + [ + ...c.call(opInit, c.getLocal("r")), + ...c.ret([]) + ] ) ); - f.addCode( - c.setLocal("i", c.i32_const(0)), - c.block(c.loop( - c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), + f.addCode(c.call(opCopy, c.getLocal("base"), aux)); + f.addCode(c.call(opInit, c.getLocal("r"))); + f.addCode(c.setLocal("i", c.getLocal("scalarLength"))); + f.addCode(c.block(c.loop( + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - c.call( - opGtimesF, - c.getLocal("pFrom"), - t, - c.getLocal("pTo") - ), - c.setLocal("pFrom", c.i32_add(c.getLocal("pFrom"), c.i32_const(sizeGIn))), - c.setLocal("pTo", c.i32_add(c.getLocal("pTo"), c.i32_const(sizeGOut))), + c.setLocal( + "b", + c.i32_load8_u( + c.i32_add( + c.getLocal("scalar"), + c.getLocal("i") + ) + ) + ), + ...innerLoop(), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.br(0) + ))); - // t = t* inc - c.call( - frPrefix + "_mul", - t, - c.getLocal("pInc"), - t - ), - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - ); - module.exportFunction(fnName); + function innerLoop() { + const code = []; + for (let i=0; i<8; i++) { + code.push( + ...c.call(opAA, c.getLocal("r"), c.getLocal("r")), + ...c.if( + c.i32_ge_u( c.getLocal("b"), c.i32_const(0x80 >> i)), + [ + ...c.setLocal( + "b", + c.i32_sub( + c.getLocal("b"), + c.i32_const(0x80 >> i) + ) + ), + ...c.call(opAB, c.getLocal("r"),aux, c.getLocal("r")) + ] + ) + ); + } + return code; + } }; +var build_batchinverse = buildBatchInverse$3; -/***/ }), - -/***/ 9440: -/***/ ((module) => { - - - -module.exports = buildBatchConvertion; - -function buildBatchConvertion(module, fnName, internalFnName, sizeIn, sizeOut, reverse) { - if (typeof reverse === "undefined") { - // Set the reverse in a way that allows to use the same buffer as in/out. - if (sizeIn < sizeOut) { - reverse = true; - } else { - reverse = false; - } - } - - const f = module.addFunction(fnName); - f.addParam("pIn", "i32"); - f.addParam("n", "i32"); - f.addParam("pOut", "i32"); - f.addLocal("i", "i32"); - f.addLocal("itIn", "i32"); - f.addLocal("itOut", "i32"); - - const c = f.getCodeBuilder(); - - if (reverse) { - f.addCode( - c.setLocal("itIn", - c.i32_add( - c.getLocal("pIn"), - c.i32_mul( - c.i32_sub( - c.getLocal("n"), - c.i32_const(1) - ), - c.i32_const(sizeIn) - ) - ) - ), - c.setLocal("itOut", - c.i32_add( - c.getLocal("pOut"), - c.i32_mul( - c.i32_sub( - c.getLocal("n"), - c.i32_const(1) - ), - c.i32_const(sizeOut) - ) - ) - ), - c.setLocal("i", c.i32_const(0)), - c.block(c.loop( - c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), - - c.call(internalFnName, c.getLocal("itIn"), c.getLocal("itOut")), - - c.setLocal("itIn", c.i32_sub(c.getLocal("itIn"), c.i32_const(sizeIn))), - c.setLocal("itOut", c.i32_sub(c.getLocal("itOut"), c.i32_const(sizeOut))), - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )), - ); - } else { - f.addCode( - c.setLocal("itIn", c.getLocal("pIn")), - c.setLocal("itOut", c.getLocal("pOut")), - c.setLocal("i", c.i32_const(0)), - c.block(c.loop( - c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), - - c.call(internalFnName, c.getLocal("itIn"), c.getLocal("itOut")), - - c.setLocal("itIn", c.i32_add(c.getLocal("itIn"), c.i32_const(sizeIn))), - c.setLocal("itOut", c.i32_add(c.getLocal("itOut"), c.i32_const(sizeOut))), - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )), - ); - } -} - - -/***/ }), - -/***/ 18163: -/***/ ((module) => { - - -module.exports = buildBatchInverse; - -function buildBatchInverse(module, prefix) { +function buildBatchInverse$3(module, prefix) { const n8 = module.modules[prefix].n64*8; @@ -115007,17 +114602,88 @@ function buildBatchInverse(module, prefix) { } +var build_batchconvertion = buildBatchConvertion$3; -/***/ }), +function buildBatchConvertion$3(module, fnName, internalFnName, sizeIn, sizeOut, reverse) { + if (typeof reverse === "undefined") { + // Set the reverse in a way that allows to use the same buffer as in/out. + if (sizeIn < sizeOut) { + reverse = true; + } else { + reverse = false; + } + } -/***/ 4948: -/***/ ((module) => { + const f = module.addFunction(fnName); + f.addParam("pIn", "i32"); + f.addParam("n", "i32"); + f.addParam("pOut", "i32"); + f.addLocal("i", "i32"); + f.addLocal("itIn", "i32"); + f.addLocal("itOut", "i32"); + const c = f.getCodeBuilder(); + if (reverse) { + f.addCode( + c.setLocal("itIn", + c.i32_add( + c.getLocal("pIn"), + c.i32_mul( + c.i32_sub( + c.getLocal("n"), + c.i32_const(1) + ), + c.i32_const(sizeIn) + ) + ) + ), + c.setLocal("itOut", + c.i32_add( + c.getLocal("pOut"), + c.i32_mul( + c.i32_sub( + c.getLocal("n"), + c.i32_const(1) + ), + c.i32_const(sizeOut) + ) + ) + ), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), -module.exports = buildBatchConvertion; + c.call(internalFnName, c.getLocal("itIn"), c.getLocal("itOut")), -function buildBatchConvertion(module, fnName, internalFnName, sizeIn, sizeOut, reverse) { + c.setLocal("itIn", c.i32_sub(c.getLocal("itIn"), c.i32_const(sizeIn))), + c.setLocal("itOut", c.i32_sub(c.getLocal("itOut"), c.i32_const(sizeOut))), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + ); + } else { + f.addCode( + c.setLocal("itIn", c.getLocal("pIn")), + c.setLocal("itOut", c.getLocal("pOut")), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), + + c.call(internalFnName, c.getLocal("itIn"), c.getLocal("itOut")), + + c.setLocal("itIn", c.i32_add(c.getLocal("itIn"), c.i32_const(sizeIn))), + c.setLocal("itOut", c.i32_add(c.getLocal("itOut"), c.i32_const(sizeOut))), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + ); + } +} + +var build_batchop = buildBatchConvertion$2; + +function buildBatchConvertion$2(module, fnName, internalFnName, sizeIn, sizeOut, reverse) { if (typeof reverse === "undefined") { // Set the reverse in a way that allows to use the same buffer as in/out. if (sizeIn < sizeOut) { @@ -115111,11 +114777,162 @@ function buildBatchConvertion(module, fnName, internalFnName, sizeIn, sizeOut, r } } +var bigint = {}; -/***/ }), +// Many of these utilities are from the `big-integer` library, +// but adjusted to only work with native BigInt type +// Ref https://github.com/peterolson/BigInteger.js/blob/e5d2154d3c417069c51e7116bafc3b91d0b9fe41/BigInteger.js +// Originally licensed The Unlicense -/***/ 15904: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +function compare(a, b) { + return a === b ? 0 : a > b ? 1 : -1; +} + +function square$1(n) { + return n * n; +} + +function isOdd$4(n) { + return n % 2n !== 0n; +} + +function isEven(n) { + return n % 2n === 0n; +} + +function isNegative$3(n) { + return n < 0n; +} + +function isPositive(n) { + return n > 0n; +} + +function bitLength$5(n) { + if (isNegative$3(n)) { + return n.toString(2).length - 1; // discard the - sign + } else { + return n.toString(2).length; + } +} + +function abs(n) { + return n < 0n ? -n : n; +} + +function isUnit(n) { + return abs(n) === 1n; +} + +function modInv$3(a, n) { + var t = 0n, newT = 1n, r = n, newR = abs(a), q, lastT, lastR; + while (newR !== 0n) { + q = r / newR; + lastT = t; + lastR = r; + t = newT; + r = newR; + newT = lastT - (q * newT); + newR = lastR - (q * newR); + } + if (!isUnit(r)) throw new Error(a.toString() + " and " + n.toString() + " are not co-prime"); + if (compare(t, 0n) === -1) { + t = t + n; + } + if (isNegative$3(a)) { + return -t; + } + return t; +} + +function modPow$2(n, exp, mod) { + if (mod === 0n) throw new Error("Cannot take modPow with modulus 0"); + var r = 1n, + base = n % mod; + if (isNegative$3(exp)) { + exp = exp * -1n; + base = modInv$3(base, mod); + } + while (isPositive(exp)) { + if (base === 0n) return 0n; + if (isOdd$4(exp)) r = r * base % mod; + exp = exp / 2n; + base = square$1(base) % mod; + } + return r; +} + +function compareAbs(a, b) { + a = a >= 0n ? a : -a; + b = b >= 0n ? b : -b; + return a === b ? 0 : a > b ? 1 : -1; +} + +function isDivisibleBy(a, n) { + if (n === 0n) return false; + if (isUnit(n)) return true; + if (compareAbs(n, 2n) === 0) return isEven(a); + return a % n === 0n; +} + +function isBasicPrime(v) { + var n = abs(v); + if (isUnit(n)) return false; + if (n === 2n || n === 3n || n === 5n) return true; + if (isEven(n) || isDivisibleBy(n, 3n) || isDivisibleBy(n, 5n)) return false; + if (n < 49n) return true; + // we don't know if it's prime: let the other functions figure it out +} + +function prev(n) { + return n - 1n; +} + +function millerRabinTest(n, a) { + var nPrev = prev(n), + b = nPrev, + r = 0, + d, i, x; + while (isEven(b)) b = b / 2n, r++; + next: for (i = 0; i < a.length; i++) { + if (n < a[i]) continue; + x = modPow$2(BigInt(a[i]), b, n); + if (isUnit(x) || x === nPrev) continue; + for (d = r - 1; d != 0; d--) { + x = square$1(x) % n; + if (isUnit(x)) return false; + if (x === nPrev) continue next; + } + return false; + } + return true; +} + +function isPrime$1(p) { + var isPrime = isBasicPrime(p); + if (isPrime !== undefined) return isPrime; + var n = abs(p); + var bits = bitLength$5(n); + if (bits <= 64) + return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]); + var logN = Math.log(2) * Number(bits); + var t = Math.ceil(logN); + for (var a = [], i = 0; i < t; i++) { + a.push(BigInt(i + 2)); + } + return millerRabinTest(n, a); +} + +bigint.bitLength = bitLength$5; +bigint.isOdd = isOdd$4; +bigint.isNegative = isNegative$3; +bigint.abs = abs; +bigint.isUnit = isUnit; +bigint.compare = compare; +bigint.modInv = modInv$3; +bigint.modPow = modPow$2; +bigint.isPrime = isPrime$1; +bigint.square = square$1; /* Copyright 2019 0KIMS association. @@ -115136,12 +114953,3098 @@ function buildBatchConvertion(module, fnName, internalFnName, sizeIn, sizeOut, r along with wasmsnark. If not, see . */ -const buildTimesScalarNAF = __webpack_require__(33972); -//const buildTimesScalar = require("./build_timesscalar"); -const buildBatchConvertion = __webpack_require__(9440); -const buildMultiexp = __webpack_require__(74911); +const buildInt = build_int; +const utils$5 = utils$6; +const buildExp$2 = build_timesscalar; +const buildBatchInverse$2 = build_batchinverse; +const buildBatchConvertion$1 = build_batchconvertion; +const buildBatchOp = build_batchop; +const { bitLength: bitLength$4, modInv: modInv$2, modPow: modPow$1, isPrime, isOdd: isOdd$3, square } = bigint; -module.exports = function buildCurve(module, prefix, prefixField, pB) { +var build_f1m = function buildF1m(module, _q, _prefix, _intPrefix) { + const q = BigInt(_q); + const n64 = Math.floor((bitLength$4(q - 1n) - 1)/64) +1; + const n32 = n64*2; + const n8 = n64*8; + + const prefix = _prefix || "f1m"; + if (module.modules[prefix]) return prefix; // already builded + + const intPrefix = buildInt(module, n64, _intPrefix); + const pq = module.alloc(n8, utils$5.bigInt2BytesLE(q, n8)); + + const pR2 = module.alloc(utils$5.bigInt2BytesLE(square(1n << BigInt(n64*64)) % q, n8)); + const pOne = module.alloc(utils$5.bigInt2BytesLE((1n << BigInt(n64*64)) % q, n8)); + const pZero = module.alloc(utils$5.bigInt2BytesLE(0n, n8)); + const _minusOne = q - 1n; + const _e = _minusOne >> 1n; // e = (p-1)/2 + const pe = module.alloc(n8, utils$5.bigInt2BytesLE(_e, n8)); + + const _ePlusOne = _e + 1n; // e = (p-1)/2 + const pePlusOne = module.alloc(n8, utils$5.bigInt2BytesLE(_ePlusOne, n8)); + + module.modules[prefix] = { + pq: pq, + pR2: pR2, + n64: n64, + q: q, + pOne: pOne, + pZero: pZero, + pePlusOne: pePlusOne + }; + + function buildOne() { + const f = module.addFunction(prefix+"_one"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call(intPrefix + "_copy", c.i32_const(pOne), c.getLocal("pr"))); + } + + function buildAdd() { + const f = module.addFunction(prefix+"_add"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.if( + c.call(intPrefix+"_add", c.getLocal("x"), c.getLocal("y"), c.getLocal("r")), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + c.if( + c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + ) + ) + ); + } + + function buildSub() { + const f = module.addFunction(prefix+"_sub"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.if( + c.call(intPrefix+"_sub", c.getLocal("x"), c.getLocal("y"), c.getLocal("r")), + c.drop(c.call(intPrefix+"_add", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))) + ) + ); + } + + function buildNeg() { + const f = module.addFunction(prefix+"_neg"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(prefix + "_sub", c.i32_const(pZero), c.getLocal("x"), c.getLocal("r")) + ); + } + + + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.call(prefix + "_fromMontgomery", c.getLocal("x"), AUX), + c.call(intPrefix + "_gte", AUX, c.i32_const(pePlusOne) ) + ); + } + + function buildSign() { + const f = module.addFunction(prefix+"_sign"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.if ( + c.call(intPrefix + "_isZero", c.getLocal("x")), + c.ret(c.i32_const(0)) + ), + c.call(prefix + "_fromMontgomery", c.getLocal("x"), AUX), + c.if( + c.call(intPrefix + "_gte", AUX, c.i32_const(pePlusOne)), + c.ret(c.i32_const(-1)) + ), + c.ret(c.i32_const(1)) + ); + } + + + function buildMReduct() { + const carries = module.alloc(n32*n32*8); + + const f = module.addFunction(prefix+"_mReduct"); + f.addParam("t", "i32"); + f.addParam("r", "i32"); + f.addLocal("np32", "i64"); + f.addLocal("c", "i64"); + f.addLocal("m", "i64"); + + const c = f.getCodeBuilder(); + + const np32 = Number(0x100000000n - modInv$2(q, 0x100000000n)); + + f.addCode(c.setLocal("np32", c.i64_const(np32))); + + for (let i=0; i=n32) { + f.addCode( + c.i64_store32( + c.getLocal("r"), + (k-n32)*4, + c.getLocal(c0) + ) + ); + } + [c0, c1] = [c1, c0]; + f.addCode( + c.setLocal(c1, + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ) + ); + } + f.addCode( + c.i64_store32( + c.getLocal("r"), + n32*4-4, + c.getLocal(c0) + ) + ); + + f.addCode( + c.if( + c.i32_wrap_i64(c.getLocal(c1)), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + c.if( + c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + ) + ) + ); + } + + + function buildSquare() { + + const f = module.addFunction(prefix+"_square"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + f.addLocal("c0", "i64"); + f.addLocal("c1", "i64"); + f.addLocal("c0_old", "i64"); + f.addLocal("c1_old", "i64"); + f.addLocal("np32", "i64"); + + + for (let i=0;i>1) )&&(i>1, k>>1) + ) + ) + ); + + f.addCode( + c.setLocal(c1, + c.i64_add( + c.getLocal(c1), + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ) + ) + ); + } + + // Add the old carry + + if (k>0) { + f.addCode( + c.setLocal(c0, + c.i64_add( + c.i64_and( + c.getLocal(c0), + c.i64_const(0xFFFFFFFF) + ), + c.i64_and( + c.getLocal(c0_old), + c.i64_const(0xFFFFFFFF) + ), + ) + ) + ); + + f.addCode( + c.setLocal(c1, + c.i64_add( + c.i64_add( + c.getLocal(c1), + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ), + c.getLocal(c1_old) + ) + ) + ); + } + + + for (let i=Math.max(1, k-n32+1); (i<=k)&&(i=n32) { + f.addCode( + c.i64_store32( + c.getLocal("r"), + (k-n32)*4, + c.getLocal(c0) + ) + ); + } + f.addCode( + c.setLocal( + c0_old, + c.getLocal(c1) + ), + c.setLocal( + c1_old, + c.i64_shr_u( + c.getLocal(c0_old), + c.i64_const(32) + ) + ) + ); + } + f.addCode( + c.i64_store32( + c.getLocal("r"), + n32*4-4, + c.getLocal(c0_old) + ) + ); + + f.addCode( + c.if( + c.i32_wrap_i64(c.getLocal(c1_old)), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + c.if( + c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + ) + ) + ); + } + + + function buildSquareOld() { + const f = module.addFunction(prefix+"_squareOld"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); + } + + function buildToMontgomery() { + const f = module.addFunction(prefix+"_toMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(prefix+"_mul", c.getLocal("x"), c.i32_const(pR2), c.getLocal("r"))); + } + + function buildFromMontgomery() { + + const pAux2 = module.alloc(n8*2); + + const f = module.addFunction(prefix+"_fromMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(intPrefix + "_copy", c.getLocal("x"), c.i32_const(pAux2) )); + f.addCode(c.call(intPrefix + "_zero", c.i32_const(pAux2 + n8) )); + f.addCode(c.call(prefix+"_mReduct", c.i32_const(pAux2), c.getLocal("r"))); + } + + function buildInverse() { + + const f = module.addFunction(prefix+ "_inverse"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(prefix + "_fromMontgomery", c.getLocal("x"), c.getLocal("r"))); + f.addCode(c.call(intPrefix + "_inverseMod", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))); + f.addCode(c.call(prefix + "_toMontgomery", c.getLocal("r"), c.getLocal("r"))); + } + + // Calculate various valuse needed for sqrt + + + let _nqr = 2n; + if (isPrime(q)) { + while (modPow$1(_nqr, _e, q) !== _minusOne) _nqr = _nqr + 1n; + } + + let s2 = 0; + let _t = _minusOne; + + while ((!isOdd$3(_t))&&(_t !== 0n)) { + s2++; + _t = _t >> 1n; + } + const pt = module.alloc(n8, utils$5.bigInt2BytesLE(_t, n8)); + + const _nqrToT = modPow$1(_nqr, _t, q); + const pNqrToT = module.alloc(utils$5.bigInt2BytesLE((_nqrToT << BigInt(n64*64)) % q, n8)); + + const _tPlusOneOver2 = (_t + 1n) >> 1n; + const ptPlusOneOver2 = module.alloc(n8, utils$5.bigInt2BytesLE(_tPlusOneOver2, n8)); + + function buildSqrt() { + + const f = module.addFunction(prefix+ "_sqrt"); + f.addParam("n", "i32"); + f.addParam("r", "i32"); + f.addLocal("m", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + + const c = f.getCodeBuilder(); + + const ONE = c.i32_const(pOne); + const C = c.i32_const(module.alloc(n8)); + const T = c.i32_const(module.alloc(n8)); + const R = c.i32_const(module.alloc(n8)); + const SQ = c.i32_const(module.alloc(n8)); + const B = c.i32_const(module.alloc(n8)); + + f.addCode( + + // If (n==0) return 0 + c.if( + c.call(prefix + "_isZero", c.getLocal("n")), + c.ret( + c.call(prefix + "_zero", c.getLocal("r")) + ) + ), + + c.setLocal("m", c.i32_const(s2)), + c.call(prefix + "_copy", c.i32_const(pNqrToT), C), + c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(pt), c.i32_const(n8), T), + c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(ptPlusOneOver2), c.i32_const(n8), R), + + c.block(c.loop( + c.br_if(1, c.call(prefix + "_eq", T, ONE)), + + c.call(prefix + "_square", T, SQ), + c.setLocal("i", c.i32_const(1)), + c.block(c.loop( + c.br_if(1, c.call(prefix + "_eq", SQ, ONE)), + c.call(prefix + "_square", SQ, SQ), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + + c.call(prefix + "_copy", C, B), + c.setLocal("j", c.i32_sub(c.i32_sub( c.getLocal("m"), c.getLocal("i")), c.i32_const(1)) ), + c.block(c.loop( + c.br_if(1, c.i32_eqz(c.getLocal("j"))), + c.call(prefix + "_square", B, B), + c.setLocal("j", c.i32_sub(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + + c.setLocal("m", c.getLocal("i")), + c.call(prefix + "_square", B, C), + c.call(prefix + "_mul", T, C, T), + c.call(prefix + "_mul", R, B, R), + + c.br(0) + )), + + c.if( + c.call(prefix + "_isNegative", R), + c.call(prefix + "_neg", R, c.getLocal("r")), + c.call(prefix + "_copy", R, c.getLocal("r")), + ) + ); + } + + function buildIsSquare() { + const f = module.addFunction(prefix+"_isSquare"); + f.addParam("n", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const ONE = c.i32_const(pOne); + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.if( + c.call(prefix + "_isZero", c.getLocal("n")), + c.ret(c.i32_const(1)) + ), + c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(pe), c.i32_const(n8), AUX), + c.call(prefix + "_eq", AUX, ONE) + ); + } + + + function buildLoad() { + const f = module.addFunction(prefix+"_load"); + f.addParam("scalar", "i32"); + f.addParam("scalarLen", "i32"); + f.addParam("r", "i32"); + f.addLocal("p", "i32"); + f.addLocal("l", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + const c = f.getCodeBuilder(); + + const R = c.i32_const(module.alloc(n8)); + const pAux = module.alloc(n8); + const AUX = c.i32_const(pAux); + + f.addCode( + c.call(intPrefix + "_zero", c.getLocal("r")), + c.setLocal("i", c.i32_const(n8)), + c.setLocal("p", c.getLocal("scalar")), + c.block(c.loop( + c.br_if(1, c.i32_gt_u(c.getLocal("i"), c.getLocal("scalarLen"))), + + c.if( + c.i32_eq(c.getLocal("i"), c.i32_const(n8)), + c.call(prefix + "_one", R), + c.call(prefix + "_mul", R, c.i32_const(pR2), R) + ), + c.call(prefix + "_mul", c.getLocal("p"), R, AUX), + c.call(prefix + "_add", c.getLocal("r"), AUX, c.getLocal("r")), + + c.setLocal("p", c.i32_add(c.getLocal("p"), c.i32_const(n8))), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(n8))), + c.br(0) + )), + + c.setLocal("l", c.i32_rem_u( c.getLocal("scalarLen"), c.i32_const(n8))), + c.if(c.i32_eqz(c.getLocal("l")), c.ret([])), + c.call(intPrefix + "_zero", AUX), + c.setLocal("j", c.i32_const(0)), + c.block(c.loop( + c.br_if(1, c.i32_eq(c.getLocal("j"), c.getLocal("l"))), + + c.i32_store8( + c.getLocal("j"), + pAux, + c.i32_load8_u(c.getLocal("p")), + ), + c.setLocal("p", c.i32_add(c.getLocal("p"), c.i32_const(1))), + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + + c.if( + c.i32_eq(c.getLocal("i"), c.i32_const(n8)), + c.call(prefix + "_one", R), + c.call(prefix + "_mul", R, c.i32_const(pR2), R) + ), + c.call(prefix + "_mul", AUX, R, AUX), + c.call(prefix + "_add", c.getLocal("r"), AUX, c.getLocal("r")), + ); + } + + function buildTimesScalar() { + const f = module.addFunction(prefix+"_timesScalar"); + f.addParam("x", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLen", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.call(prefix + "_load", c.getLocal("scalar"), c.getLocal("scalarLen"), AUX), + c.call(prefix + "_toMontgomery", AUX, AUX), + c.call(prefix + "_mul", c.getLocal("x"), AUX, c.getLocal("r")), + ); + } + + function buildIsOne() { + const f = module.addFunction(prefix+"_isOne"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + f.addCode( + c.ret(c.call(intPrefix + "_eq", c.getLocal("x"), c.i32_const(pOne))) + ); + } + + + module.exportFunction(intPrefix + "_copy", prefix+"_copy"); + module.exportFunction(intPrefix + "_zero", prefix+"_zero"); + module.exportFunction(intPrefix + "_isZero", prefix+"_isZero"); + module.exportFunction(intPrefix + "_eq", prefix+"_eq"); + + buildIsOne(); + buildAdd(); + buildSub(); + buildNeg(); + buildMReduct(); + buildMul(); + buildSquare(); + buildSquareOld(); + buildToMontgomery(); + buildFromMontgomery(); + buildIsNegative(); + buildSign(); + buildInverse(); + buildOne(); + buildLoad(); + buildTimesScalar(); + buildBatchInverse$2(module, prefix); + buildBatchConvertion$1(module, prefix + "_batchToMontgomery", prefix + "_toMontgomery", n8, n8); + buildBatchConvertion$1(module, prefix + "_batchFromMontgomery", prefix + "_fromMontgomery", n8, n8); + buildBatchConvertion$1(module, prefix + "_batchNeg", prefix + "_neg", n8, n8); + buildBatchOp(module, prefix + "_batchAdd", prefix + "_add", n8, n8); + buildBatchOp(module, prefix + "_batchSub", prefix + "_sub", n8, n8); + buildBatchOp(module, prefix + "_batchMul", prefix + "_mul", n8, n8); + + module.exportFunction(prefix + "_add"); + module.exportFunction(prefix + "_sub"); + module.exportFunction(prefix + "_neg"); + module.exportFunction(prefix + "_isNegative"); + module.exportFunction(prefix + "_isOne"); + module.exportFunction(prefix + "_sign"); + module.exportFunction(prefix + "_mReduct"); + module.exportFunction(prefix + "_mul"); + module.exportFunction(prefix + "_square"); + module.exportFunction(prefix + "_squareOld"); + module.exportFunction(prefix + "_fromMontgomery"); + module.exportFunction(prefix + "_toMontgomery"); + module.exportFunction(prefix + "_inverse"); + module.exportFunction(prefix + "_one"); + module.exportFunction(prefix + "_load"); + module.exportFunction(prefix + "_timesScalar"); + buildExp$2( + module, + prefix + "_exp", + n8, + prefix + "_mul", + prefix + "_square", + intPrefix + "_copy", + prefix + "_one", + ); + module.exportFunction(prefix + "_exp"); + module.exportFunction(prefix + "_batchInverse"); + if (isPrime(q)) { + buildSqrt(); + buildIsSquare(); + module.exportFunction(prefix + "_sqrt"); + module.exportFunction(prefix + "_isSquare"); + } + module.exportFunction(prefix + "_batchToMontgomery"); + module.exportFunction(prefix + "_batchFromMontgomery"); + // console.log(module.functionIdxByName); + + return prefix; +}; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const buildF1m$2 =build_f1m; +const { bitLength: bitLength$3 } = bigint; + +var build_f1 = function buildF1(module, _q, _prefix, _f1mPrefix, _intPrefix) { + + const q = BigInt(_q); + const n64 = Math.floor((bitLength$3(q - 1n) - 1)/64) +1; + const n8 = n64*8; + + const prefix = _prefix || "f1"; + if (module.modules[prefix]) return prefix; // already builded + module.modules[prefix] = { + n64: n64 + }; + + const intPrefix = _intPrefix || "int"; + const f1mPrefix = buildF1m$2(module, q, _f1mPrefix, intPrefix); + + + const pR2 = module.modules[f1mPrefix].pR2; + const pq = module.modules[f1mPrefix].pq; + const pePlusOne = module.modules[f1mPrefix].pePlusOne; + + function buildMul() { + const pAux1 = module.alloc(n8); + + const f = module.addFunction(prefix+ "_mul"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(f1mPrefix + "_mul", c.getLocal("x"), c.getLocal("y"), c.i32_const(pAux1))); + f.addCode(c.call(f1mPrefix + "_mul", c.i32_const(pAux1), c.i32_const(pR2), c.getLocal("r"))); + } + + function buildSquare() { + const f = module.addFunction(prefix+"_square"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); + } + + + function buildInverse() { + + const f = module.addFunction(prefix+ "_inverse"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(intPrefix + "_inverseMod", c.getLocal("x"), c.i32_const(pq), c.getLocal("r"))); + } + + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(intPrefix + "_gte", c.getLocal("x"), c.i32_const(pePlusOne) ) + ); + } + + + buildMul(); + buildSquare(); + buildInverse(); + buildIsNegative(); + module.exportFunction(f1mPrefix + "_add", prefix + "_add"); + module.exportFunction(f1mPrefix + "_sub", prefix + "_sub"); + module.exportFunction(f1mPrefix + "_neg", prefix + "_neg"); + module.exportFunction(prefix + "_mul"); + module.exportFunction(prefix + "_square"); + module.exportFunction(prefix + "_inverse"); + module.exportFunction(prefix + "_isNegative"); + module.exportFunction(f1mPrefix + "_copy", prefix+"_copy"); + module.exportFunction(f1mPrefix + "_zero", prefix+"_zero"); + module.exportFunction(f1mPrefix + "_one", prefix+"_one"); + module.exportFunction(f1mPrefix + "_isZero", prefix+"_isZero"); + module.exportFunction(f1mPrefix + "_eq", prefix+"_eq"); + + return prefix; +}; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const buildExp$1 = build_timesscalar; +const buildBatchInverse$1 = build_batchinverse; +const utils$4 = utils$6; + +var build_f2m = function buildF2m(module, mulNonResidueFn, prefix, f1mPrefix) { + + if (module.modules[prefix]) return prefix; // already builded + + const f1n8 = module.modules[f1mPrefix].n64*8; + const q = module.modules[f1mPrefix].q; + + module.modules[prefix] = { + n64: module.modules[f1mPrefix].n64*2 + }; + + function buildAdd() { + const f = module.addFunction(prefix+"_add"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_add", x0, y0, r0), + c.call(f1mPrefix+"_add", x1, y1, r1), + ); + } + + function buildTimesScalar() { + const f = module.addFunction(prefix+"_timesScalar"); + f.addParam("x", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLen", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_timesScalar", x0, c.getLocal("scalar"), c.getLocal("scalarLen"), r0), + c.call(f1mPrefix+"_timesScalar", x1, c.getLocal("scalar"), c.getLocal("scalarLen"), r1), + ); + } + + function buildSub() { + const f = module.addFunction(prefix+"_sub"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_sub", x0, y0, r0), + c.call(f1mPrefix+"_sub", x1, y1, r1), + ); + } + + function buildNeg() { + const f = module.addFunction(prefix+"_neg"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_neg", x0, r0), + c.call(f1mPrefix+"_neg", x1, r1), + ); + } + + function buildConjugate() { + const f = module.addFunction(prefix+"_conjugate"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_copy", x0, r0), + c.call(f1mPrefix+"_neg", x1, r1), + ); + } + + + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.if( + c.call(f1mPrefix+"_isZero", x1), + c.ret(c.call(f1mPrefix+"_isNegative", x0)) + ), + c.ret(c.call(f1mPrefix+"_isNegative", x1)) + ); + } + + function buildMul() { + const f = module.addFunction(prefix+"_mul"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + const A = c.i32_const(module.alloc(f1n8)); + const B = c.i32_const(module.alloc(f1n8)); + const C = c.i32_const(module.alloc(f1n8)); + const D = c.i32_const(module.alloc(f1n8)); + + + f.addCode( + c.call(f1mPrefix + "_mul", x0, y0, A), // A = x0*y0 + c.call(f1mPrefix + "_mul", x1, y1, B), // B = x1*y1 + + c.call(f1mPrefix + "_add", x0, x1, C), // C = x0 + x1 + c.call(f1mPrefix + "_add", y0, y1, D), // D = y0 + y1 + c.call(f1mPrefix + "_mul", C, D, C), // C = (x0 + x1)*(y0 + y1) = x0*y0+x0*y1+x1*y0+x1*y1 + + // c.call(f1mPrefix + "_mul", B, c.i32_const(pNonResidue), r0), // r0 = nr*(x1*y1) + c.call(mulNonResidueFn, B, r0), // r0 = nr*(x1*y1) + c.call(f1mPrefix + "_add", A, r0, r0), // r0 = x0*y0 + nr*(x1*y1) + c.call(f1mPrefix + "_add", A, B, r1), // r1 = x0*y0+x1*y1 + c.call(f1mPrefix + "_sub", C, r1, r1) // r1 = x0*y0+x0*y1+x1*y0+x1*y1 - x0*y0+x1*y1 = x0*y1+x1*y0 + ); + + } + + function buildMul1() { + const f = module.addFunction(prefix+"_mul1"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y = c.getLocal("y"); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + + f.addCode( + c.call(f1mPrefix + "_mul", x0, y, r0), // A = x0*y + c.call(f1mPrefix + "_mul", x1, y, r1), // B = x1*y + ); + } + + function buildSquare() { + const f = module.addFunction(prefix+"_square"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + const AB = c.i32_const(module.alloc(f1n8)); + const APB = c.i32_const(module.alloc(f1n8)); + const APNB = c.i32_const(module.alloc(f1n8)); + const ABPNAB = c.i32_const(module.alloc(f1n8)); + + + f.addCode( + // AB = x0*y1 + c.call(f1mPrefix + "_mul", x0, x1, AB), + + // APB = x0+y1 + c.call(f1mPrefix + "_add", x0, x1, APB), + + // APBN0 = x0 + nr*x1 + c.call(mulNonResidueFn, x1, APNB), + c.call(f1mPrefix + "_add", x0, APNB, APNB), + + // ABPNAB = ab + nr*ab + c.call(mulNonResidueFn, AB, ABPNAB), + c.call(f1mPrefix + "_add", ABPNAB, AB, ABPNAB), + + // r0 = APB * APNB - ABPNAB + c.call(f1mPrefix + "_mul", APB, APNB, r0), + c.call(f1mPrefix + "_sub", r0, ABPNAB, r0), + + // r1 = AB + AB + c.call(f1mPrefix + "_add", AB, AB, r1), + ); + + } + + + function buildToMontgomery() { + const f = module.addFunction(prefix+"_toMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_toMontgomery", x0, r0), + c.call(f1mPrefix+"_toMontgomery", x1, r1) + ); + } + + function buildFromMontgomery() { + const f = module.addFunction(prefix+"_fromMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_fromMontgomery", x0, r0), + c.call(f1mPrefix+"_fromMontgomery", x1, r1) + ); + } + + function buildCopy() { + const f = module.addFunction(prefix+"_copy"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_copy", x0, r0), + c.call(f1mPrefix+"_copy", x1, r1) + ); + } + + function buildZero() { + const f = module.addFunction(prefix+"_zero"); + f.addParam("x", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_zero", x0), + c.call(f1mPrefix+"_zero", x1) + ); + } + + function buildOne() { + const f = module.addFunction(prefix+"_one"); + f.addParam("x", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_one", x0), + c.call(f1mPrefix+"_zero", x1) + ); + } + + function buildEq() { + const f = module.addFunction(prefix+"_eq"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + + f.addCode( + c.i32_and( + c.call(f1mPrefix+"_eq", x0, y0), + c.call(f1mPrefix+"_eq", x1, y1) + ) + ); + } + + function buildIsZero() { + const f = module.addFunction(prefix+"_isZero"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.i32_and( + c.call(f1mPrefix+"_isZero", x0), + c.call(f1mPrefix+"_isZero", x1) + ) + ); + } + + function buildInverse() { + const f = module.addFunction(prefix+"_inverse"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + const t0 = c.i32_const(module.alloc(f1n8)); + const t1 = c.i32_const(module.alloc(f1n8)); + const t2 = c.i32_const(module.alloc(f1n8)); + const t3 = c.i32_const(module.alloc(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_square", x0, t0), + c.call(f1mPrefix+"_square", x1, t1), + // c.call(f1mPrefix+"_mul", t1, c.i32_const(pNonResidue), t2), + c.call(mulNonResidueFn, t1, t2), + + c.call(f1mPrefix+"_sub", t0, t2, t2), + c.call(f1mPrefix+"_inverse", t2, t3), + + c.call(f1mPrefix+"_mul", x0, t3, r0), + c.call(f1mPrefix+"_mul", x1, t3, r1), + c.call(f1mPrefix+"_neg", r1, r1), + ); + } + + + function buildSign() { + const f = module.addFunction(prefix+"_sign"); + f.addParam("x", "i32"); + f.addLocal("s", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.setLocal("s" , c.call( f1mPrefix + "_sign", x1)), + c.if( + c.getLocal("s"), + c.ret(c.getLocal("s")) + ), + c.ret(c.call( f1mPrefix + "_sign", x0)) + ); + } + + function buildIsOne() { + const f = module.addFunction(prefix+"_isOne"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.ret(c.i32_and( + c.call(f1mPrefix + "_isOne", x0), + c.call(f1mPrefix + "_isZero", x1), + )) + ); + } + + + // Check here: https://eprint.iacr.org/2012/685.pdf + // Alg 9adj + function buildSqrt() { + + const f = module.addFunction(prefix+"_sqrt"); + f.addParam("a", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + // BigInt can't take `undefined` so we use `|| 0` + const e34 = c.i32_const(module.alloc(utils$4.bigInt2BytesLE((BigInt(q || 0) - 3n) / 4n, f1n8 ))); + // BigInt can't take `undefined` so we use `|| 0` + const e12 = c.i32_const(module.alloc(utils$4.bigInt2BytesLE((BigInt(q || 0) - 1n) / 2n, f1n8 ))); + + const a = c.getLocal("a"); + const a1 = c.i32_const(module.alloc(f1n8*2)); + const alpha = c.i32_const(module.alloc(f1n8*2)); + const a0 = c.i32_const(module.alloc(f1n8*2)); + const pn1 = module.alloc(f1n8*2); + const n1 = c.i32_const(pn1); + const n1a = c.i32_const(pn1); + const n1b = c.i32_const(pn1+f1n8); + const x0 = c.i32_const(module.alloc(f1n8*2)); + const b = c.i32_const(module.alloc(f1n8*2)); + + f.addCode( + + c.call(prefix + "_one", n1), + c.call(prefix + "_neg", n1, n1), + + // const a1 = F.pow(a, F.sqrt_e34); + c.call(prefix + "_exp", a, e34, c.i32_const(f1n8), a1), + + // const a1 = F.pow(a, F.sqrt_e34); + c.call(prefix + "_square", a1, alpha), + c.call(prefix + "_mul", a, alpha, alpha), + + // const a0 = F.mul(F.frobenius(1, alfa), alfa); + c.call(prefix + "_conjugate", alpha, a0), + c.call(prefix + "_mul", a0, alpha, a0), + + // if (F.eq(a0, F.negone)) return null; + c.if(c.call(prefix + "_eq",a0,n1), c.unreachable() ), + + // const x0 = F.mul(a1, a); + c.call(prefix + "_mul", a1, a, x0), + + // if (F.eq(alfa, F.negone)) { + c.if( + c.call(prefix + "_eq", alpha, n1), + [ + // x = F.mul(x0, [F.F.zero, F.F.one]); + ...c.call(f1mPrefix + "_zero", n1a), + ...c.call(f1mPrefix + "_one", n1b), + ...c.call(prefix + "_mul", n1, x0, c.getLocal("pr")), + ], + [ + // const b = F.pow(F.add(F.one, alfa), F.sqrt_e12); + ...c.call(prefix + "_one", b), + ...c.call(prefix + "_add", b, alpha, b), + ...c.call(prefix + "_exp", b, e12, c.i32_const(f1n8), b), + + // x = F.mul(b, x0); + ...c.call(prefix + "_mul", b, x0, c.getLocal("pr")), + ] + ) + ); + + } + + + function buildIsSquare() { + + const f = module.addFunction(prefix+"_isSquare"); + f.addParam("a", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + // BigInt can't take `undefined` so we use `|| 0` + const e34 = c.i32_const(module.alloc(utils$4.bigInt2BytesLE((BigInt(q || 0) - 3n) / 4n, f1n8 ))); + + const a = c.getLocal("a"); + const a1 = c.i32_const(module.alloc(f1n8*2)); + const alpha = c.i32_const(module.alloc(f1n8*2)); + const a0 = c.i32_const(module.alloc(f1n8*2)); + const pn1 = module.alloc(f1n8*2); + const n1 = c.i32_const(pn1); + + f.addCode( + + c.call(prefix + "_one", n1), + c.call(prefix + "_neg", n1, n1), + + // const a1 = F.pow(a, F.sqrt_e34); + c.call(prefix + "_exp", a, e34, c.i32_const(f1n8), a1), + + // const a1 = F.pow(a, F.sqrt_e34); + c.call(prefix + "_square", a1, alpha), + c.call(prefix + "_mul", a, alpha, alpha), + + // const a0 = F.mul(F.frobenius(1, alfa), alfa); + c.call(prefix + "_conjugate", alpha, a0), + c.call(prefix + "_mul", a0, alpha, a0), + + // if (F.eq(a0, F.negone)) return null; + c.if( + c.call( + prefix + "_eq", + a0, + n1 + ), + c.ret(c.i32_const(0)) + ), + c.ret(c.i32_const(1)) + ); + + } + + + buildIsZero(); + buildIsOne(); + buildZero(); + buildOne(); + buildCopy(); + buildMul(); + buildMul1(); + buildSquare(); + buildAdd(); + buildSub(); + buildNeg(); + buildConjugate(); + buildToMontgomery(); + buildFromMontgomery(); + buildEq(); + buildInverse(); + buildTimesScalar(); + buildSign(); + buildIsNegative(); + + module.exportFunction(prefix + "_isZero"); + module.exportFunction(prefix + "_isOne"); + module.exportFunction(prefix + "_zero"); + module.exportFunction(prefix + "_one"); + module.exportFunction(prefix + "_copy"); + module.exportFunction(prefix + "_mul"); + module.exportFunction(prefix + "_mul1"); + module.exportFunction(prefix + "_square"); + module.exportFunction(prefix + "_add"); + module.exportFunction(prefix + "_sub"); + module.exportFunction(prefix + "_neg"); + module.exportFunction(prefix + "_sign"); + module.exportFunction(prefix + "_conjugate"); + module.exportFunction(prefix + "_fromMontgomery"); + module.exportFunction(prefix + "_toMontgomery"); + module.exportFunction(prefix + "_eq"); + module.exportFunction(prefix + "_inverse"); + buildBatchInverse$1(module, prefix); + buildExp$1( + module, + prefix + "_exp", + f1n8*2, + prefix + "_mul", + prefix + "_square", + prefix + "_copy", + prefix + "_one", + ); + buildSqrt(); + buildIsSquare(); + + module.exportFunction(prefix + "_exp"); + module.exportFunction(prefix + "_timesScalar"); + module.exportFunction(prefix + "_batchInverse"); + module.exportFunction(prefix + "_sqrt"); + module.exportFunction(prefix + "_isSquare"); + module.exportFunction(prefix + "_isNegative"); + + + return prefix; +}; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const buildExp = build_timesscalar; +const buildBatchInverse = build_batchinverse; + +var build_f3m = function buildF3m(module, mulNonResidueFn, prefix, f1mPrefix) { + + if (module.modules[prefix]) return prefix; // already builded + + const f1n8 = module.modules[f1mPrefix].n64*8; + module.modules[prefix] = { + n64: module.modules[f1mPrefix].n64*3 + }; + + function buildAdd() { + const f = module.addFunction(prefix+"_add"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_add", x0, y0, r0), + c.call(f1mPrefix+"_add", x1, y1, r1), + c.call(f1mPrefix+"_add", x2, y2, r2), + ); + } + + function buildTimesScalar() { + const f = module.addFunction(prefix+"_timesScalar"); + f.addParam("x", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLen", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_timesScalar", x0, c.getLocal("scalar"), c.getLocal("scalarLen"), r0), + c.call(f1mPrefix+"_timesScalar", x1, c.getLocal("scalar"), c.getLocal("scalarLen"), r1), + c.call(f1mPrefix+"_timesScalar", x2, c.getLocal("scalar"), c.getLocal("scalarLen"), r2), + ); + } + + + function buildSub() { + const f = module.addFunction(prefix+"_sub"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_sub", x0, y0, r0), + c.call(f1mPrefix+"_sub", x1, y1, r1), + c.call(f1mPrefix+"_sub", x2, y2, r2), + ); + } + + function buildNeg() { + const f = module.addFunction(prefix+"_neg"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_neg", x0, r0), + c.call(f1mPrefix+"_neg", x1, r1), + c.call(f1mPrefix+"_neg", x2, r2), + ); + } + + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.if( + c.call(f1mPrefix+"_isZero", x2), + c.if( + c.call(f1mPrefix+"_isZero", x1), + c.ret(c.call(f1mPrefix+"_isNegative", x0)), + c.ret(c.call(f1mPrefix+"_isNegative", x1)) + ) + ), + c.ret(c.call(f1mPrefix+"_isNegative", x2)) + ); + } + + + function buildMul() { + const f = module.addFunction(prefix+"_mul"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const cd = f.getCodeBuilder(); + + const a = cd.getLocal("x"); + const b = cd.i32_add(cd.getLocal("x"), cd.i32_const(f1n8)); + const c = cd.i32_add(cd.getLocal("x"), cd.i32_const(2*f1n8)); + const A = cd.getLocal("y"); + const B = cd.i32_add(cd.getLocal("y"), cd.i32_const(f1n8)); + const C = cd.i32_add(cd.getLocal("y"), cd.i32_const(2*f1n8)); + const r0 = cd.getLocal("r"); + const r1 = cd.i32_add(cd.getLocal("r"), cd.i32_const(f1n8)); + const r2 = cd.i32_add(cd.getLocal("r"), cd.i32_const(2*f1n8)); + + const aA = cd.i32_const(module.alloc(f1n8)); + const bB = cd.i32_const(module.alloc(f1n8)); + const cC = cd.i32_const(module.alloc(f1n8)); + const a_b = cd.i32_const(module.alloc(f1n8)); + const A_B = cd.i32_const(module.alloc(f1n8)); + const a_c = cd.i32_const(module.alloc(f1n8)); + const A_C = cd.i32_const(module.alloc(f1n8)); + const b_c = cd.i32_const(module.alloc(f1n8)); + const B_C = cd.i32_const(module.alloc(f1n8)); + const aA_bB = cd.i32_const(module.alloc(f1n8)); + const aA_cC = cd.i32_const(module.alloc(f1n8)); + const bB_cC = cd.i32_const(module.alloc(f1n8)); + const AUX = cd.i32_const(module.alloc(f1n8)); + + + f.addCode( + cd.call(f1mPrefix + "_mul", a, A, aA), + cd.call(f1mPrefix + "_mul", b, B, bB), + cd.call(f1mPrefix + "_mul", c, C, cC), + + cd.call(f1mPrefix + "_add", a, b, a_b), + cd.call(f1mPrefix + "_add", A, B, A_B), + cd.call(f1mPrefix + "_add", a, c, a_c), + cd.call(f1mPrefix + "_add", A, C, A_C), + cd.call(f1mPrefix + "_add", b, c, b_c), + cd.call(f1mPrefix + "_add", B, C, B_C), + + cd.call(f1mPrefix + "_add", aA, bB, aA_bB), + cd.call(f1mPrefix + "_add", aA, cC, aA_cC), + cd.call(f1mPrefix + "_add", bB, cC, bB_cC), + + cd.call(f1mPrefix + "_mul", b_c, B_C, r0), + cd.call(f1mPrefix + "_sub", r0, bB_cC, r0), + cd.call(mulNonResidueFn, r0, r0), + cd.call(f1mPrefix + "_add", aA, r0, r0), + + cd.call(f1mPrefix + "_mul", a_b, A_B, r1), + cd.call(f1mPrefix + "_sub", r1, aA_bB, r1), + cd.call(mulNonResidueFn, cC, AUX), + cd.call(f1mPrefix + "_add", r1, AUX, r1), + + cd.call(f1mPrefix + "_mul", a_c, A_C, r2), + cd.call(f1mPrefix + "_sub", r2, aA_cC, r2), + cd.call(f1mPrefix + "_add", r2, bB, r2), + ); + + } + + function buildSquare() { + const f = module.addFunction(prefix+"_square"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const A = c.getLocal("x"); + const B = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const C = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + const s0 = c.i32_const(module.alloc(f1n8)); + const ab = c.i32_const(module.alloc(f1n8)); + const s1 = c.i32_const(module.alloc(f1n8)); + const s2 = c.i32_const(module.alloc(f1n8)); + const bc = c.i32_const(module.alloc(f1n8)); + const s3 = c.i32_const(module.alloc(f1n8)); + const s4 = c.i32_const(module.alloc(f1n8)); + + + f.addCode( + + c.call(f1mPrefix + "_square", A, s0), + c.call(f1mPrefix + "_mul", A, B, ab), + c.call(f1mPrefix + "_add", ab, ab, s1), + + c.call(f1mPrefix + "_sub", A, B, s2), + c.call(f1mPrefix + "_add", s2, C, s2), + c.call(f1mPrefix + "_square", s2, s2), + + c.call(f1mPrefix + "_mul", B, C, bc), + c.call(f1mPrefix + "_add", bc, bc, s3), + + c.call(f1mPrefix + "_square", C, s4), + + c.call(mulNonResidueFn, s3, r0), + c.call(f1mPrefix + "_add", s0, r0, r0), + + c.call(mulNonResidueFn, s4, r1), + c.call(f1mPrefix + "_add", s1, r1, r1), + + c.call(f1mPrefix + "_add", s0, s4, r2), + c.call(f1mPrefix + "_sub", s3, r2, r2), + c.call(f1mPrefix + "_add", s2, r2, r2), + c.call(f1mPrefix + "_add", s1, r2, r2), + ); + + } + + + function buildToMontgomery() { + const f = module.addFunction(prefix+"_toMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_toMontgomery", x0, r0), + c.call(f1mPrefix+"_toMontgomery", x1, r1), + c.call(f1mPrefix+"_toMontgomery", x2, r2) + ); + } + + function buildFromMontgomery() { + const f = module.addFunction(prefix+"_fromMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_fromMontgomery", x0, r0), + c.call(f1mPrefix+"_fromMontgomery", x1, r1), + c.call(f1mPrefix+"_fromMontgomery", x2, r2) + ); + } + + function buildCopy() { + const f = module.addFunction(prefix+"_copy"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_copy", x0, r0), + c.call(f1mPrefix+"_copy", x1, r1), + c.call(f1mPrefix+"_copy", x2, r2), + ); + } + + function buildZero() { + const f = module.addFunction(prefix+"_zero"); + f.addParam("x", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_zero", x0), + c.call(f1mPrefix+"_zero", x1), + c.call(f1mPrefix+"_zero", x2), + ); + } + + function buildOne() { + const f = module.addFunction(prefix+"_one"); + f.addParam("x", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_one", x0), + c.call(f1mPrefix+"_zero", x1), + c.call(f1mPrefix+"_zero", x2), + ); + } + + function buildEq() { + const f = module.addFunction(prefix+"_eq"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); + + f.addCode( + c.i32_and( + c.i32_and( + c.call(f1mPrefix+"_eq", x0, y0), + c.call(f1mPrefix+"_eq", x1, y1), + ), + c.call(f1mPrefix+"_eq", x2, y2) + ) + ); + } + + function buildIsZero() { + const f = module.addFunction(prefix+"_isZero"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.i32_and( + c.i32_and( + c.call(f1mPrefix+"_isZero", x0), + c.call(f1mPrefix+"_isZero", x1) + ), + c.call(f1mPrefix+"_isZero", x2) + ) + ); + } + + function buildInverse() { + const f = module.addFunction(prefix+"_inverse"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + const t0 = c.i32_const(module.alloc(f1n8)); + const t1 = c.i32_const(module.alloc(f1n8)); + const t2 = c.i32_const(module.alloc(f1n8)); + const t3 = c.i32_const(module.alloc(f1n8)); + const t4 = c.i32_const(module.alloc(f1n8)); + const t5 = c.i32_const(module.alloc(f1n8)); + const c0 = c.i32_const(module.alloc(f1n8)); + const c1 = c.i32_const(module.alloc(f1n8)); + const c2 = c.i32_const(module.alloc(f1n8)); + const t6 = c.i32_const(module.alloc(f1n8)); + const AUX = c.i32_const(module.alloc(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_square", x0, t0), + c.call(f1mPrefix+"_square", x1, t1), + c.call(f1mPrefix+"_square", x2, t2), + c.call(f1mPrefix+"_mul", x0, x1, t3), + c.call(f1mPrefix+"_mul", x0, x2, t4), + c.call(f1mPrefix+"_mul", x1, x2, t5), + + c.call(mulNonResidueFn, t5, c0), + c.call(f1mPrefix+"_sub", t0, c0, c0), + + c.call(mulNonResidueFn, t2, c1), + c.call(f1mPrefix+"_sub", c1, t3, c1), + + c.call(f1mPrefix+"_sub", t1, t4, c2), + + c.call(f1mPrefix+"_mul", x2, c1, t6), + c.call(f1mPrefix+"_mul", x1, c2, AUX), + c.call(f1mPrefix+"_add", t6, AUX, t6), + c.call(mulNonResidueFn, t6, t6), + c.call(f1mPrefix+"_mul", x0, c0, AUX), + c.call(f1mPrefix+"_add", AUX, t6, t6), + + c.call(f1mPrefix+"_inverse", t6, t6), + + c.call(f1mPrefix+"_mul", t6, c0, r0), + c.call(f1mPrefix+"_mul", t6, c1, r1), + c.call(f1mPrefix+"_mul", t6, c2, r2) + ); + } + + + function buildSign() { + const f = module.addFunction(prefix+"_sign"); + f.addParam("x", "i32"); + f.addLocal("s", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.setLocal("s" , c.call( f1mPrefix + "_sign", x2)), + c.if( + c.getLocal("s"), + c.ret(c.getLocal("s")) + ), + c.setLocal("s" , c.call( f1mPrefix + "_sign", x1)), + c.if( + c.getLocal("s"), + c.ret(c.getLocal("s")) + ), + c.ret(c.call( f1mPrefix + "_sign", x0)) + ); + } + + function buildIsOne() { + const f = module.addFunction(prefix+"_isOne"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8*2)); + + f.addCode( + c.ret( + c.i32_and( + c.i32_and( + c.call(f1mPrefix + "_isOne", x0), + c.call(f1mPrefix + "_isZero", x1) + ), + c.call(f1mPrefix + "_isZero", x2) + ) + ) + ); + } + + buildIsZero(); + buildIsOne(); + buildZero(); + buildOne(); + buildCopy(); + buildMul(); + buildSquare(); + buildAdd(); + buildSub(); + buildNeg(); + buildSign(); + buildToMontgomery(); + buildFromMontgomery(); + buildEq(); + buildInverse(); + buildTimesScalar(); + buildIsNegative(); + + module.exportFunction(prefix + "_isZero"); + module.exportFunction(prefix + "_isOne"); + module.exportFunction(prefix + "_zero"); + module.exportFunction(prefix + "_one"); + module.exportFunction(prefix + "_copy"); + module.exportFunction(prefix + "_mul"); + module.exportFunction(prefix + "_square"); + module.exportFunction(prefix + "_add"); + module.exportFunction(prefix + "_sub"); + module.exportFunction(prefix + "_neg"); + module.exportFunction(prefix + "_sign"); + module.exportFunction(prefix + "_fromMontgomery"); + module.exportFunction(prefix + "_toMontgomery"); + module.exportFunction(prefix + "_eq"); + module.exportFunction(prefix + "_inverse"); + buildBatchInverse(module, prefix); + buildExp( + module, + prefix + "_exp", + f1n8*3, + prefix + "_mul", + prefix + "_square", + prefix + "_copy", + prefix + "_one" + ); + module.exportFunction(prefix + "_exp"); + module.exportFunction(prefix + "_timesScalar"); + module.exportFunction(prefix + "_batchInverse"); + module.exportFunction(prefix + "_isNegative"); + + return prefix; +}; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +var build_timesscalarnaf = function buildTimesScalarNAF(module, fnName, elementLen, opAB, opAA, opAmB, opCopy, opInit) { + + const f = module.addFunction(fnName); + f.addParam("base", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLength", "i32"); + f.addParam("r", "i32"); + f.addLocal("old0", "i32"); + f.addLocal("nbits", "i32"); + f.addLocal("i", "i32"); + f.addLocal("last", "i32"); + f.addLocal("cur", "i32"); + f.addLocal("carry", "i32"); + f.addLocal("p", "i32"); + + const c = f.getCodeBuilder(); + + const aux = c.i32_const(module.alloc(elementLen)); + + function getBit(IDX) { + return c.i32_and( + c.i32_shr_u( + c.i32_load( + c.i32_add( + c.getLocal("scalar"), + c.i32_and( + c.i32_shr_u( + IDX, + c.i32_const(3) + ), + c.i32_const(0xFFFFFFFC) + ) + ) + ), + c.i32_and( + IDX, + c.i32_const(0x1F) + ) + ), + c.i32_const(1) + ); + } + + function pushBit(b) { + return [ + ...c.i32_store8( + c.getLocal("p"), + c.i32_const(b) + ), + ...c.setLocal( + "p", + c.i32_add( + c.getLocal("p"), + c.i32_const(1) + ) + ) + ]; + } + + f.addCode( + c.if( + c.i32_eqz(c.getLocal("scalarLength")), + [ + ...c.call(opInit, c.getLocal("r")), + ...c.ret([]) + ] + ), + c.setLocal("nbits", c.i32_shl(c.getLocal("scalarLength"), c.i32_const(3))), + c.setLocal("old0", c.i32_load(c.i32_const(0))), + c.setLocal("p", c.getLocal("old0")), + c.i32_store( + c.i32_const(0), + c.i32_and( + c.i32_add( + c.i32_add( + c.getLocal("old0"), + c.i32_const(32) + ), + c.getLocal("nbits") + ), + c.i32_const(0xFFFFFFF8) + ) + ), + c.setLocal("i", c.i32_const(1)), + + c.setLocal("last",getBit(c.i32_const(0))), + c.setLocal("carry",c.i32_const(0)), + + c.block(c.loop( + c.br_if(1, c.i32_eq( c.getLocal("i"), c.getLocal("nbits"))), + + c.setLocal("cur", getBit(c.getLocal("i"))), + c.if( c.getLocal("last"), + c.if( c.getLocal("cur"), + c.if(c.getLocal("carry"), + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(1)), + ...pushBit(1) + ] + , + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(1)), + ...pushBit(255) + ], + ), + c.if(c.getLocal("carry"), + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(1)), + ...pushBit(255) + ] + , + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(0)), + ...pushBit(1) + ], + ), + ), + c.if( c.getLocal("cur"), + c.if(c.getLocal("carry"), + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(1)), + ...pushBit(0) + ] + , + [ + ...c.setLocal("last", c.i32_const(1)), + ...c.setLocal("carry", c.i32_const(0)), + ...pushBit(0) + ], + ), + c.if(c.getLocal("carry"), + [ + ...c.setLocal("last", c.i32_const(1)), + ...c.setLocal("carry", c.i32_const(0)), + ...pushBit(0) + ] + , + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(0)), + ...pushBit(0) + ], + ), + ) + ), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + + c.if( c.getLocal("last"), + c.if(c.getLocal("carry"), + [ + ...pushBit(255), + ...pushBit(0), + ...pushBit(1) + ] + , + [ + ...pushBit(1) + ], + ), + c.if(c.getLocal("carry"), + [ + ...pushBit(0), + ...pushBit(1) + ] + ), + ), + + c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), + + // p already points to the last bit + + c.call(opCopy, c.getLocal("base"), aux), + + c.call(opInit, c.getLocal("r")), + + c.block(c.loop( + + + c.call(opAA, c.getLocal("r"), c.getLocal("r")), + + + c.setLocal("cur", + c.i32_load8_u( + c.getLocal("p") + ) + ), + + c.if( + c.getLocal("cur"), + c.if( + c.i32_eq(c.getLocal("cur"), c.i32_const(1)), + c.call(opAB, c.getLocal("r"), aux, c.getLocal("r")), + c.call(opAmB, c.getLocal("r"), aux, c.getLocal("r")), + ) + ), + + c.br_if(1, c.i32_eq( c.getLocal("old0"), c.getLocal("p"))), + c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), + c.br(0) + + )), + + c.i32_store( c.i32_const(0), c.getLocal("old0")) + + ); + +}; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +var build_multiexp = function buildMultiexp(module, prefix, fnName, opAdd, n8b) { + + const n64g = module.modules[prefix].n64; + const n8g = n64g*8; + + function buildGetChunk() { + const f = module.addFunction(fnName + "_getChunk"); + f.addParam("pScalar", "i32"); + f.addParam("scalarSize", "i32"); // Number of bytes of the scalar + f.addParam("startBit", "i32"); // Bit to start extract + f.addParam("chunkSize", "i32"); // Chunk size in bits + f.addLocal("bitsToEnd", "i32"); + f.addLocal("mask", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.setLocal("bitsToEnd", + c.i32_sub( + c.i32_mul( + c.getLocal("scalarSize"), + c.i32_const(8) + ), + c.getLocal("startBit") + ) + ), + c.if( + c.i32_gt_s( + c.getLocal("chunkSize"), + c.getLocal("bitsToEnd") + ), + c.setLocal( + "mask", + c.i32_sub( + c.i32_shl( + c.i32_const(1), + c.getLocal("bitsToEnd") + ), + c.i32_const(1) + ) + ), + c.setLocal( + "mask", + c.i32_sub( + c.i32_shl( + c.i32_const(1), + c.getLocal("chunkSize") + ), + c.i32_const(1) + ) + ) + ), + c.i32_and( + c.i32_shr_u( + c.i32_load( + c.i32_add( + c.getLocal("pScalar"), + c.i32_shr_u( + c.getLocal("startBit"), + c.i32_const(3) + ) + ), + 0, // offset + 0 // align to byte. + ), + c.i32_and( + c.getLocal("startBit"), + c.i32_const(0x7) + ) + ), + c.getLocal("mask") + ) + ); + } + + function buildMutiexpChunk() { + const f = module.addFunction(fnName + "_chunk"); + f.addParam("pBases", "i32"); + f.addParam("pScalars", "i32"); + f.addParam("scalarSize", "i32"); // Number of points + f.addParam("n", "i32"); // Number of points + f.addParam("startBit", "i32"); // bit where it starts the chunk + f.addParam("chunkSize", "i32"); // bit where it starts the chunk + f.addParam("pr", "i32"); + f.addLocal("nChunks", "i32"); + f.addLocal("itScalar", "i32"); + f.addLocal("endScalar", "i32"); + f.addLocal("itBase", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + f.addLocal("nTable", "i32"); + f.addLocal("pTable", "i32"); + f.addLocal("idx", "i32"); + f.addLocal("pIdxTable", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.if( + c.i32_eqz(c.getLocal("n")), + [ + ...c.call(prefix + "_zero", c.getLocal("pr")), + ...c.ret([]) + ] + ), + + // Allocate memory + + c.setLocal( + "nTable", + c.i32_shl( + c.i32_const(1), + c.getLocal("chunkSize") + ) + ), + c.setLocal("pTable", c.i32_load( c.i32_const(0) )), + c.i32_store( + c.i32_const(0), + c.i32_add( + c.getLocal("pTable"), + c.i32_mul( + c.getLocal("nTable"), + c.i32_const(n8g) + ) + ) + ), + + // Reset Table + c.setLocal("j", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("j"), + c.getLocal("nTable") + ) + ), + + c.call( + prefix + "_zero", + c.i32_add( + c.getLocal("pTable"), + c.i32_mul( + c.getLocal("j"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + + // Distribute elements + c.setLocal("itBase", c.getLocal("pBases")), + c.setLocal("itScalar", c.getLocal("pScalars")), + c.setLocal("endScalar", + c.i32_add( + c.getLocal("pScalars"), + c.i32_mul( + c.getLocal("n"), + c.getLocal("scalarSize") + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("itScalar"), + c.getLocal("endScalar") + ) + ), + + c.setLocal( + "idx", + c.call(fnName + "_getChunk", + c.getLocal("itScalar"), + c.getLocal("scalarSize"), + c.getLocal("startBit"), + c.getLocal("chunkSize") + ) + ), + + c.if( + c.getLocal("idx"), + [ + ...c.setLocal( + "pIdxTable", + c.i32_add( + c.getLocal("pTable"), + c.i32_mul( + c.i32_sub( + c.getLocal("idx"), + c.i32_const(1) + ), + c.i32_const(n8g) + ) + ) + ), + ...c.call( + opAdd, + c.getLocal("pIdxTable"), + c.getLocal("itBase"), + c.getLocal("pIdxTable"), + ) + ] + ), + + c.setLocal("itScalar", c.i32_add(c.getLocal("itScalar"), c.getLocal("scalarSize"))), + c.setLocal("itBase", c.i32_add(c.getLocal("itBase"), c.i32_const(n8b))), + c.br(0) + )), + + c.call(fnName + "_reduceTable", c.getLocal("pTable"), c.getLocal("chunkSize")), + c.call( + prefix + "_copy", + c.getLocal("pTable"), + c.getLocal("pr") + ), + + + c.i32_store( + c.i32_const(0), + c.getLocal("pTable") + ) + + ); + } + + function buildMultiexp() { + const f = module.addFunction(fnName); + f.addParam("pBases", "i32"); + f.addParam("pScalars", "i32"); + f.addParam("scalarSize", "i32"); // Number of points + f.addParam("n", "i32"); // Number of points + f.addParam("pr", "i32"); + f.addLocal("chunkSize", "i32"); + f.addLocal("nChunks", "i32"); + f.addLocal("itScalar", "i32"); + f.addLocal("endScalar", "i32"); + f.addLocal("itBase", "i32"); + f.addLocal("itBit", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + f.addLocal("nTable", "i32"); + f.addLocal("pTable", "i32"); + f.addLocal("idx", "i32"); + f.addLocal("pIdxTable", "i32"); + + const c = f.getCodeBuilder(); + + const aux = c.i32_const(module.alloc(n8g)); + + const pTSizes = module.alloc([ + 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 16, 16, 15, 14, 13, 13, + 12, 11, 10, 9, 8, 7, 7, 6, + 5 , 4, 3, 2, 1, 1, 1, 1 + ]); + + f.addCode( + c.call(prefix + "_zero", c.getLocal("pr")), + c.if( + c.i32_eqz(c.getLocal("n")), + c.ret([]) + ), + c.setLocal("chunkSize", c.i32_load8_u( c.i32_clz(c.getLocal("n")), pTSizes )), + c.setLocal( + "nChunks", + c.i32_add( + c.i32_div_u( + c.i32_sub( + c.i32_shl( + c.getLocal("scalarSize"), + c.i32_const(3) + ), + c.i32_const(1) + ), + c.getLocal("chunkSize") + ), + c.i32_const(1) + ) + ), + + + // Allocate memory + + c.setLocal( + "itBit", + c.i32_mul( + c.i32_sub( + c.getLocal("nChunks"), + c.i32_const(1) + ), + c.getLocal("chunkSize") + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_lt_s( + c.getLocal("itBit"), + c.i32_const(0) + ) + ), + + // Double nChunk times + c.if( + c.i32_eqz(c.call(prefix + "_isZero", c.getLocal("pr"))), + [ + ...c.setLocal("j", c.i32_const(0)), + ...c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("j"), + c.getLocal("chunkSize") + ) + ), + + c.call(prefix + "_double", c.getLocal("pr"), c.getLocal("pr")), + + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )) + ] + ), + + c.call( + fnName + "_chunk", + c.getLocal("pBases"), + c.getLocal("pScalars"), + c.getLocal("scalarSize"), + c.getLocal("n"), + c.getLocal("itBit"), + c.getLocal("chunkSize"), + aux + ), + + c.call( + prefix + "_add", + c.getLocal("pr"), + aux, + c.getLocal("pr") + ), + c.setLocal("itBit", c.i32_sub(c.getLocal("itBit"), c.getLocal("chunkSize"))), + c.br(0) + )) + ); + } + + function buildReduceTable() { + const f = module.addFunction(fnName + "_reduceTable"); + f.addParam("pTable", "i32"); + f.addParam("p", "i32"); // Number of bits of the table + f.addLocal("half", "i32"); + f.addLocal("it1", "i32"); + f.addLocal("it2", "i32"); + f.addLocal("pAcc", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.if( + c.i32_eq(c.getLocal("p"), c.i32_const(1)), + c.ret([]) + ), + c.setLocal( + "half", + c.i32_shl( + c.i32_const(1), + c.i32_sub( + c.getLocal("p"), + c.i32_const(1) + ) + ) + ), + + c.setLocal("it1", c.getLocal("pTable")), + c.setLocal( + "it2", + c.i32_add( + c.getLocal("pTable"), + c.i32_mul( + c.getLocal("half"), + c.i32_const(n8g) + ) + ) + ), + c.setLocal("pAcc", + c.i32_sub( + c.getLocal("it2"), + c.i32_const(n8g) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("it1"), + c.getLocal("pAcc") + ) + ), + c.call( + prefix + "_add", + c.getLocal("it1"), + c.getLocal("it2"), + c.getLocal("it1") + ), + c.call( + prefix + "_add", + c.getLocal("pAcc"), + c.getLocal("it2"), + c.getLocal("pAcc") + ), + c.setLocal("it1", c.i32_add(c.getLocal("it1"), c.i32_const(n8g))), + c.setLocal("it2", c.i32_add(c.getLocal("it2"), c.i32_const(n8g))), + c.br(0) + )), + + c.call( + fnName + "_reduceTable", + c.getLocal("pTable"), + c.i32_sub( + c.getLocal("p"), + c.i32_const(1) + ) + ), + + c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), + c.block(c.loop( + c.br_if(1, c.i32_eqz(c.getLocal("p"))), + c.call(prefix + "_double", c.getLocal("pAcc"), c.getLocal("pAcc")), + c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), + c.br(0) + )), + + c.call(prefix + "_add", c.getLocal("pTable"), c.getLocal("pAcc"), c.getLocal("pTable")) + ); + } + + buildGetChunk(); + buildReduceTable(); + buildMutiexpChunk(); + buildMultiexp(); + + module.exportFunction(fnName); + module.exportFunction(fnName +"_chunk"); + + +}; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const buildTimesScalarNAF = build_timesscalarnaf; +//const buildTimesScalar = require("./build_timesscalar"); +const buildBatchConvertion = build_batchconvertion; +const buildMultiexp$1 = build_multiexp; + +var build_curve_jacobian_a0 = function buildCurve(module, prefix, prefixField, pB) { const n64 = module.modules[prefixField].n64; @@ -116291,7 +119194,7 @@ module.exports = function buildCurve(module, prefix, prefixField, pB) { f.addCode( c.if( - c.call(prefix + "_isZero", c.getLocal("pIn")), + c.call(prefix + "_isZeroAffine", c.getLocal("pIn")), [ ...c.call(prefixField + "_zero", c.getLocal("pOut")), ...c.i32_store8( @@ -116336,10 +119239,6 @@ module.exports = function buildCurve(module, prefix, prefixField, pB) { c.call(prefix + "_isZeroAffine", c.getLocal("pIn")), [ ...c.call(prefix + "_zeroAffine", c.getLocal("pOut")), - ...c.i32_store8( - c.getLocal("pOut"), - c.i32_const(0x40) - ), ...c.ret([]) ] ), @@ -116442,32 +119341,6 @@ module.exports = function buildCurve(module, prefix, prefixField, pB) { ); } - - function buildInCurveAffine() { - const f = module.addFunction(prefix + "_inCurveAffine"); - f.addParam("pIn", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x = c.getLocal("pIn"); - const y = c.i32_add(c.getLocal("pIn"), n8); - - const y2 = module.alloc(n8*2); - const x3b = module.alloc(n8*2); - - f.addCode( - c.call(prefixField + "_square", y, y2), - c.call(prefixField + "_square", x, x3b), - c.call(prefixField + "_mul", x, x3b, x3b), - c.call(prefixField + "_add", x3b, c.i32_const(pB), x3b), - - c.ret( - c.call(prefixField + "_eq", y2, x3b) - ) - ); - } - function buildInCurveAffine() { const f = module.addFunction(prefix + "_inCurveAffine"); f.addParam("pIn", "i32"); @@ -116558,8 +119431,8 @@ module.exports = function buildCurve(module, prefix, prefixField, pB) { buildBatchConvertion(module, prefix + "_batchToJacobian", prefix + "_toJacobian", n8*2, n8*3, true); - buildMultiexp(module, prefix, prefix + "_multiexp", prefix + "_add", n8*3); - buildMultiexp(module, prefix, prefix + "_multiexpAffine", prefix + "_addMixed", n8*2); + buildMultiexp$1(module, prefix, prefix + "_multiexp", prefix + "_add", n8*3); + buildMultiexp$1(module, prefix, prefix + "_multiexpAffine", prefix + "_addMixed", n8*2); /* buildTimesScalar( @@ -116660,12 +119533,6 @@ module.exports = function buildCurve(module, prefix, prefixField, pB) { return prefix; }; - -/***/ }), - -/***/ 38138: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - /* Copyright 2019 0KIMS association. @@ -116685,2434 +119552,10 @@ module.exports = function buildCurve(module, prefix, prefixField, pB) { along with wasmsnark. If not, see . */ -const bigInt = __webpack_require__(92096); +const { isOdd: isOdd$2, modInv: modInv$1, modPow } = bigint; +const utils$3 = utils$6; -const buildF1m =__webpack_require__(70075); - -module.exports = function buildF1(module, _q, _prefix, _f1mPrefix, _intPrefix) { - - const q = bigInt(_q); - const n64 = Math.floor((q.minus(1).bitLength() - 1)/64) +1; - const n8 = n64*8; - - const prefix = _prefix || "f1"; - if (module.modules[prefix]) return prefix; // already builded - module.modules[prefix] = { - n64: n64 - }; - - const intPrefix = _intPrefix || "int"; - const f1mPrefix = buildF1m(module, q, _f1mPrefix, intPrefix); - - - const pR2 = module.modules[f1mPrefix].pR2; - const pq = module.modules[f1mPrefix].pq; - const pePlusOne = module.modules[f1mPrefix].pePlusOne; - - function buildMul() { - const pAux1 = module.alloc(n8); - - const f = module.addFunction(prefix+ "_mul"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - f.addCode(c.call(f1mPrefix + "_mul", c.getLocal("x"), c.getLocal("y"), c.i32_const(pAux1))); - f.addCode(c.call(f1mPrefix + "_mul", c.i32_const(pAux1), c.i32_const(pR2), c.getLocal("r"))); - } - - function buildSquare() { - const f = module.addFunction(prefix+"_square"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); - } - - - function buildInverse() { - - const f = module.addFunction(prefix+ "_inverse"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - f.addCode(c.call(intPrefix + "_inverseMod", c.getLocal("x"), c.i32_const(pq), c.getLocal("r"))); - } - - function buildIsNegative() { - const f = module.addFunction(prefix+"_isNegative"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call(intPrefix + "_gte", c.getLocal("x"), c.i32_const(pePlusOne) ) - ); - } - - - buildMul(); - buildSquare(); - buildInverse(); - buildIsNegative(); - module.exportFunction(f1mPrefix + "_add", prefix + "_add"); - module.exportFunction(f1mPrefix + "_sub", prefix + "_sub"); - module.exportFunction(f1mPrefix + "_neg", prefix + "_neg"); - module.exportFunction(prefix + "_mul"); - module.exportFunction(prefix + "_square"); - module.exportFunction(prefix + "_inverse"); - module.exportFunction(prefix + "_isNegative"); - module.exportFunction(f1mPrefix + "_copy", prefix+"_copy"); - module.exportFunction(f1mPrefix + "_zero", prefix+"_zero"); - module.exportFunction(f1mPrefix + "_one", prefix+"_one"); - module.exportFunction(f1mPrefix + "_isZero", prefix+"_isZero"); - module.exportFunction(f1mPrefix + "_eq", prefix+"_eq"); - - return prefix; -}; - - -/***/ }), - -/***/ 70075: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -const bigInt = __webpack_require__(92096); -const buildInt = __webpack_require__(76754); -const utils = __webpack_require__(12333); -const buildExp = __webpack_require__(50345); -const buildBatchInverse = __webpack_require__(18163); -const buildBatchConvertion = __webpack_require__(9440); -const buildBatchOp = __webpack_require__(4948); - -module.exports = function buildF1m(module, _q, _prefix, _intPrefix) { - const q = bigInt(_q); - const n64 = Math.floor((q.minus(1).bitLength() - 1)/64) +1; - const n32 = n64*2; - const n8 = n64*8; - - const prefix = _prefix || "f1m"; - if (module.modules[prefix]) return prefix; // already builded - - const intPrefix = buildInt(module, n64, _intPrefix); - const pq = module.alloc(n8, utils.bigInt2BytesLE(q, n8)); - - const pR = module.alloc(utils.bigInt2BytesLE(bigInt.one.shiftLeft(n64*64).mod(q), n8)); - const pR2 = module.alloc(utils.bigInt2BytesLE(bigInt.one.shiftLeft(n64*64).square().mod(q), n8)); - const pOne = module.alloc(utils.bigInt2BytesLE(bigInt.one.shiftLeft(n64*64).mod(q), n8)); - const pZero = module.alloc(utils.bigInt2BytesLE(bigInt.zero, n8)); - const _minusOne = q.minus(bigInt.one); - const _e = _minusOne.shiftRight(1); // e = (p-1)/2 - const pe = module.alloc(n8, utils.bigInt2BytesLE(_e, n8)); - - const _ePlusOne = _e.add(bigInt.one); // e = (p-1)/2 - const pePlusOne = module.alloc(n8, utils.bigInt2BytesLE(_ePlusOne, n8)); - - module.modules[prefix] = { - pq: pq, - pR2: pR2, - n64: n64, - q: q, - pOne: pOne, - pZero: pZero, - pePlusOne: pePlusOne - }; - - function buildOne() { - const f = module.addFunction(prefix+"_one"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode(c.call(intPrefix + "_copy", c.i32_const(pOne), c.getLocal("pr"))); - } - - function buildAdd() { - const f = module.addFunction(prefix+"_add"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.if( - c.call(intPrefix+"_add", c.getLocal("x"), c.getLocal("y"), c.getLocal("r")), - c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), - c.if( - c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), - c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), - ) - ) - ); - } - - function buildSub() { - const f = module.addFunction(prefix+"_sub"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.if( - c.call(intPrefix+"_sub", c.getLocal("x"), c.getLocal("y"), c.getLocal("r")), - c.drop(c.call(intPrefix+"_add", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))) - ) - ); - } - - function buildNeg() { - const f = module.addFunction(prefix+"_neg"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call(prefix + "_sub", c.i32_const(pZero), c.getLocal("x"), c.getLocal("r")) - ); - } - - - function buildIsNegative() { - const f = module.addFunction(prefix+"_isNegative"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const AUX = c.i32_const(module.alloc(n8)); - - f.addCode( - c.call(prefix + "_fromMontgomery", c.getLocal("x"), AUX), - c.call(intPrefix + "_gte", AUX, c.i32_const(pePlusOne) ) - ); - } - - -/* - function buildIsNegative() { - const f = module.addFunction(prefix+"_isNegative"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const AUX = c.i32_const(module.alloc(n8)); - - f.addCode( - c.call(prefix + "_fromMontgomery", c.getLocal("x"), AUX), - c.i32_and( - c.i32_load(AUX), - c.i32_const(1) - ) - ); - } -*/ - - function buildSign() { - const f = module.addFunction(prefix+"_sign"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const AUX = c.i32_const(module.alloc(n8)); - - f.addCode( - c.if ( - c.call(intPrefix + "_isZero", c.getLocal("x")), - c.ret(c.i32_const(0)) - ), - c.call(prefix + "_fromMontgomery", c.getLocal("x"), AUX), - c.if( - c.call(intPrefix + "_gte", AUX, c.i32_const(pePlusOne)), - c.ret(c.i32_const(-1)) - ), - c.ret(c.i32_const(1)) - ); - } - - - function buildMReduct() { - const carries = module.alloc(n32*n32*8); - - const f = module.addFunction(prefix+"_mReduct"); - f.addParam("t", "i32"); - f.addParam("r", "i32"); - f.addLocal("np32", "i64"); - f.addLocal("c", "i64"); - f.addLocal("m", "i64"); - - const c = f.getCodeBuilder(); - - const np32 = bigInt("100000000",16).minus( q.modInv(bigInt("100000000",16))).toJSNumber(); - - f.addCode(c.setLocal("np32", c.i64_const(np32))); - - for (let i=0; i=n32) { - f.addCode( - c.i64_store32( - c.getLocal("r"), - (k-n32)*4, - c.getLocal(c0) - ) - ); - } - [c0, c1] = [c1, c0]; - f.addCode( - c.setLocal(c1, - c.i64_shr_u( - c.getLocal(c0), - c.i64_const(32) - ) - ) - ); - } - f.addCode( - c.i64_store32( - c.getLocal("r"), - n32*4-4, - c.getLocal(c0) - ) - ); - - f.addCode( - c.if( - c.i32_wrap_i64(c.getLocal(c1)), - c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), - c.if( - c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), - c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), - ) - ) - ); - } - - - function buildSquare() { - - const f = module.addFunction(prefix+"_square"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - f.addLocal("c0", "i64"); - f.addLocal("c1", "i64"); - f.addLocal("c0_old", "i64"); - f.addLocal("c1_old", "i64"); - f.addLocal("np32", "i64"); - - - for (let i=0;i>1) )&&(i>1, k>>1) - ) - ) - ); - - f.addCode( - c.setLocal(c1, - c.i64_add( - c.getLocal(c1), - c.i64_shr_u( - c.getLocal(c0), - c.i64_const(32) - ) - ) - ) - ); - } - - // Add the old carry - - if (k>0) { - f.addCode( - c.setLocal(c0, - c.i64_add( - c.i64_and( - c.getLocal(c0), - c.i64_const(0xFFFFFFFF) - ), - c.i64_and( - c.getLocal(c0_old), - c.i64_const(0xFFFFFFFF) - ), - ) - ) - ); - - f.addCode( - c.setLocal(c1, - c.i64_add( - c.i64_add( - c.getLocal(c1), - c.i64_shr_u( - c.getLocal(c0), - c.i64_const(32) - ) - ), - c.getLocal(c1_old) - ) - ) - ); - } - - - for (let i=Math.max(1, k-n32+1); (i<=k)&&(i=n32) { - f.addCode( - c.i64_store32( - c.getLocal("r"), - (k-n32)*4, - c.getLocal(c0) - ) - ); - } - f.addCode( - c.setLocal( - c0_old, - c.getLocal(c1) - ), - c.setLocal( - c1_old, - c.i64_shr_u( - c.getLocal(c0_old), - c.i64_const(32) - ) - ) - ); - } - f.addCode( - c.i64_store32( - c.getLocal("r"), - n32*4-4, - c.getLocal(c0_old) - ) - ); - - f.addCode( - c.if( - c.i32_wrap_i64(c.getLocal(c1_old)), - c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), - c.if( - c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), - c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), - ) - ) - ); - } - - - function buildSquareOld() { - const f = module.addFunction(prefix+"_squareOld"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); - } - - function buildToMontgomery() { - const f = module.addFunction(prefix+"_toMontgomery"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - f.addCode(c.call(prefix+"_mul", c.getLocal("x"), c.i32_const(pR2), c.getLocal("r"))); - } - - function buildFromMontgomery() { - - const pAux2 = module.alloc(n8*2); - - const f = module.addFunction(prefix+"_fromMontgomery"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - f.addCode(c.call(intPrefix + "_copy", c.getLocal("x"), c.i32_const(pAux2) )); - f.addCode(c.call(intPrefix + "_zero", c.i32_const(pAux2 + n8) )); - f.addCode(c.call(prefix+"_mReduct", c.i32_const(pAux2), c.getLocal("r"))); - } - - function buildInverse() { - - const f = module.addFunction(prefix+ "_inverse"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - f.addCode(c.call(prefix + "_fromMontgomery", c.getLocal("x"), c.getLocal("r"))); - f.addCode(c.call(intPrefix + "_inverseMod", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))); - f.addCode(c.call(prefix + "_toMontgomery", c.getLocal("r"), c.getLocal("r"))); - } - - // Calculate various valuse needed for sqrt - - - let _nqr = bigInt(2); - if (q.isPrime()) { - while (!_nqr.modPow(_e, q).equals(_minusOne)) _nqr = _nqr.add(bigInt.one); - } - - const pnqr = module.alloc(utils.bigInt2BytesLE(_nqr.shiftLeft(n64*64).mod(q), n8)); - - let s2 = 0; - let _t = _minusOne; - - while ((!_t.isOdd())&&(!_t.isZero())) { - s2++; - _t = _t.shiftRight(1); - } - const pt = module.alloc(n8, utils.bigInt2BytesLE(_t, n8)); - - const _nqrToT = _nqr.modPow(_t, q); - const pNqrToT = module.alloc(utils.bigInt2BytesLE(_nqrToT.shiftLeft(n64*64).mod(q), n8)); - - const _tPlusOneOver2 = _t.add(1).shiftRight(1); - const ptPlusOneOver2 = module.alloc(n8, utils.bigInt2BytesLE(_tPlusOneOver2, n8)); - - function buildSqrt() { - - const f = module.addFunction(prefix+ "_sqrt"); - f.addParam("n", "i32"); - f.addParam("r", "i32"); - f.addLocal("m", "i32"); - f.addLocal("i", "i32"); - f.addLocal("j", "i32"); - - const c = f.getCodeBuilder(); - - const ONE = c.i32_const(pOne); - const C = c.i32_const(module.alloc(n8)); - const T = c.i32_const(module.alloc(n8)); - const R = c.i32_const(module.alloc(n8)); - const SQ = c.i32_const(module.alloc(n8)); - const B = c.i32_const(module.alloc(n8)); - - f.addCode( - - // If (n==0) return 0 - c.if( - c.call(prefix + "_isZero", c.getLocal("n")), - c.ret( - c.call(prefix + "_zero", c.getLocal("r")) - ) - ), - - c.setLocal("m", c.i32_const(s2)), - c.call(prefix + "_copy", c.i32_const(pNqrToT), C), - c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(pt), c.i32_const(n8), T), - c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(ptPlusOneOver2), c.i32_const(n8), R), - - c.block(c.loop( - c.br_if(1, c.call(prefix + "_eq", T, ONE)), - - c.call(prefix + "_square", T, SQ), - c.setLocal("i", c.i32_const(1)), - c.block(c.loop( - c.br_if(1, c.call(prefix + "_eq", SQ, ONE)), - c.call(prefix + "_square", SQ, SQ), - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )), - - c.call(prefix + "_copy", C, B), - c.setLocal("j", c.i32_sub(c.i32_sub( c.getLocal("m"), c.getLocal("i")), c.i32_const(1)) ), - c.block(c.loop( - c.br_if(1, c.i32_eqz(c.getLocal("j"))), - c.call(prefix + "_square", B, B), - c.setLocal("j", c.i32_sub(c.getLocal("j"), c.i32_const(1))), - c.br(0) - )), - - c.setLocal("m", c.getLocal("i")), - c.call(prefix + "_square", B, C), - c.call(prefix + "_mul", T, C, T), - c.call(prefix + "_mul", R, B, R), - - c.br(0) - )), - - c.if( - c.call(prefix + "_isNegative", R), - c.call(prefix + "_neg", R, c.getLocal("r")), - c.call(prefix + "_copy", R, c.getLocal("r")), - ) - ); - } - - function buildIsSquare() { - const f = module.addFunction(prefix+"_isSquare"); - f.addParam("n", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const ONE = c.i32_const(pOne); - const AUX = c.i32_const(module.alloc(n8)); - - f.addCode( - c.if( - c.call(prefix + "_isZero", c.getLocal("n")), - c.ret(c.i32_const(1)) - ), - c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(pe), c.i32_const(n8), AUX), - c.call(prefix + "_eq", AUX, ONE) - ); - } - - - function buildLoad() { - const f = module.addFunction(prefix+"_load"); - f.addParam("scalar", "i32"); - f.addParam("scalarLen", "i32"); - f.addParam("r", "i32"); - f.addLocal("p", "i32"); - f.addLocal("l", "i32"); - f.addLocal("i", "i32"); - f.addLocal("j", "i32"); - const c = f.getCodeBuilder(); - - const R = c.i32_const(module.alloc(n8)); - const pAux = module.alloc(n8); - const AUX = c.i32_const(pAux); - - f.addCode( - c.call(intPrefix + "_zero", c.getLocal("r")), - c.setLocal("i", c.i32_const(n8)), - c.setLocal("p", c.getLocal("scalar")), - c.block(c.loop( - c.br_if(1, c.i32_gt_u(c.getLocal("i"), c.getLocal("scalarLen"))), - - c.if( - c.i32_eq(c.getLocal("i"), c.i32_const(n8)), - c.call(prefix + "_one", R), - c.call(prefix + "_mul", R, c.i32_const(pR2), R) - ), - c.call(prefix + "_mul", c.getLocal("p"), R, AUX), - c.call(prefix + "_add", c.getLocal("r"), AUX, c.getLocal("r")), - - c.setLocal("p", c.i32_add(c.getLocal("p"), c.i32_const(n8))), - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(n8))), - c.br(0) - )), - - c.setLocal("l", c.i32_rem_u( c.getLocal("scalarLen"), c.i32_const(n8))), - c.if(c.i32_eqz(c.getLocal("l")), c.ret([])), - c.call(intPrefix + "_zero", AUX), - c.setLocal("j", c.i32_const(0)), - c.block(c.loop( - c.br_if(1, c.i32_eq(c.getLocal("j"), c.getLocal("l"))), - - c.i32_store8( - c.getLocal("j"), - pAux, - c.i32_load8_u(c.getLocal("p")), - ), - c.setLocal("p", c.i32_add(c.getLocal("p"), c.i32_const(1))), - c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), - c.br(0) - )), - - c.if( - c.i32_eq(c.getLocal("i"), c.i32_const(n8)), - c.call(prefix + "_one", R), - c.call(prefix + "_mul", R, c.i32_const(pR2), R) - ), - c.call(prefix + "_mul", AUX, R, AUX), - c.call(prefix + "_add", c.getLocal("r"), AUX, c.getLocal("r")), - ); - } - - function buildTimesScalar() { - const f = module.addFunction(prefix+"_timesScalar"); - f.addParam("x", "i32"); - f.addParam("scalar", "i32"); - f.addParam("scalarLen", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const AUX = c.i32_const(module.alloc(n8)); - - f.addCode( - c.call(prefix + "_load", c.getLocal("scalar"), c.getLocal("scalarLen"), AUX), - c.call(prefix + "_toMontgomery", AUX, AUX), - c.call(prefix + "_mul", c.getLocal("x"), AUX, c.getLocal("r")), - ); - } - - function buildIsOne() { - const f = module.addFunction(prefix+"_isOne"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - f.addCode( - c.ret(c.call(intPrefix + "_eq", c.getLocal("x"), c.i32_const(pOne))) - ); - } - - - module.exportFunction(intPrefix + "_copy", prefix+"_copy"); - module.exportFunction(intPrefix + "_zero", prefix+"_zero"); - module.exportFunction(intPrefix + "_isZero", prefix+"_isZero"); - module.exportFunction(intPrefix + "_eq", prefix+"_eq"); - - buildIsOne(); - buildAdd(); - buildSub(); - buildNeg(); - buildMReduct(); - buildMul(); - buildSquare(); - buildSquareOld(); - buildToMontgomery(); - buildFromMontgomery(); - buildIsNegative(); - buildSign(); - buildInverse(); - buildOne(); - buildLoad(); - buildTimesScalar(); - buildBatchInverse(module, prefix); - buildBatchConvertion(module, prefix + "_batchToMontgomery", prefix + "_toMontgomery", n8, n8); - buildBatchConvertion(module, prefix + "_batchFromMontgomery", prefix + "_fromMontgomery", n8, n8); - buildBatchConvertion(module, prefix + "_batchNeg", prefix + "_neg", n8, n8); - buildBatchOp(module, prefix + "_batchAdd", prefix + "_add", n8, n8); - buildBatchOp(module, prefix + "_batchSub", prefix + "_sub", n8, n8); - buildBatchOp(module, prefix + "_batchMul", prefix + "_mul", n8, n8); - - module.exportFunction(prefix + "_add"); - module.exportFunction(prefix + "_sub"); - module.exportFunction(prefix + "_neg"); - module.exportFunction(prefix + "_isNegative"); - module.exportFunction(prefix + "_isOne"); - module.exportFunction(prefix + "_sign"); - module.exportFunction(prefix + "_mReduct"); - module.exportFunction(prefix + "_mul"); - module.exportFunction(prefix + "_square"); - module.exportFunction(prefix + "_squareOld"); - module.exportFunction(prefix + "_fromMontgomery"); - module.exportFunction(prefix + "_toMontgomery"); - module.exportFunction(prefix + "_inverse"); - module.exportFunction(prefix + "_one"); - module.exportFunction(prefix + "_load"); - module.exportFunction(prefix + "_timesScalar"); - buildExp( - module, - prefix + "_exp", - n8, - prefix + "_mul", - prefix + "_square", - intPrefix + "_copy", - prefix + "_one", - ); - module.exportFunction(prefix + "_exp"); - module.exportFunction(prefix + "_batchInverse"); - if (q.isPrime()) { - buildSqrt(); - buildIsSquare(); - module.exportFunction(prefix + "_sqrt"); - module.exportFunction(prefix + "_isSquare"); - } - module.exportFunction(prefix + "_batchToMontgomery"); - module.exportFunction(prefix + "_batchFromMontgomery"); - // console.log(module.functionIdxByName); - - return prefix; -}; - - -/***/ }), - -/***/ 15420: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ -const buildExp = __webpack_require__(50345); -const buildBatchInverse = __webpack_require__(18163); -const bigInt = __webpack_require__(92096); -const utils = __webpack_require__(12333); - -module.exports = function buildF2m(module, mulNonResidueFn, prefix, f1mPrefix) { - - if (module.modules[prefix]) return prefix; // already builded - - const f1n8 = module.modules[f1mPrefix].n64*8; - const q = module.modules[f1mPrefix].q; - - module.modules[prefix] = { - n64: module.modules[f1mPrefix].n64*2 - }; - - function buildAdd() { - const f = module.addFunction(prefix+"_add"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const y0 = c.getLocal("y"); - const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_add", x0, y0, r0), - c.call(f1mPrefix+"_add", x1, y1, r1), - ); - } - - function buildTimesScalar() { - const f = module.addFunction(prefix+"_timesScalar"); - f.addParam("x", "i32"); - f.addParam("scalar", "i32"); - f.addParam("scalarLen", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_timesScalar", x0, c.getLocal("scalar"), c.getLocal("scalarLen"), r0), - c.call(f1mPrefix+"_timesScalar", x1, c.getLocal("scalar"), c.getLocal("scalarLen"), r1), - ); - } - - function buildSub() { - const f = module.addFunction(prefix+"_sub"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const y0 = c.getLocal("y"); - const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_sub", x0, y0, r0), - c.call(f1mPrefix+"_sub", x1, y1, r1), - ); - } - - function buildNeg() { - const f = module.addFunction(prefix+"_neg"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_neg", x0, r0), - c.call(f1mPrefix+"_neg", x1, r1), - ); - } - - function buildConjugate() { - const f = module.addFunction(prefix+"_conjugate"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_copy", x0, r0), - c.call(f1mPrefix+"_neg", x1, r1), - ); - } - - - function buildIsNegative() { - const f = module.addFunction(prefix+"_isNegative"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - - f.addCode( - c.if( - c.call(f1mPrefix+"_isZero", x1), - c.ret(c.call(f1mPrefix+"_isNegative", x0)) - ), - c.ret(c.call(f1mPrefix+"_isNegative", x1)) - ); - } - - function buildMul() { - const f = module.addFunction(prefix+"_mul"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const y0 = c.getLocal("y"); - const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - const A = c.i32_const(module.alloc(f1n8)); - const B = c.i32_const(module.alloc(f1n8)); - const C = c.i32_const(module.alloc(f1n8)); - const D = c.i32_const(module.alloc(f1n8)); - - - f.addCode( - c.call(f1mPrefix + "_mul", x0, y0, A), // A = x0*y0 - c.call(f1mPrefix + "_mul", x1, y1, B), // B = x1*y1 - - c.call(f1mPrefix + "_add", x0, x1, C), // C = x0 + x1 - c.call(f1mPrefix + "_add", y0, y1, D), // D = y0 + y1 - c.call(f1mPrefix + "_mul", C, D, C), // C = (x0 + x1)*(y0 + y1) = x0*y0+x0*y1+x1*y0+x1*y1 - - // c.call(f1mPrefix + "_mul", B, c.i32_const(pNonResidue), r0), // r0 = nr*(x1*y1) - c.call(mulNonResidueFn, B, r0), // r0 = nr*(x1*y1) - c.call(f1mPrefix + "_add", A, r0, r0), // r0 = x0*y0 + nr*(x1*y1) - c.call(f1mPrefix + "_add", A, B, r1), // r1 = x0*y0+x1*y1 - c.call(f1mPrefix + "_sub", C, r1, r1) // r1 = x0*y0+x0*y1+x1*y0+x1*y1 - x0*y0+x1*y1 = x0*y1+x1*y0 - ); - - } - - function buildMul1() { - const f = module.addFunction(prefix+"_mul1"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const y = c.getLocal("y"); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - - f.addCode( - c.call(f1mPrefix + "_mul", x0, y, r0), // A = x0*y - c.call(f1mPrefix + "_mul", x1, y, r1), // B = x1*y - ); - } - - function buildSquare() { - const f = module.addFunction(prefix+"_square"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - const AB = c.i32_const(module.alloc(f1n8)); - const APB = c.i32_const(module.alloc(f1n8)); - const APNB = c.i32_const(module.alloc(f1n8)); - const ABPNAB = c.i32_const(module.alloc(f1n8)); - - - f.addCode( - // AB = x0*y1 - c.call(f1mPrefix + "_mul", x0, x1, AB), - - // APB = x0+y1 - c.call(f1mPrefix + "_add", x0, x1, APB), - - // APBN0 = x0 + nr*x1 - c.call(mulNonResidueFn, x1, APNB), - c.call(f1mPrefix + "_add", x0, APNB, APNB), - - // ABPNAB = ab + nr*ab - c.call(mulNonResidueFn, AB, ABPNAB), - c.call(f1mPrefix + "_add", ABPNAB, AB, ABPNAB), - - // r0 = APB * APNB - ABPNAB - c.call(f1mPrefix + "_mul", APB, APNB, r0), - c.call(f1mPrefix + "_sub", r0, ABPNAB, r0), - - // r1 = AB + AB - c.call(f1mPrefix + "_add", AB, AB, r1), - ); - - } - - - function buildToMontgomery() { - const f = module.addFunction(prefix+"_toMontgomery"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_toMontgomery", x0, r0), - c.call(f1mPrefix+"_toMontgomery", x1, r1) - ); - } - - function buildFromMontgomery() { - const f = module.addFunction(prefix+"_fromMontgomery"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_fromMontgomery", x0, r0), - c.call(f1mPrefix+"_fromMontgomery", x1, r1) - ); - } - - function buildCopy() { - const f = module.addFunction(prefix+"_copy"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_copy", x0, r0), - c.call(f1mPrefix+"_copy", x1, r1) - ); - } - - function buildZero() { - const f = module.addFunction(prefix+"_zero"); - f.addParam("x", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_zero", x0), - c.call(f1mPrefix+"_zero", x1) - ); - } - - function buildOne() { - const f = module.addFunction(prefix+"_one"); - f.addParam("x", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_one", x0), - c.call(f1mPrefix+"_zero", x1) - ); - } - - function buildEq() { - const f = module.addFunction(prefix+"_eq"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const y0 = c.getLocal("y"); - const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); - - f.addCode( - c.i32_and( - c.call(f1mPrefix+"_eq", x0, y0), - c.call(f1mPrefix+"_eq", x1, y1) - ) - ); - } - - function buildIsZero() { - const f = module.addFunction(prefix+"_isZero"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - - f.addCode( - c.i32_and( - c.call(f1mPrefix+"_isZero", x0), - c.call(f1mPrefix+"_isZero", x1) - ) - ); - } - - function buildInverse() { - const f = module.addFunction(prefix+"_inverse"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - const t0 = c.i32_const(module.alloc(f1n8)); - const t1 = c.i32_const(module.alloc(f1n8)); - const t2 = c.i32_const(module.alloc(f1n8)); - const t3 = c.i32_const(module.alloc(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_square", x0, t0), - c.call(f1mPrefix+"_square", x1, t1), - // c.call(f1mPrefix+"_mul", t1, c.i32_const(pNonResidue), t2), - c.call(mulNonResidueFn, t1, t2), - - c.call(f1mPrefix+"_sub", t0, t2, t2), - c.call(f1mPrefix+"_inverse", t2, t3), - - c.call(f1mPrefix+"_mul", x0, t3, r0), - c.call(f1mPrefix+"_mul", x1, t3, r1), - c.call(f1mPrefix+"_neg", r1, r1), - ); - } - - - function buildSign() { - const f = module.addFunction(prefix+"_sign"); - f.addParam("x", "i32"); - f.addLocal("s", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - - f.addCode( - c.setLocal("s" , c.call( f1mPrefix + "_sign", x1)), - c.if( - c.getLocal("s"), - c.ret(c.getLocal("s")) - ), - c.ret(c.call( f1mPrefix + "_sign", x0)) - ); - } - - function buildIsOne() { - const f = module.addFunction(prefix+"_isOne"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - - f.addCode( - c.ret(c.i32_and( - c.call(f1mPrefix + "_isOne", x0), - c.call(f1mPrefix + "_isZero", x1), - )) - ); - } - - - // Check here: https://eprint.iacr.org/2012/685.pdf - // Alg 9adj - function buildSqrt() { - - const f = module.addFunction(prefix+"_sqrt"); - f.addParam("a", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - const e34 = c.i32_const(module.alloc(utils.bigInt2BytesLE(bigInt(q).minus(bigInt(3)).divide(4), f1n8 ))); - const e12 = c.i32_const(module.alloc(utils.bigInt2BytesLE(bigInt(q).minus(bigInt(1)).divide(2), f1n8 ))); - - const a = c.getLocal("a"); - const a1 = c.i32_const(module.alloc(f1n8*2)); - const alpha = c.i32_const(module.alloc(f1n8*2)); - const a0 = c.i32_const(module.alloc(f1n8*2)); - const pn1 = module.alloc(f1n8*2); - const n1 = c.i32_const(pn1); - const n1a = c.i32_const(pn1); - const n1b = c.i32_const(pn1+f1n8); - const x0 = c.i32_const(module.alloc(f1n8*2)); - const b = c.i32_const(module.alloc(f1n8*2)); - - f.addCode( - - c.call(prefix + "_one", n1), - c.call(prefix + "_neg", n1, n1), - - // const a1 = F.pow(a, F.sqrt_e34); - c.call(prefix + "_exp", a, e34, c.i32_const(f1n8), a1), - - // const a1 = F.pow(a, F.sqrt_e34); - c.call(prefix + "_square", a1, alpha), - c.call(prefix + "_mul", a, alpha, alpha), - - // const a0 = F.mul(F.frobenius(1, alfa), alfa); - c.call(prefix + "_conjugate", alpha, a0), - c.call(prefix + "_mul", a0, alpha, a0), - - // if (F.eq(a0, F.negone)) return null; - c.if(c.call(prefix + "_eq",a0,n1), c.unreachable() ), - - // const x0 = F.mul(a1, a); - c.call(prefix + "_mul", a1, a, x0), - - // if (F.eq(alfa, F.negone)) { - c.if( - c.call(prefix + "_eq", alpha, n1), - [ - // x = F.mul(x0, [F.F.zero, F.F.one]); - ...c.call(f1mPrefix + "_zero", n1a), - ...c.call(f1mPrefix + "_one", n1b), - ...c.call(prefix + "_mul", n1, x0, c.getLocal("pr")), - ], - [ - // const b = F.pow(F.add(F.one, alfa), F.sqrt_e12); - ...c.call(prefix + "_one", b), - ...c.call(prefix + "_add", b, alpha, b), - ...c.call(prefix + "_exp", b, e12, c.i32_const(f1n8), b), - - // x = F.mul(b, x0); - ...c.call(prefix + "_mul", b, x0, c.getLocal("pr")), - ] - ) - ); - - } - - - function buildIsSquare() { - - const f = module.addFunction(prefix+"_isSquare"); - f.addParam("a", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const e34 = c.i32_const(module.alloc(utils.bigInt2BytesLE(bigInt(q).minus(bigInt(3)).divide(4), f1n8 ))); - - const a = c.getLocal("a"); - const a1 = c.i32_const(module.alloc(f1n8*2)); - const alpha = c.i32_const(module.alloc(f1n8*2)); - const a0 = c.i32_const(module.alloc(f1n8*2)); - const pn1 = module.alloc(f1n8*2); - const n1 = c.i32_const(pn1); - - f.addCode( - - c.call(prefix + "_one", n1), - c.call(prefix + "_neg", n1, n1), - - // const a1 = F.pow(a, F.sqrt_e34); - c.call(prefix + "_exp", a, e34, c.i32_const(f1n8), a1), - - // const a1 = F.pow(a, F.sqrt_e34); - c.call(prefix + "_square", a1, alpha), - c.call(prefix + "_mul", a, alpha, alpha), - - // const a0 = F.mul(F.frobenius(1, alfa), alfa); - c.call(prefix + "_conjugate", alpha, a0), - c.call(prefix + "_mul", a0, alpha, a0), - - // if (F.eq(a0, F.negone)) return null; - c.if( - c.call( - prefix + "_eq", - a0, - n1 - ), - c.ret(c.i32_const(0)) - ), - c.ret(c.i32_const(1)) - ); - - } - - - buildIsZero(); - buildIsOne(); - buildZero(); - buildOne(); - buildCopy(); - buildMul(); - buildMul1(); - buildSquare(); - buildAdd(); - buildSub(); - buildNeg(); - buildConjugate(); - buildToMontgomery(); - buildFromMontgomery(); - buildEq(); - buildInverse(); - buildTimesScalar(); - buildSign(); - buildIsNegative(); - - module.exportFunction(prefix + "_isZero"); - module.exportFunction(prefix + "_isOne"); - module.exportFunction(prefix + "_zero"); - module.exportFunction(prefix + "_one"); - module.exportFunction(prefix + "_copy"); - module.exportFunction(prefix + "_mul"); - module.exportFunction(prefix + "_mul1"); - module.exportFunction(prefix + "_square"); - module.exportFunction(prefix + "_add"); - module.exportFunction(prefix + "_sub"); - module.exportFunction(prefix + "_neg"); - module.exportFunction(prefix + "_sign"); - module.exportFunction(prefix + "_conjugate"); - module.exportFunction(prefix + "_fromMontgomery"); - module.exportFunction(prefix + "_toMontgomery"); - module.exportFunction(prefix + "_eq"); - module.exportFunction(prefix + "_inverse"); - buildBatchInverse(module, prefix); - buildExp( - module, - prefix + "_exp", - f1n8*2, - prefix + "_mul", - prefix + "_square", - prefix + "_copy", - prefix + "_one", - ); - buildSqrt(); - buildIsSquare(); - - module.exportFunction(prefix + "_exp"); - module.exportFunction(prefix + "_timesScalar"); - module.exportFunction(prefix + "_batchInverse"); - module.exportFunction(prefix + "_sqrt"); - module.exportFunction(prefix + "_isSquare"); - module.exportFunction(prefix + "_isNegative"); - - - return prefix; -}; - - -/***/ }), - -/***/ 77173: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ -const buildExp = __webpack_require__(50345); -const buildBatchInverse = __webpack_require__(18163); - -module.exports = function buildF3m(module, mulNonResidueFn, prefix, f1mPrefix) { - - if (module.modules[prefix]) return prefix; // already builded - - const f1n8 = module.modules[f1mPrefix].n64*8; - module.modules[prefix] = { - n64: module.modules[f1mPrefix].n64*3 - }; - - function buildAdd() { - const f = module.addFunction(prefix+"_add"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const y0 = c.getLocal("y"); - const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); - const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_add", x0, y0, r0), - c.call(f1mPrefix+"_add", x1, y1, r1), - c.call(f1mPrefix+"_add", x2, y2, r2), - ); - } - - function buildTimesScalar() { - const f = module.addFunction(prefix+"_timesScalar"); - f.addParam("x", "i32"); - f.addParam("scalar", "i32"); - f.addParam("scalarLen", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_timesScalar", x0, c.getLocal("scalar"), c.getLocal("scalarLen"), r0), - c.call(f1mPrefix+"_timesScalar", x1, c.getLocal("scalar"), c.getLocal("scalarLen"), r1), - c.call(f1mPrefix+"_timesScalar", x2, c.getLocal("scalar"), c.getLocal("scalarLen"), r2), - ); - } - - - function buildSub() { - const f = module.addFunction(prefix+"_sub"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const y0 = c.getLocal("y"); - const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); - const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_sub", x0, y0, r0), - c.call(f1mPrefix+"_sub", x1, y1, r1), - c.call(f1mPrefix+"_sub", x2, y2, r2), - ); - } - - function buildNeg() { - const f = module.addFunction(prefix+"_neg"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_neg", x0, r0), - c.call(f1mPrefix+"_neg", x1, r1), - c.call(f1mPrefix+"_neg", x2, r2), - ); - } - - function buildIsNegative() { - const f = module.addFunction(prefix+"_isNegative"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - - f.addCode( - c.if( - c.call(f1mPrefix+"_isZero", x2), - c.if( - c.call(f1mPrefix+"_isZero", x1), - c.ret(c.call(f1mPrefix+"_isNegative", x0)), - c.ret(c.call(f1mPrefix+"_isNegative", x1)) - ) - ), - c.ret(c.call(f1mPrefix+"_isNegative", x2)) - ); - } - - - function buildMul() { - const f = module.addFunction(prefix+"_mul"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const cd = f.getCodeBuilder(); - - const a = cd.getLocal("x"); - const b = cd.i32_add(cd.getLocal("x"), cd.i32_const(f1n8)); - const c = cd.i32_add(cd.getLocal("x"), cd.i32_const(2*f1n8)); - const A = cd.getLocal("y"); - const B = cd.i32_add(cd.getLocal("y"), cd.i32_const(f1n8)); - const C = cd.i32_add(cd.getLocal("y"), cd.i32_const(2*f1n8)); - const r0 = cd.getLocal("r"); - const r1 = cd.i32_add(cd.getLocal("r"), cd.i32_const(f1n8)); - const r2 = cd.i32_add(cd.getLocal("r"), cd.i32_const(2*f1n8)); - - const aA = cd.i32_const(module.alloc(f1n8)); - const bB = cd.i32_const(module.alloc(f1n8)); - const cC = cd.i32_const(module.alloc(f1n8)); - const a_b = cd.i32_const(module.alloc(f1n8)); - const A_B = cd.i32_const(module.alloc(f1n8)); - const a_c = cd.i32_const(module.alloc(f1n8)); - const A_C = cd.i32_const(module.alloc(f1n8)); - const b_c = cd.i32_const(module.alloc(f1n8)); - const B_C = cd.i32_const(module.alloc(f1n8)); - const aA_bB = cd.i32_const(module.alloc(f1n8)); - const aA_cC = cd.i32_const(module.alloc(f1n8)); - const bB_cC = cd.i32_const(module.alloc(f1n8)); - const AUX = cd.i32_const(module.alloc(f1n8)); - - - f.addCode( - cd.call(f1mPrefix + "_mul", a, A, aA), - cd.call(f1mPrefix + "_mul", b, B, bB), - cd.call(f1mPrefix + "_mul", c, C, cC), - - cd.call(f1mPrefix + "_add", a, b, a_b), - cd.call(f1mPrefix + "_add", A, B, A_B), - cd.call(f1mPrefix + "_add", a, c, a_c), - cd.call(f1mPrefix + "_add", A, C, A_C), - cd.call(f1mPrefix + "_add", b, c, b_c), - cd.call(f1mPrefix + "_add", B, C, B_C), - - cd.call(f1mPrefix + "_add", aA, bB, aA_bB), - cd.call(f1mPrefix + "_add", aA, cC, aA_cC), - cd.call(f1mPrefix + "_add", bB, cC, bB_cC), - - cd.call(f1mPrefix + "_mul", b_c, B_C, r0), - cd.call(f1mPrefix + "_sub", r0, bB_cC, r0), - cd.call(mulNonResidueFn, r0, r0), - cd.call(f1mPrefix + "_add", aA, r0, r0), - - cd.call(f1mPrefix + "_mul", a_b, A_B, r1), - cd.call(f1mPrefix + "_sub", r1, aA_bB, r1), - cd.call(mulNonResidueFn, cC, AUX), - cd.call(f1mPrefix + "_add", r1, AUX, r1), - - cd.call(f1mPrefix + "_mul", a_c, A_C, r2), - cd.call(f1mPrefix + "_sub", r2, aA_cC, r2), - cd.call(f1mPrefix + "_add", r2, bB, r2), - ); - - } - - function buildSquare() { - const f = module.addFunction(prefix+"_square"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const A = c.getLocal("x"); - const B = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const C = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - const s0 = c.i32_const(module.alloc(f1n8)); - const ab = c.i32_const(module.alloc(f1n8)); - const s1 = c.i32_const(module.alloc(f1n8)); - const s2 = c.i32_const(module.alloc(f1n8)); - const bc = c.i32_const(module.alloc(f1n8)); - const s3 = c.i32_const(module.alloc(f1n8)); - const s4 = c.i32_const(module.alloc(f1n8)); - - - f.addCode( - - c.call(f1mPrefix + "_square", A, s0), - c.call(f1mPrefix + "_mul", A, B, ab), - c.call(f1mPrefix + "_add", ab, ab, s1), - - c.call(f1mPrefix + "_sub", A, B, s2), - c.call(f1mPrefix + "_add", s2, C, s2), - c.call(f1mPrefix + "_square", s2, s2), - - c.call(f1mPrefix + "_mul", B, C, bc), - c.call(f1mPrefix + "_add", bc, bc, s3), - - c.call(f1mPrefix + "_square", C, s4), - - c.call(mulNonResidueFn, s3, r0), - c.call(f1mPrefix + "_add", s0, r0, r0), - - c.call(mulNonResidueFn, s4, r1), - c.call(f1mPrefix + "_add", s1, r1, r1), - - c.call(f1mPrefix + "_add", s0, s4, r2), - c.call(f1mPrefix + "_sub", s3, r2, r2), - c.call(f1mPrefix + "_add", s2, r2, r2), - c.call(f1mPrefix + "_add", s1, r2, r2), - ); - - } - - - function buildToMontgomery() { - const f = module.addFunction(prefix+"_toMontgomery"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_toMontgomery", x0, r0), - c.call(f1mPrefix+"_toMontgomery", x1, r1), - c.call(f1mPrefix+"_toMontgomery", x2, r2) - ); - } - - function buildFromMontgomery() { - const f = module.addFunction(prefix+"_fromMontgomery"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_fromMontgomery", x0, r0), - c.call(f1mPrefix+"_fromMontgomery", x1, r1), - c.call(f1mPrefix+"_fromMontgomery", x2, r2) - ); - } - - function buildCopy() { - const f = module.addFunction(prefix+"_copy"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_copy", x0, r0), - c.call(f1mPrefix+"_copy", x1, r1), - c.call(f1mPrefix+"_copy", x2, r2), - ); - } - - function buildZero() { - const f = module.addFunction(prefix+"_zero"); - f.addParam("x", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_zero", x0), - c.call(f1mPrefix+"_zero", x1), - c.call(f1mPrefix+"_zero", x2), - ); - } - - function buildOne() { - const f = module.addFunction(prefix+"_one"); - f.addParam("x", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_one", x0), - c.call(f1mPrefix+"_zero", x1), - c.call(f1mPrefix+"_zero", x2), - ); - } - - function buildEq() { - const f = module.addFunction(prefix+"_eq"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const y0 = c.getLocal("y"); - const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); - const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); - - f.addCode( - c.i32_and( - c.i32_and( - c.call(f1mPrefix+"_eq", x0, y0), - c.call(f1mPrefix+"_eq", x1, y1), - ), - c.call(f1mPrefix+"_eq", x2, y2) - ) - ); - } - - function buildIsZero() { - const f = module.addFunction(prefix+"_isZero"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - - f.addCode( - c.i32_and( - c.i32_and( - c.call(f1mPrefix+"_isZero", x0), - c.call(f1mPrefix+"_isZero", x1) - ), - c.call(f1mPrefix+"_isZero", x2) - ) - ); - } - - function buildInverse() { - const f = module.addFunction(prefix+"_inverse"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - const t0 = c.i32_const(module.alloc(f1n8)); - const t1 = c.i32_const(module.alloc(f1n8)); - const t2 = c.i32_const(module.alloc(f1n8)); - const t3 = c.i32_const(module.alloc(f1n8)); - const t4 = c.i32_const(module.alloc(f1n8)); - const t5 = c.i32_const(module.alloc(f1n8)); - const c0 = c.i32_const(module.alloc(f1n8)); - const c1 = c.i32_const(module.alloc(f1n8)); - const c2 = c.i32_const(module.alloc(f1n8)); - const t6 = c.i32_const(module.alloc(f1n8)); - const AUX = c.i32_const(module.alloc(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_square", x0, t0), - c.call(f1mPrefix+"_square", x1, t1), - c.call(f1mPrefix+"_square", x2, t2), - c.call(f1mPrefix+"_mul", x0, x1, t3), - c.call(f1mPrefix+"_mul", x0, x2, t4), - c.call(f1mPrefix+"_mul", x1, x2, t5), - - c.call(mulNonResidueFn, t5, c0), - c.call(f1mPrefix+"_sub", t0, c0, c0), - - c.call(mulNonResidueFn, t2, c1), - c.call(f1mPrefix+"_sub", c1, t3, c1), - - c.call(f1mPrefix+"_sub", t1, t4, c2), - - c.call(f1mPrefix+"_mul", x2, c1, t6), - c.call(f1mPrefix+"_mul", x1, c2, AUX), - c.call(f1mPrefix+"_add", t6, AUX, t6), - c.call(mulNonResidueFn, t6, t6), - c.call(f1mPrefix+"_mul", x0, c0, AUX), - c.call(f1mPrefix+"_add", AUX, t6, t6), - - c.call(f1mPrefix+"_inverse", t6, t6), - - c.call(f1mPrefix+"_mul", t6, c0, r0), - c.call(f1mPrefix+"_mul", t6, c1, r1), - c.call(f1mPrefix+"_mul", t6, c2, r2) - ); - } - - - function buildSign() { - const f = module.addFunction(prefix+"_sign"); - f.addParam("x", "i32"); - f.addLocal("s", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - - f.addCode( - c.setLocal("s" , c.call( f1mPrefix + "_sign", x2)), - c.if( - c.getLocal("s"), - c.ret(c.getLocal("s")) - ), - c.setLocal("s" , c.call( f1mPrefix + "_sign", x1)), - c.if( - c.getLocal("s"), - c.ret(c.getLocal("s")) - ), - c.ret(c.call( f1mPrefix + "_sign", x0)) - ); - } - - function buildIsOne() { - const f = module.addFunction(prefix+"_isOne"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8*2)); - - f.addCode( - c.ret( - c.i32_and( - c.i32_and( - c.call(f1mPrefix + "_isOne", x0), - c.call(f1mPrefix + "_isZero", x1) - ), - c.call(f1mPrefix + "_isZero", x2) - ) - ) - ); - } - - buildIsZero(); - buildIsOne(); - buildZero(); - buildOne(); - buildCopy(); - buildMul(); - buildSquare(); - buildAdd(); - buildSub(); - buildNeg(); - buildSign(); - buildToMontgomery(); - buildFromMontgomery(); - buildEq(); - buildInverse(); - buildTimesScalar(); - buildIsNegative(); - - module.exportFunction(prefix + "_isZero"); - module.exportFunction(prefix + "_isOne"); - module.exportFunction(prefix + "_zero"); - module.exportFunction(prefix + "_one"); - module.exportFunction(prefix + "_copy"); - module.exportFunction(prefix + "_mul"); - module.exportFunction(prefix + "_square"); - module.exportFunction(prefix + "_add"); - module.exportFunction(prefix + "_sub"); - module.exportFunction(prefix + "_neg"); - module.exportFunction(prefix + "_sign"); - module.exportFunction(prefix + "_fromMontgomery"); - module.exportFunction(prefix + "_toMontgomery"); - module.exportFunction(prefix + "_eq"); - module.exportFunction(prefix + "_inverse"); - buildBatchInverse(module, prefix); - buildExp( - module, - prefix + "_exp", - f1n8*3, - prefix + "_mul", - prefix + "_square", - prefix + "_copy", - prefix + "_one" - ); - module.exportFunction(prefix + "_exp"); - module.exportFunction(prefix + "_timesScalar"); - module.exportFunction(prefix + "_batchInverse"); - module.exportFunction(prefix + "_isNegative"); - - return prefix; -}; - - -/***/ }), - -/***/ 93911: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -const bigInt = __webpack_require__(92096); -const utils = __webpack_require__(12333); - -module.exports = function buildFFT(module, prefix, gPrefix, fPrefix, opGtimesF) { +var build_fft = function buildFFT(module, prefix, gPrefix, fPrefix, opGtimesF) { const n64f = module.modules[fPrefix].n64; const n8f = n64f*8; @@ -119122,61 +119565,61 @@ module.exports = function buildFFT(module, prefix, gPrefix, fPrefix, opGtimesF) const q = module.modules[fPrefix].q; - let rem = q.minus(bigInt(1)); + let rem = q - 1n; let maxBits = 0; - while (!rem.isOdd()) { + while (!isOdd$2(rem)) { maxBits ++; - rem = rem.shiftRight(1); + rem = rem >> 1n; } - let nr = bigInt(2); + let nr = 2n; - while ( nr.modPow(q.shiftRight(1), q).equals(1) ) nr = nr.add(1); + while ( modPow(nr, q >> 1n, q) === 1n ) nr = nr + 1n; // console.log(nr); const w = new Array(maxBits+1); - w[maxBits] = nr.modPow(rem, q); + w[maxBits] = modPow(nr, rem, q); let n=maxBits-1; while (n>=0) { - w[n] = w[n+1].modPow(2, q); + w[n] = modPow(w[n+1], 2n, q); n--; } const bytes = []; - const R = bigInt(1).shiftLeft(n8f*8).mod(q); + const R = (1n << BigInt(n8f*8)) % q; for (let i=0; i { - /* Copyright 2019 0KIMS association. @@ -120482,1581 +120919,7 @@ module.exports = function buildFFT(module, prefix, gPrefix, fPrefix, opGtimesF) along with wasmsnark. If not, see . */ -const utils = __webpack_require__(12333); - -module.exports = function buildInt(module, n64, _prefix) { - - const prefix = _prefix || "int"; - if (module.modules[prefix]) return prefix; // already builded - module.modules[prefix] = {}; - - const n32 = n64*2; - const n8 = n64*8; - - const one = module.alloc(n8, utils.bigInt2BytesLE(1, n8)); - - function buildCopy() { - const f = module.addFunction(prefix+"_copy"); - f.addParam("px", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - for (let i=0; i>1) )&&(i>1, k>>1) - ) - ) - ); - - f.addCode( - c.setLocal(c1, - c.i64_add( - c.getLocal(c1), - c.i64_shr_u( - c.getLocal(c0), - c.i64_const(32) - ) - ) - ) - ); - } - - // Add the old carry - - if (k>0) { - f.addCode( - c.setLocal(c0, - c.i64_add( - c.i64_and( - c.getLocal(c0), - c.i64_const(0xFFFFFFFF) - ), - c.i64_and( - c.getLocal(c0_old), - c.i64_const(0xFFFFFFFF) - ), - ) - ) - ); - - f.addCode( - c.setLocal(c1, - c.i64_add( - c.i64_add( - c.getLocal(c1), - c.i64_shr_u( - c.getLocal(c0), - c.i64_const(32) - ) - ), - c.getLocal(c1_old) - ) - ) - ); - } - - f.addCode( - c.i64_store32( - c.getLocal("r"), - k*4, - c.getLocal(c0) - ) - ); - - f.addCode( - c.setLocal( - c0_old, - c.getLocal(c1) - ), - c.setLocal( - c1_old, - c.i64_shr_u( - c.getLocal(c0_old), - c.i64_const(32) - ) - ) - ); - - } - f.addCode( - c.i64_store32( - c.getLocal("r"), - n32*4*2-4, - c.getLocal(c0_old) - ) - ); - - } - - - function buildSquareOld() { - const f = module.addFunction(prefix+"_squareOld"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); - } - - function _buildMul1() { - const f = module.addFunction(prefix+"__mul1"); - f.addParam("px", "i32"); - f.addParam("y", "i64"); - f.addParam("pr", "i32"); - f.addLocal("c", "i64"); - - const c = f.getCodeBuilder(); - - f.addCode(c.setLocal( - "c", - c.i64_mul( - c.i64_load32_u(c.getLocal("px"), 0, 0), - c.getLocal("y") - ) - )); - - f.addCode(c.i64_store32( - c.getLocal("pr"), - 0, - 0, - c.getLocal("c"), - )); - - for (let i=1; i3)&&(Y[eY]==0) ey--; - f.addCode(c.block(c.loop( - c.br_if( - 1, - c.i32_or( - c.i32_load8_u( - c.i32_add(Y , c.getLocal("eY")), - 0, - 0 - ), - c.i32_eq( - c.getLocal("eY"), - c.i32_const(3) - ) - ) - ), - c.setLocal("eY", c.i32_sub(c.getLocal("eY"), c.i32_const(1))), - c.br(0) - ))); - - f.addCode( - c.setLocal( - "sy", - c.i64_add( - c.i64_load32_u( - c.i32_sub( - c.i32_add( Y, c.getLocal("eY")), - c.i32_const(3) - ), - 0, - 0 - ), - c.i64_const(1) - ) - ) - ); - - // Force a divide by 0 if quotien is 0 - f.addCode( - c.if( - c.i64_eq( - c.getLocal("sy"), - c.i64_const(1) - ), - c.drop(c.i64_div_u(c.i64_const(0), c.i64_const(0))) - ) - ); - - f.addCode(c.block(c.loop( - - // while (eX>7)&&(Y[eX]==0) ex--; - c.block(c.loop( - c.br_if( - 1, - c.i32_or( - c.i32_load8_u( - c.i32_add(R , c.getLocal("eX")), - 0, - 0 - ), - c.i32_eq( - c.getLocal("eX"), - c.i32_const(7) - ) - ) - ), - c.setLocal("eX", c.i32_sub(c.getLocal("eX"), c.i32_const(1))), - c.br(0) - )), - - c.setLocal( - "sx", - c.i64_load( - c.i32_sub( - c.i32_add( R, c.getLocal("eX")), - c.i32_const(7) - ), - 0, - 0 - ) - ), - - c.setLocal( - "sx", - c.i64_div_u( - c.getLocal("sx"), - c.getLocal("sy") - ) - ), - c.setLocal( - "ec", - c.i32_sub( - c.i32_sub( - c.getLocal("eX"), - c.getLocal("eY") - ), - c.i32_const(4) - ) - ), - - // While greater than 32 bits or ec is neg, shr and inc exp - c.block(c.loop( - c.br_if( - 1, - c.i32_and( - c.i64_eqz( - c.i64_and( - c.getLocal("sx"), - c.i64_const("0xFFFFFFFF00000000") - ) - ), - c.i32_ge_s( - c.getLocal("ec"), - c.i32_const(0) - ) - ) - ), - - c.setLocal( - "sx", - c.i64_shr_u( - c.getLocal("sx"), - c.i64_const(8) - ) - ), - - c.setLocal( - "ec", - c.i32_add( - c.getLocal("ec"), - c.i32_const(1) - ) - ), - c.br(0) - )), - - c.if( - c.i64_eqz(c.getLocal("sx")), - [ - ...c.br_if( - 2, - c.i32_eqz(c.call(prefix + "_gte", R, Y)) - ), - ...c.setLocal("sx", c.i64_const(1)), - ...c.setLocal("ec", c.i32_const(0)) - ] - ), - - c.call(prefix + "__mul1", Y, c.getLocal("sx"), R2), - c.drop(c.call( - prefix + "_sub", - R, - c.i32_sub(R2, c.getLocal("ec")), - R - )), - c.call( - prefix + "__add1", - c.i32_add(C, c.getLocal("ec")), - c.getLocal("sx") - ), - c.br(0) - ))); - } - - function buildInverseMod() { - - const f = module.addFunction(prefix+"_inverseMod"); - f.addParam("px", "i32"); - f.addParam("pm", "i32"); - f.addParam("pr", "i32"); - f.addLocal("t", "i32"); - f.addLocal("newt", "i32"); - f.addLocal("r", "i32"); - f.addLocal("qq", "i32"); - f.addLocal("qr", "i32"); - f.addLocal("newr", "i32"); - f.addLocal("swp", "i32"); - f.addLocal("x", "i32"); - f.addLocal("signt", "i32"); - f.addLocal("signnewt", "i32"); - f.addLocal("signx", "i32"); - - const c = f.getCodeBuilder(); - - const aux1 = c.i32_const(module.alloc(n8)); - const aux2 = c.i32_const(module.alloc(n8)); - const aux3 = c.i32_const(module.alloc(n8)); - const aux4 = c.i32_const(module.alloc(n8)); - const aux5 = c.i32_const(module.alloc(n8)); - const aux6 = c.i32_const(module.alloc(n8)); - const mulBuff = c.i32_const(module.alloc(n8*2)); - const aux7 = c.i32_const(module.alloc(n8)); - - f.addCode( - c.setLocal("t", aux1), - c.call(prefix + "_zero", aux1), - c.setLocal("signt", c.i32_const(0)), - ); - - f.addCode( - c.setLocal("r", aux2), - c.call(prefix + "_copy", c.getLocal("pm"), aux2) - ); - - f.addCode( - c.setLocal("newt", aux3), - c.call(prefix + "_one", aux3), - c.setLocal("signnewt", c.i32_const(0)), - ); - - f.addCode( - c.setLocal("newr", aux4), - c.call(prefix + "_copy", c.getLocal("px"), aux4) - ); - - - - - f.addCode(c.setLocal("qq", aux5)); - f.addCode(c.setLocal("qr", aux6)); - f.addCode(c.setLocal("x", aux7)); - - f.addCode(c.block(c.loop( - c.br_if( - 1, - c.call(prefix + "_isZero", c.getLocal("newr") ) - ), - c.call(prefix + "_div", c.getLocal("r"), c.getLocal("newr"), c.getLocal("qq"), c.getLocal("qr")), - - c.call(prefix + "_mul", c.getLocal("qq"), c.getLocal("newt"), mulBuff), - - c.if( - c.getLocal("signt"), - c.if( - c.getLocal("signnewt"), - c.if ( - c.call(prefix + "_gte", mulBuff, c.getLocal("t")), - [ - ...c.drop(c.call(prefix + "_sub", mulBuff, c.getLocal("t"), c.getLocal("x"))), - ...c.setLocal("signx", c.i32_const(0)) - ], - [ - ...c.drop(c.call(prefix + "_sub", c.getLocal("t"), mulBuff, c.getLocal("x"))), - ...c.setLocal("signx", c.i32_const(1)) - ], - ), - [ - ...c.drop(c.call(prefix + "_add", mulBuff, c.getLocal("t"), c.getLocal("x"))), - ...c.setLocal("signx", c.i32_const(1)) - ] - ), - c.if( - c.getLocal("signnewt"), - [ - ...c.drop(c.call(prefix + "_add", mulBuff, c.getLocal("t"), c.getLocal("x"))), - ...c.setLocal("signx", c.i32_const(0)) - ], - c.if ( - c.call(prefix + "_gte", c.getLocal("t"), mulBuff), - [ - ...c.drop(c.call(prefix + "_sub", c.getLocal("t"), mulBuff, c.getLocal("x"))), - ...c.setLocal("signx", c.i32_const(0)) - ], - [ - ...c.drop(c.call(prefix + "_sub", mulBuff, c.getLocal("t"), c.getLocal("x"))), - ...c.setLocal("signx", c.i32_const(1)) - ] - ) - ) - ), - - c.setLocal("swp", c.getLocal("t")), - c.setLocal("t", c.getLocal("newt")), - c.setLocal("newt", c.getLocal("x")), - c.setLocal("x", c.getLocal("swp")), - - c.setLocal("signt", c.getLocal("signnewt")), - c.setLocal("signnewt", c.getLocal("signx")), - - c.setLocal("swp", c.getLocal("r")), - c.setLocal("r", c.getLocal("newr")), - c.setLocal("newr", c.getLocal("qr")), - c.setLocal("qr", c.getLocal("swp")), - - c.br(0) - ))); - - f.addCode(c.if( - c.getLocal("signt"), - c.drop(c.call(prefix + "_sub", c.getLocal("pm"), c.getLocal("t"), c.getLocal("pr"))), - c.call(prefix + "_copy", c.getLocal("t"), c.getLocal("pr")) - )); - } - - - buildCopy(); - buildZero(); - buildIsZero(); - buildOne(); - buildEq(); - buildGte(); - buildAdd(); - buildSub(); - buildMul(); - buildSquare(); - buildSquareOld(); - buildDiv(); - buildInverseMod(); - module.exportFunction(prefix+"_copy"); - module.exportFunction(prefix+"_zero"); - module.exportFunction(prefix+"_one"); - module.exportFunction(prefix+"_isZero"); - module.exportFunction(prefix+"_eq"); - module.exportFunction(prefix+"_gte"); - module.exportFunction(prefix+"_add"); - module.exportFunction(prefix+"_sub"); - module.exportFunction(prefix+"_mul"); - module.exportFunction(prefix+"_square"); - module.exportFunction(prefix+"_squareOld"); - module.exportFunction(prefix+"_div"); - module.exportFunction(prefix+"_inverseMod"); - - return prefix; -}; - - -/***/ }), - -/***/ 74911: -/***/ ((module) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -module.exports = function buildMultiexp(module, prefix, fnName, opAdd, n8b) { - - const n64g = module.modules[prefix].n64; - const n8g = n64g*8; - - function buildGetChunk() { - const f = module.addFunction(fnName + "_getChunk"); - f.addParam("pScalar", "i32"); - f.addParam("scalarSize", "i32"); // Number of bytes of the scalar - f.addParam("startBit", "i32"); // Bit to start extract - f.addParam("chunkSize", "i32"); // Chunk size in bits - f.addLocal("bitsToEnd", "i32"); - f.addLocal("mask", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.setLocal("bitsToEnd", - c.i32_sub( - c.i32_mul( - c.getLocal("scalarSize"), - c.i32_const(8) - ), - c.getLocal("startBit") - ) - ), - c.if( - c.i32_gt_s( - c.getLocal("chunkSize"), - c.getLocal("bitsToEnd") - ), - c.setLocal( - "mask", - c.i32_sub( - c.i32_shl( - c.i32_const(1), - c.getLocal("bitsToEnd") - ), - c.i32_const(1) - ) - ), - c.setLocal( - "mask", - c.i32_sub( - c.i32_shl( - c.i32_const(1), - c.getLocal("chunkSize") - ), - c.i32_const(1) - ) - ) - ), - c.i32_and( - c.i32_shr_u( - c.i32_load( - c.i32_add( - c.getLocal("pScalar"), - c.i32_shr_u( - c.getLocal("startBit"), - c.i32_const(3) - ) - ), - 0, // offset - 0 // align to byte. - ), - c.i32_and( - c.getLocal("startBit"), - c.i32_const(0x7) - ) - ), - c.getLocal("mask") - ) - ); - } - - function buildMutiexpChunk() { - const f = module.addFunction(fnName + "_chunk"); - f.addParam("pBases", "i32"); - f.addParam("pScalars", "i32"); - f.addParam("scalarSize", "i32"); // Number of points - f.addParam("n", "i32"); // Number of points - f.addParam("startBit", "i32"); // bit where it starts the chunk - f.addParam("chunkSize", "i32"); // bit where it starts the chunk - f.addParam("pr", "i32"); - f.addLocal("nChunks", "i32"); - f.addLocal("itScalar", "i32"); - f.addLocal("endScalar", "i32"); - f.addLocal("itBase", "i32"); - f.addLocal("i", "i32"); - f.addLocal("j", "i32"); - f.addLocal("nTable", "i32"); - f.addLocal("pTable", "i32"); - f.addLocal("idx", "i32"); - f.addLocal("pIdxTable", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.if( - c.i32_eqz(c.getLocal("n")), - [ - ...c.call(prefix + "_zero", c.getLocal("pr")), - ...c.ret([]) - ] - ), - - // Allocate memory - - c.setLocal( - "nTable", - c.i32_shl( - c.i32_const(1), - c.getLocal("chunkSize") - ) - ), - c.setLocal("pTable", c.i32_load( c.i32_const(0) )), - c.i32_store( - c.i32_const(0), - c.i32_add( - c.getLocal("pTable"), - c.i32_mul( - c.getLocal("nTable"), - c.i32_const(n8g) - ) - ) - ), - - // Reset Table - c.setLocal("j", c.i32_const(0)), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("j"), - c.getLocal("nTable") - ) - ), - - c.call( - prefix + "_zero", - c.i32_add( - c.getLocal("pTable"), - c.i32_mul( - c.getLocal("j"), - c.i32_const(n8g) - ) - ) - ), - - c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), - c.br(0) - )), - - // Distribute elements - c.setLocal("itBase", c.getLocal("pBases")), - c.setLocal("itScalar", c.getLocal("pScalars")), - c.setLocal("endScalar", - c.i32_add( - c.getLocal("pScalars"), - c.i32_mul( - c.getLocal("n"), - c.getLocal("scalarSize") - ) - ) - ), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("itScalar"), - c.getLocal("endScalar") - ) - ), - - c.setLocal( - "idx", - c.call(fnName + "_getChunk", - c.getLocal("itScalar"), - c.getLocal("scalarSize"), - c.getLocal("startBit"), - c.getLocal("chunkSize") - ) - ), - - c.if( - c.getLocal("idx"), - [ - ...c.setLocal( - "pIdxTable", - c.i32_add( - c.getLocal("pTable"), - c.i32_mul( - c.i32_sub( - c.getLocal("idx"), - c.i32_const(1) - ), - c.i32_const(n8g) - ) - ) - ), - ...c.call( - opAdd, - c.getLocal("pIdxTable"), - c.getLocal("itBase"), - c.getLocal("pIdxTable"), - ) - ] - ), - - c.setLocal("itScalar", c.i32_add(c.getLocal("itScalar"), c.getLocal("scalarSize"))), - c.setLocal("itBase", c.i32_add(c.getLocal("itBase"), c.i32_const(n8b))), - c.br(0) - )), - - c.call(fnName + "_reduceTable", c.getLocal("pTable"), c.getLocal("chunkSize")), - c.call( - prefix + "_copy", - c.getLocal("pTable"), - c.getLocal("pr") - ), - - - c.i32_store( - c.i32_const(0), - c.getLocal("pTable") - ) - - ); - } - - function buildMultiexp() { - const f = module.addFunction(fnName); - f.addParam("pBases", "i32"); - f.addParam("pScalars", "i32"); - f.addParam("scalarSize", "i32"); // Number of points - f.addParam("n", "i32"); // Number of points - f.addParam("pr", "i32"); - f.addLocal("chunkSize", "i32"); - f.addLocal("nChunks", "i32"); - f.addLocal("itScalar", "i32"); - f.addLocal("endScalar", "i32"); - f.addLocal("itBase", "i32"); - f.addLocal("itBit", "i32"); - f.addLocal("i", "i32"); - f.addLocal("j", "i32"); - f.addLocal("nTable", "i32"); - f.addLocal("pTable", "i32"); - f.addLocal("idx", "i32"); - f.addLocal("pIdxTable", "i32"); - - const c = f.getCodeBuilder(); - - const aux = c.i32_const(module.alloc(n8g)); - - const pTSizes = module.alloc([ - 17, 17, 17, 17, 17, 17, 17, 17, - 17, 17, 16, 16, 15, 14, 13, 13, - 12, 11, 10, 9, 8, 7, 7, 6, - 5 , 4, 3, 2, 1, 1, 1, 1 - ]); - - f.addCode( - c.call(prefix + "_zero", c.getLocal("pr")), - c.if( - c.i32_eqz(c.getLocal("n")), - c.ret([]) - ), - c.setLocal("chunkSize", c.i32_load8_u( c.i32_clz(c.getLocal("n")), pTSizes )), - c.setLocal( - "nChunks", - c.i32_add( - c.i32_div_u( - c.i32_sub( - c.i32_shl( - c.getLocal("scalarSize"), - c.i32_const(3) - ), - c.i32_const(1) - ), - c.getLocal("chunkSize") - ), - c.i32_const(1) - ) - ), - - - // Allocate memory - - c.setLocal( - "itBit", - c.i32_mul( - c.i32_sub( - c.getLocal("nChunks"), - c.i32_const(1) - ), - c.getLocal("chunkSize") - ) - ), - c.block(c.loop( - c.br_if( - 1, - c.i32_lt_s( - c.getLocal("itBit"), - c.i32_const(0) - ) - ), - - // Double nChunk times - c.if( - c.i32_eqz(c.call(prefix + "_isZero", c.getLocal("pr"))), - [ - ...c.setLocal("j", c.i32_const(0)), - ...c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("j"), - c.getLocal("chunkSize") - ) - ), - - c.call(prefix + "_double", c.getLocal("pr"), c.getLocal("pr")), - - c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), - c.br(0) - )) - ] - ), - - c.call( - fnName + "_chunk", - c.getLocal("pBases"), - c.getLocal("pScalars"), - c.getLocal("scalarSize"), - c.getLocal("n"), - c.getLocal("itBit"), - c.getLocal("chunkSize"), - aux - ), - - c.call( - prefix + "_add", - c.getLocal("pr"), - aux, - c.getLocal("pr") - ), - c.setLocal("itBit", c.i32_sub(c.getLocal("itBit"), c.getLocal("chunkSize"))), - c.br(0) - )) - ); - } - - function buildReduceTable() { - const f = module.addFunction(fnName + "_reduceTable"); - f.addParam("pTable", "i32"); - f.addParam("p", "i32"); // Number of bits of the table - f.addLocal("half", "i32"); - f.addLocal("it1", "i32"); - f.addLocal("it2", "i32"); - f.addLocal("pAcc", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.if( - c.i32_eq(c.getLocal("p"), c.i32_const(1)), - c.ret([]) - ), - c.setLocal( - "half", - c.i32_shl( - c.i32_const(1), - c.i32_sub( - c.getLocal("p"), - c.i32_const(1) - ) - ) - ), - - c.setLocal("it1", c.getLocal("pTable")), - c.setLocal( - "it2", - c.i32_add( - c.getLocal("pTable"), - c.i32_mul( - c.getLocal("half"), - c.i32_const(n8g) - ) - ) - ), - c.setLocal("pAcc", - c.i32_sub( - c.getLocal("it2"), - c.i32_const(n8g) - ) - ), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("it1"), - c.getLocal("pAcc") - ) - ), - c.call( - prefix + "_add", - c.getLocal("it1"), - c.getLocal("it2"), - c.getLocal("it1") - ), - c.call( - prefix + "_add", - c.getLocal("pAcc"), - c.getLocal("it2"), - c.getLocal("pAcc") - ), - c.setLocal("it1", c.i32_add(c.getLocal("it1"), c.i32_const(n8g))), - c.setLocal("it2", c.i32_add(c.getLocal("it2"), c.i32_const(n8g))), - c.br(0) - )), - - c.call( - fnName + "_reduceTable", - c.getLocal("pTable"), - c.i32_sub( - c.getLocal("p"), - c.i32_const(1) - ) - ), - - c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), - c.block(c.loop( - c.br_if(1, c.i32_eqz(c.getLocal("p"))), - c.call(prefix + "_double", c.getLocal("pAcc"), c.getLocal("pAcc")), - c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), - c.br(0) - )), - - c.call(prefix + "_add", c.getLocal("pTable"), c.getLocal("pAcc"), c.getLocal("pTable")) - ); - } - - buildGetChunk(); - buildReduceTable(); - buildMutiexpChunk(); - buildMultiexp(); - - module.exportFunction(fnName); - module.exportFunction(fnName +"_chunk"); - - -}; - - - - - -/***/ }), - -/***/ 2896: -/***/ ((module) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -module.exports = function buildPol(module, prefix, prefixField) { +var build_pol = function buildPol(module, prefix, prefixField) { const n64 = module.modules[prefixField].n64; const n8 = n64*8; @@ -122196,14 +121059,7 @@ module.exports = function buildPol(module, prefix, prefixField) { }; - -/***/ }), - -/***/ 10637: -/***/ ((module) => { - - -module.exports = function buildQAP(module, prefix, prefixField) { +var build_qap = function buildQAP(module, prefix, prefixField) { const n64 = module.modules[prefixField].n64; const n8 = n64*8; @@ -122540,13 +121396,6 @@ module.exports = function buildQAP(module, prefix, prefixField) { }; - - -/***/ }), - -/***/ 50345: -/***/ ((module) => { - /* Copyright 2019 0KIMS association. @@ -122566,320 +121415,3090 @@ module.exports = function buildQAP(module, prefix, prefixField) { along with wasmsnark. If not, see . */ -module.exports = function buildTimesScalar(module, fnName, elementLen, opAB, opAA, opCopy, opInit) { +var build_applykey = function buildApplyKey(module, fnName, gPrefix, frPrefix, sizeGIn, sizeGOut, sizeF, opGtimesF) { const f = module.addFunction(fnName); - f.addParam("base", "i32"); - f.addParam("scalar", "i32"); - f.addParam("scalarLength", "i32"); - f.addParam("r", "i32"); + f.addParam("pIn", "i32"); + f.addParam("n", "i32"); + f.addParam("pFirst", "i32"); + f.addParam("pInc", "i32"); + f.addParam("pOut", "i32"); + f.addLocal("pOldFree", "i32"); f.addLocal("i", "i32"); - f.addLocal("b", "i32"); + f.addLocal("pFrom", "i32"); + f.addLocal("pTo", "i32"); const c = f.getCodeBuilder(); - const aux = c.i32_const(module.alloc(elementLen)); + const t = c.i32_const(module.alloc(sizeF)); f.addCode( - c.if( - c.i32_eqz(c.getLocal("scalarLength")), - [ - ...c.call(opInit, c.getLocal("r")), - ...c.ret([]) - ] + c.setLocal("pFrom", c.getLocal("pIn")), + c.setLocal("pTo", c.getLocal("pOut")), + ); + + // t = first + f.addCode( + c.call( + frPrefix + "_copy", + c.getLocal("pFirst"), + t ) ); - f.addCode(c.call(opCopy, c.getLocal("base"), aux)); - f.addCode(c.call(opInit, c.getLocal("r"))); - f.addCode(c.setLocal("i", c.getLocal("scalarLength"))); - f.addCode(c.block(c.loop( - c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - - c.setLocal( - "b", - c.i32_load8_u( - c.i32_add( - c.getLocal("scalar"), - c.getLocal("i") - ) - ) - ), - ...innerLoop(), - c.br_if(1, c.i32_eqz ( c.getLocal("i") )), - c.br(0) - ))); - - - function innerLoop() { - const code = []; - for (let i=0; i<8; i++) { - code.push( - ...c.call(opAA, c.getLocal("r"), c.getLocal("r")), - ...c.if( - c.i32_ge_u( c.getLocal("b"), c.i32_const(0x80 >> i)), - [ - ...c.setLocal( - "b", - c.i32_sub( - c.getLocal("b"), - c.i32_const(0x80 >> i) - ) - ), - ...c.call(opAB, c.getLocal("r"),aux, c.getLocal("r")) - ] - ) - ); - } - return code; - } - -}; - - -/***/ }), - -/***/ 33972: -/***/ ((module) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -module.exports = function buildTimesScalarNAF(module, fnName, elementLen, opAB, opAA, opAmB, opCopy, opInit) { - - const f = module.addFunction(fnName); - f.addParam("base", "i32"); - f.addParam("scalar", "i32"); - f.addParam("scalarLength", "i32"); - f.addParam("r", "i32"); - f.addLocal("old0", "i32"); - f.addLocal("nbits", "i32"); - f.addLocal("i", "i32"); - f.addLocal("last", "i32"); - f.addLocal("cur", "i32"); - f.addLocal("carry", "i32"); - f.addLocal("p", "i32"); - - const c = f.getCodeBuilder(); - - const aux = c.i32_const(module.alloc(elementLen)); - - function getBit(IDX) { - return c.i32_and( - c.i32_shr_u( - c.i32_load( - c.i32_add( - c.getLocal("scalar"), - c.i32_and( - c.i32_shr_u( - IDX, - c.i32_const(3) - ), - c.i32_const(0xFFFFFFFC) - ) - ) - ), - c.i32_and( - IDX, - c.i32_const(0x1F) - ) - ), - c.i32_const(1) - ); - } - - function pushBit(b) { - return [ - ...c.i32_store8( - c.getLocal("p"), - c.i32_const(b) - ), - ...c.setLocal( - "p", - c.i32_add( - c.getLocal("p"), - c.i32_const(1) - ) - ) - ]; - } - f.addCode( - c.if( - c.i32_eqz(c.getLocal("scalarLength")), - [ - ...c.call(opInit, c.getLocal("r")), - ...c.ret([]) - ] - ), - c.setLocal("nbits", c.i32_shl(c.getLocal("scalarLength"), c.i32_const(3))), - c.setLocal("old0", c.i32_load(c.i32_const(0))), - c.setLocal("p", c.getLocal("old0")), - c.i32_store( - c.i32_const(0), - c.i32_and( - c.i32_add( - c.i32_add( - c.getLocal("old0"), - c.i32_const(32) - ), - c.getLocal("nbits") - ), - c.i32_const(0xFFFFFFF8) - ) - ), - c.setLocal("i", c.i32_const(1)), - - c.setLocal("last",getBit(c.i32_const(0))), - c.setLocal("carry",c.i32_const(0)), - + c.setLocal("i", c.i32_const(0)), c.block(c.loop( - c.br_if(1, c.i32_eq( c.getLocal("i"), c.getLocal("nbits"))), + c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), - c.setLocal("cur", getBit(c.getLocal("i"))), - c.if( c.getLocal("last"), - c.if( c.getLocal("cur"), - c.if(c.getLocal("carry"), - [ - ...c.setLocal("last", c.i32_const(0)), - ...c.setLocal("carry", c.i32_const(1)), - ...pushBit(1) - ] - , - [ - ...c.setLocal("last", c.i32_const(0)), - ...c.setLocal("carry", c.i32_const(1)), - ...pushBit(255) - ], - ), - c.if(c.getLocal("carry"), - [ - ...c.setLocal("last", c.i32_const(0)), - ...c.setLocal("carry", c.i32_const(1)), - ...pushBit(255) - ] - , - [ - ...c.setLocal("last", c.i32_const(0)), - ...c.setLocal("carry", c.i32_const(0)), - ...pushBit(1) - ], - ), - ), - c.if( c.getLocal("cur"), - c.if(c.getLocal("carry"), - [ - ...c.setLocal("last", c.i32_const(0)), - ...c.setLocal("carry", c.i32_const(1)), - ...pushBit(0) - ] - , - [ - ...c.setLocal("last", c.i32_const(1)), - ...c.setLocal("carry", c.i32_const(0)), - ...pushBit(0) - ], - ), - c.if(c.getLocal("carry"), - [ - ...c.setLocal("last", c.i32_const(1)), - ...c.setLocal("carry", c.i32_const(0)), - ...pushBit(0) - ] - , - [ - ...c.setLocal("last", c.i32_const(0)), - ...c.setLocal("carry", c.i32_const(0)), - ...pushBit(0) - ], - ), - ) + c.call( + opGtimesF, + c.getLocal("pFrom"), + t, + c.getLocal("pTo") + ), + c.setLocal("pFrom", c.i32_add(c.getLocal("pFrom"), c.i32_const(sizeGIn))), + c.setLocal("pTo", c.i32_add(c.getLocal("pTo"), c.i32_const(sizeGOut))), + + // t = t* inc + c.call( + frPrefix + "_mul", + t, + c.getLocal("pInc"), + t ), c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), c.br(0) - )), - - c.if( c.getLocal("last"), - c.if(c.getLocal("carry"), - [ - ...pushBit(255), - ...pushBit(0), - ...pushBit(1) - ] - , - [ - ...pushBit(1) - ], - ), - c.if(c.getLocal("carry"), - [ - ...pushBit(0), - ...pushBit(1) - ] - ), - ), - - c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), - - // p already points to the last bit - - c.call(opCopy, c.getLocal("base"), aux), - - c.call(opInit, c.getLocal("r")), - - c.block(c.loop( - - - c.call(opAA, c.getLocal("r"), c.getLocal("r")), - - - c.setLocal("cur", - c.i32_load8_u( - c.getLocal("p") - ) - ), - - c.if( - c.getLocal("cur"), - c.if( - c.i32_eq(c.getLocal("cur"), c.i32_const(1)), - c.call(opAB, c.getLocal("r"), aux, c.getLocal("r")), - c.call(opAmB, c.getLocal("r"), aux, c.getLocal("r")), - ) - ), - - c.br_if(1, c.i32_eq( c.getLocal("old0"), c.getLocal("p"))), - c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), - c.br(0) - - )), - - c.i32_store( c.i32_const(0), c.getLocal("old0")) - + )) ); + module.exportFunction(fnName); + }; +const utils$2 = utils$6; -/***/ }), +const buildF1m$1 =build_f1m; +const buildF1$1 =build_f1; +const buildF2m$1 =build_f2m; +const buildF3m$1 =build_f3m; +const buildCurve$1 =build_curve_jacobian_a0; +const buildFFT$2 = build_fft; +const buildPol$1 = build_pol; +const buildQAP$1 = build_qap; +const buildApplyKey$1 = build_applykey; +const { bitLength: bitLength$2, modInv, isOdd: isOdd$1, isNegative: isNegative$2 } = bigint; -/***/ 12333: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +var build_bn128 = function buildBN128(module, _prefix) { + + const prefix = _prefix || "bn128"; + + if (module.modules[prefix]) return prefix; // already builded + + const q = 21888242871839275222246405745257275088696311157297823662689037894645226208583n; + const r = 21888242871839275222246405745257275088548364400416034343698204186575808495617n; + + + const n64 = Math.floor((bitLength$2(q - 1n) - 1)/64) +1; + const n8 = n64*8; + const frsize = n8; + const f1size = n8; + const f2size = f1size * 2; + const ftsize = f1size * 12; + + const pr = module.alloc(utils$2.bigInt2BytesLE( r, frsize )); + + const f1mPrefix = buildF1m$1(module, q, "f1m"); + buildF1$1(module, r, "fr", "frm"); + + const pG1b = module.alloc(utils$2.bigInt2BytesLE( toMontgomery(3n), f1size )); + const g1mPrefix = buildCurve$1(module, "g1m", "f1m", pG1b); + + buildFFT$2(module, "frm", "frm", "frm", "frm_mul"); + + buildPol$1(module, "pol", "frm"); + buildQAP$1(module, "qap", "frm"); + + const f2mPrefix = buildF2m$1(module, "f1m_neg", "f2m", "f1m"); + const pG2b = module.alloc([ + ...utils$2.bigInt2BytesLE( toMontgomery(19485874751759354771024239261021720505790618469301721065564631296452457478373n), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(266929791119991161246907387137283842545076965332900288569378510910307636690n), f1size ) + ]); + const g2mPrefix = buildCurve$1(module, "g2m", "f2m", pG2b); + + + function buildGTimesFr(fnName, opMul) { + const f = module.addFunction(fnName); + f.addParam("pG", "i32"); + f.addParam("pFr", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.call("frm_fromMontgomery", c.getLocal("pFr"), AUX), + c.call( + opMul, + c.getLocal("pG"), + AUX, + c.i32_const(n8), + c.getLocal("pr") + ) + ); + + module.exportFunction(fnName); + } + buildGTimesFr("g1m_timesFr", "g1m_timesScalar"); + buildFFT$2(module, "g1m", "g1m", "frm", "g1m_timesFr"); + + buildGTimesFr("g2m_timesFr", "g2m_timesScalar"); + buildFFT$2(module, "g2m", "g2m", "frm", "g2m_timesFr"); + + buildGTimesFr("g1m_timesFrAffine", "g1m_timesScalarAffine"); + buildGTimesFr("g2m_timesFrAffine", "g2m_timesScalarAffine"); + + buildApplyKey$1(module, "frm_batchApplyKey", "fmr", "frm", n8, n8, n8, "frm_mul"); + buildApplyKey$1(module, "g1m_batchApplyKey", "g1m", "frm", n8*3, n8*3, n8, "g1m_timesFr"); + buildApplyKey$1(module, "g1m_batchApplyKeyMixed", "g1m", "frm", n8*2, n8*3, n8, "g1m_timesFrAffine"); + buildApplyKey$1(module, "g2m_batchApplyKey", "g2m", "frm", n8*2*3, n8*3*2, n8, "g2m_timesFr"); + buildApplyKey$1(module, "g2m_batchApplyKeyMixed", "g2m", "frm", n8*2*2, n8*3*2, n8, "g2m_timesFrAffine"); + + function toMontgomery(a) { + return BigInt(a) * ( 1n << BigInt(f1size*8)) % q; + } + + const G1gen = [ + 1n, + 2n, + 1n + ]; + + const pG1gen = module.alloc( + [ + ...utils$2.bigInt2BytesLE( toMontgomery(G1gen[0]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G1gen[1]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G1gen[2]), f1size ), + ] + ); + + const G1zero = [ + 0n, + 1n, + 0n + ]; + + const pG1zero = module.alloc( + [ + ...utils$2.bigInt2BytesLE( toMontgomery(G1zero[0]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G1zero[1]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G1zero[2]), f1size ) + ] + ); + + const G2gen = [ + [ + 10857046999023057135944570762232829481370756359578518086990519993285655852781n, + 11559732032986387107991004021392285783925812861821192530917403151452391805634n, + ],[ + 8495653923123431417604973247489272438418190587263600148770280649306958101930n, + 4082367875863433681332203403145435568316851327593401208105741076214120093531n, + ],[ + 1n, + 0n, + ] + ]; + + const pG2gen = module.alloc( + [ + ...utils$2.bigInt2BytesLE( toMontgomery(G2gen[0][0]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G2gen[0][1]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G2gen[1][0]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G2gen[1][1]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G2gen[2][0]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G2gen[2][1]), f1size ), + ] + ); + + const G2zero = [ + [ + 0n, + 0n, + ],[ + 1n, + 0n, + ],[ + 0n, + 0n, + ] + ]; + + const pG2zero = module.alloc( + [ + ...utils$2.bigInt2BytesLE( toMontgomery(G2zero[0][0]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G2zero[0][1]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G2zero[1][0]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G2zero[1][1]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G2zero[2][0]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G2zero[2][1]), f1size ), + ] + ); + + const pOneT = module.alloc([ + ...utils$2.bigInt2BytesLE( toMontgomery(1), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(0), f1size ), + ]); + + const pNonResidueF6 = module.alloc([ + ...utils$2.bigInt2BytesLE( toMontgomery(9), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(1), f1size ), + ]); + + const pTwoInv = module.alloc([ + ...utils$2.bigInt2BytesLE( toMontgomery( modInv(2n, q)), f1size ), + ...utils$2.bigInt2BytesLE( 0n, f1size ) + ]); + + const pAltBn128Twist = pNonResidueF6; + + const pTwistCoefB = module.alloc([ + ...utils$2.bigInt2BytesLE( toMontgomery(19485874751759354771024239261021720505790618469301721065564631296452457478373n), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(266929791119991161246907387137283842545076965332900288569378510910307636690n), f1size ), + ]); + + function build_mulNR6() { + const f = module.addFunction(prefix + "_mulNR6"); + f.addParam("x", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call( + f2mPrefix + "_mul", + c.i32_const(pNonResidueF6), + c.getLocal("x"), + c.getLocal("pr") + ) + ); + } + build_mulNR6(); + + const f6mPrefix = buildF3m$1(module, prefix+"_mulNR6", "f6m", "f2m"); + + function build_mulNR12() { + const f = module.addFunction(prefix + "_mulNR12"); + f.addParam("x", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call( + f2mPrefix + "_mul", + c.i32_const(pNonResidueF6), + c.i32_add(c.getLocal("x"), c.i32_const(n8*4)), + c.getLocal("pr") + ), + c.call( + f2mPrefix + "_copy", + c.getLocal("x"), + c.i32_add(c.getLocal("pr"), c.i32_const(n8*2)), + ), + c.call( + f2mPrefix + "_copy", + c.i32_add(c.getLocal("x"), c.i32_const(n8*2)), + c.i32_add(c.getLocal("pr"), c.i32_const(n8*4)), + ) + ); + } + build_mulNR12(); + + const ftmPrefix = buildF2m$1(module, prefix+"_mulNR12", "ftm", f6mPrefix); + + + const ateLoopCount = 29793968203157093288n; + const ateLoopBitBytes = bits(ateLoopCount); + const pAteLoopBitBytes = module.alloc(ateLoopBitBytes); + + const ateCoefSize = 3 * f2size; + const ateNDblCoefs = ateLoopBitBytes.length-1; + const ateNAddCoefs = ateLoopBitBytes.reduce((acc, b) => acc + ( b!=0 ? 1 : 0) ,0); + const ateNCoefs = ateNAddCoefs + ateNDblCoefs + 1; + const prePSize = 3*2*n8; + const preQSize = 3*n8*2 + ateNCoefs*ateCoefSize; + + + module.modules[prefix] = { + n64: n64, + pG1gen: pG1gen, + pG1zero: pG1zero, + pG1b: pG1b, + pG2gen: pG2gen, + pG2zero: pG2zero, + pG2b: pG2b, + pq: module.modules["f1m"].pq, + pr: pr, + pOneT: pOneT, + prePSize: prePSize, + preQSize: preQSize, + r: r.toString(), + q: q.toString() + }; + + // console.log("PrePSize: " +prePSize); + // console.log("PreQSize: " +preQSize); + + const finalExpZ = 4965661367192848881n; + + function naf(n) { + let E = n; + const res = []; + while (E > 0n) { + if (isOdd$1(E)) { + const z = 2 - Number(E % 4n); + res.push( z ); + E = E - BigInt(z); + } else { + res.push( 0 ); + } + E = E >> 1n; + } + return res; + } + + function bits(n) { + let E = n; + const res = []; + while (E > 0n) { + if (isOdd$1(E)) { + res.push( 1 ); + } else { + res.push( 0 ); + } + E = E >> 1n; + } + return res; + } + + function buildPrepareG1() { + const f = module.addFunction(prefix+ "_prepareG1"); + f.addParam("pP", "i32"); + f.addParam("ppreP", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(g1mPrefix + "_normalize", c.getLocal("pP"), c.getLocal("ppreP")), // TODO Remove if already in affine + ); + } + + function buildPrepAddStep() { + const f = module.addFunction(prefix+ "_prepAddStep"); + f.addParam("pQ", "i32"); + f.addParam("pR", "i32"); + f.addParam("pCoef", "i32"); + + const c = f.getCodeBuilder(); + + const X2 = c.getLocal("pQ"); + const Y2 = c.i32_add(c.getLocal("pQ"), c.i32_const(f2size)); + + const X1 = c.getLocal("pR"); + const Y1 = c.i32_add(c.getLocal("pR"), c.i32_const(f2size)); + const Z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*f2size)); + + const ELL_0 = c.getLocal("pCoef"); + const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); + const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); + + const D = ELL_VW; + const E = c.i32_const(module.alloc(f2size)); + const F = c.i32_const(module.alloc(f2size)); + const G = c.i32_const(module.alloc(f2size)); + const H = c.i32_const(module.alloc(f2size)); + const I = c.i32_const(module.alloc(f2size)); + const J = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + f.addCode( + // D = X1 - X2*Z1 + c.call(f2mPrefix + "_mul", X2, Z1, D), + c.call(f2mPrefix + "_sub", X1, D, D), + + // E = Y1 - Y2*Z1 + c.call(f2mPrefix + "_mul", Y2, Z1, E), + c.call(f2mPrefix + "_sub", Y1, E, E), + + // F = D^2 + c.call(f2mPrefix + "_square", D, F), + + // G = E^2 + c.call(f2mPrefix + "_square", E, G), + + // H = D*F + c.call(f2mPrefix + "_mul", D, F, H), + + // I = X1 * F + c.call(f2mPrefix + "_mul", X1, F, I), + + // J = H + Z1*G - (I+I) + c.call(f2mPrefix + "_add", I, I, AUX), + c.call(f2mPrefix + "_mul", Z1, G, J), + c.call(f2mPrefix + "_add", H, J, J), + c.call(f2mPrefix + "_sub", J, AUX, J), + + + // X3 (X1) = D*J + c.call(f2mPrefix + "_mul", D, J, X1), + + // Y3 (Y1) = E*(I-J)-(H*Y1) + c.call(f2mPrefix + "_mul", H, Y1, Y1), + c.call(f2mPrefix + "_sub", I, J, AUX), + c.call(f2mPrefix + "_mul", E, AUX, AUX), + c.call(f2mPrefix + "_sub", AUX, Y1, Y1), + + // Z3 (Z1) = Z1*H + c.call(f2mPrefix + "_mul", Z1, H, Z1), + + // ell_0 = xi * (E * X2 - D * Y2) + c.call(f2mPrefix + "_mul", D, Y2, AUX), + c.call(f2mPrefix + "_mul", E, X2, ELL_0), + c.call(f2mPrefix + "_sub", ELL_0, AUX, ELL_0), + c.call(f2mPrefix + "_mul", ELL_0, c.i32_const(pAltBn128Twist), ELL_0), + + + // ell_VV = - E (later: * xP) + c.call(f2mPrefix + "_neg", E, ELL_VV), + + // ell_VW = D (later: * yP ) + // Already assigned + + ); + } + + + + function buildPrepDoubleStep() { + const f = module.addFunction(prefix+ "_prepDblStep"); + f.addParam("pR", "i32"); + f.addParam("pCoef", "i32"); + + const c = f.getCodeBuilder(); + + const X1 = c.getLocal("pR"); + const Y1 = c.i32_add(c.getLocal("pR"), c.i32_const(f2size)); + const Z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*f2size)); + + const ELL_0 = c.getLocal("pCoef"); + const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); + const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); + + const A = c.i32_const(module.alloc(f2size)); + const B = c.i32_const(module.alloc(f2size)); + const C = c.i32_const(module.alloc(f2size)); + const D = c.i32_const(module.alloc(f2size)); + const E = c.i32_const(module.alloc(f2size)); + const F = c.i32_const(module.alloc(f2size)); + const G = c.i32_const(module.alloc(f2size)); + const H = c.i32_const(module.alloc(f2size)); + const I = c.i32_const(module.alloc(f2size)); + const J = c.i32_const(module.alloc(f2size)); + const E2 = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + f.addCode( + + // A = X1 * Y1 / 2 + c.call(f2mPrefix + "_mul", Y1, c.i32_const(pTwoInv), A), + c.call(f2mPrefix + "_mul", X1, A, A), + + // B = Y1^2 + c.call(f2mPrefix + "_square", Y1, B), + + // C = Z1^2 + c.call(f2mPrefix + "_square", Z1, C), + + // D = 3 * C + c.call(f2mPrefix + "_add", C, C, D), + c.call(f2mPrefix + "_add", D, C, D), + + // E = twist_b * D + c.call(f2mPrefix + "_mul", c.i32_const(pTwistCoefB), D, E), + + // F = 3 * E + c.call(f2mPrefix + "_add", E, E, F), + c.call(f2mPrefix + "_add", E, F, F), + + // G = (B+F)/2 + c.call(f2mPrefix + "_add", B, F, G), + c.call(f2mPrefix + "_mul", G, c.i32_const(pTwoInv), G), + + // H = (Y1+Z1)^2-(B+C) + c.call(f2mPrefix + "_add", B, C, AUX), + c.call(f2mPrefix + "_add", Y1, Z1, H), + c.call(f2mPrefix + "_square", H, H), + c.call(f2mPrefix + "_sub", H, AUX, H), + + // I = E-B + c.call(f2mPrefix + "_sub", E, B, I), + + // J = X1^2 + c.call(f2mPrefix + "_square", X1, J), + + // E_squared = E^2 + c.call(f2mPrefix + "_square", E, E2), + + // X3 (X1) = A * (B-F) + c.call(f2mPrefix + "_sub", B, F, AUX), + c.call(f2mPrefix + "_mul", A, AUX, X1), + + // Y3 (Y1) = G^2 - 3*E^2 + c.call(f2mPrefix + "_add", E2, E2, AUX), + c.call(f2mPrefix + "_add", E2, AUX, AUX), + c.call(f2mPrefix + "_square", G, Y1), + c.call(f2mPrefix + "_sub", Y1, AUX, Y1), + + // Z3 (Z1) = B * H + c.call(f2mPrefix + "_mul", B, H, Z1), + + // ell_0 = xi * I + c.call(f2mPrefix + "_mul", c.i32_const(pAltBn128Twist), I, ELL_0), + + // ell_VW = - H (later: * yP) + c.call(f2mPrefix + "_neg", H, ELL_VW), + + // ell_VV = 3*J (later: * xP) + c.call(f2mPrefix + "_add", J, J, ELL_VV), + c.call(f2mPrefix + "_add", J, ELL_VV, ELL_VV), + + ); + } + + function buildMulByQ() { + const f = module.addFunction(prefix + "_mulByQ"); + f.addParam("p1", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + const x = c.getLocal("p1"); + const y = c.i32_add(c.getLocal("p1"), c.i32_const(f2size)); + const z = c.i32_add(c.getLocal("p1"), c.i32_const(f2size*2)); + const x3 = c.getLocal("pr"); + const y3 = c.i32_add(c.getLocal("pr"), c.i32_const(f2size)); + const z3 = c.i32_add(c.getLocal("pr"), c.i32_const(f2size*2)); + + const MulByQX = c.i32_const(module.alloc([ + ...utils$2.bigInt2BytesLE( toMontgomery("21575463638280843010398324269430826099269044274347216827212613867836435027261"), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery("10307601595873709700152284273816112264069230130616436755625194854815875713954"), f1size ), + ])); + + const MulByQY = c.i32_const(module.alloc([ + ...utils$2.bigInt2BytesLE( toMontgomery("2821565182194536844548159561693502659359617185244120367078079554186484126554"), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery("3505843767911556378687030309984248845540243509899259641013678093033130930403"), f1size ), + ])); + + f.addCode( + // The frobeniusMap(1) in this field, is the conjugate + c.call(f2mPrefix + "_conjugate", x, x3), + c.call(f2mPrefix + "_mul", MulByQX, x3, x3), + c.call(f2mPrefix + "_conjugate", y, y3), + c.call(f2mPrefix + "_mul", MulByQY, y3, y3), + c.call(f2mPrefix + "_conjugate", z, z3), + ); + } + + + function buildPrepareG2() { + buildMulByQ(); + const f = module.addFunction(prefix+ "_prepareG2"); + f.addParam("pQ", "i32"); + f.addParam("ppreQ", "i32"); + f.addLocal("pCoef", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const QX = c.getLocal("pQ"); + + const pR = module.alloc(f2size*3); + const R = c.i32_const(pR); + const RX = c.i32_const(pR); + const RY = c.i32_const(pR+f2size); + const RZ = c.i32_const(pR+2*f2size); + + const cQX = c.i32_add( c.getLocal("ppreQ"), c.i32_const(0)); + const cQY = c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size)); + + const pQ1 = module.alloc(f2size*3); + const Q1 = c.i32_const(pQ1); + + const pQ2 = module.alloc(f2size*3); + const Q2 = c.i32_const(pQ2); + const Q2Y = c.i32_const(pQ2 + f2size); + + f.addCode( + c.call(g2mPrefix + "_normalize", QX, cQX), // TODO Remove if already in affine + c.call(f2mPrefix + "_copy", cQX, RX), + c.call(f2mPrefix + "_copy", cQY, RY), + c.call(f2mPrefix + "_one", RZ), + ); + + f.addCode( + c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), + c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), + c.block(c.loop( + + c.call(prefix + "_prepDblStep", R, c.getLocal("pCoef")), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.if( + c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), + [ + ...c.call(prefix + "_prepAddStep", cQX, R, c.getLocal("pCoef")), + ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + ] + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + + f.addCode( + c.call(prefix + "_mulByQ", cQX, Q1), + c.call(prefix + "_mulByQ", Q1, Q2) + ); + + f.addCode( + c.call(f2mPrefix + "_neg", Q2Y, Q2Y), + + c.call(prefix + "_prepAddStep", Q1, R, c.getLocal("pCoef")), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.call(prefix + "_prepAddStep", Q2, R, c.getLocal("pCoef")), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + ); + } + + function buildMulBy024Old() { + const f = module.addFunction(prefix+ "__mulBy024Old"); + f.addParam("pEll0", "i32"); + f.addParam("pEllVW", "i32"); + f.addParam("pEllVV", "i32"); + f.addParam("pR", "i32"); // Result in F12 + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("pEll0"); + const x2 = c.getLocal("pEllVV"); + const x4 = c.getLocal("pEllVW"); + + const z0 = c.getLocal("pR"); + + const pAUX12 = module.alloc(ftsize); + const AUX12 = c.i32_const(pAUX12); + const AUX12_0 = c.i32_const(pAUX12); + const AUX12_2 = c.i32_const(pAUX12+f2size); + const AUX12_4 = c.i32_const(pAUX12+f2size*2); + const AUX12_6 = c.i32_const(pAUX12+f2size*3); + const AUX12_8 = c.i32_const(pAUX12+f2size*4); + const AUX12_10 = c.i32_const(pAUX12+f2size*5); + + f.addCode( + + c.call(f2mPrefix + "_copy", x0, AUX12_0), + c.call(f2mPrefix + "_zero", AUX12_2), + c.call(f2mPrefix + "_copy", x2, AUX12_4), + c.call(f2mPrefix + "_zero", AUX12_6), + c.call(f2mPrefix + "_copy", x4, AUX12_8), + c.call(f2mPrefix + "_zero", AUX12_10), + c.call(ftmPrefix + "_mul", AUX12, z0, z0), + ); + } + + function buildMulBy024() { + const f = module.addFunction(prefix+ "__mulBy024"); + f.addParam("pEll0", "i32"); + f.addParam("pEllVW", "i32"); + f.addParam("pEllVV", "i32"); + f.addParam("pR", "i32"); // Result in F12 + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("pEll0"); + const x2 = c.getLocal("pEllVV"); + const x4 = c.getLocal("pEllVW"); + + const z0 = c.getLocal("pR"); + const z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*n8)); + const z2 = c.i32_add(c.getLocal("pR"), c.i32_const(4*n8)); + const z3 = c.i32_add(c.getLocal("pR"), c.i32_const(6*n8)); + const z4 = c.i32_add(c.getLocal("pR"), c.i32_const(8*n8)); + const z5 = c.i32_add(c.getLocal("pR"), c.i32_const(10*n8)); + + const t0 = c.i32_const(module.alloc(f2size)); + const t1 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const s0 = c.i32_const(module.alloc(f2size)); + const T3 = c.i32_const(module.alloc(f2size)); + const T4 = c.i32_const(module.alloc(f2size)); + const D0 = c.i32_const(module.alloc(f2size)); + const D2 = c.i32_const(module.alloc(f2size)); + const D4 = c.i32_const(module.alloc(f2size)); + const S1 = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + f.addCode( + + // D0 = z0 * x0; + c.call(f2mPrefix + "_mul", z0, x0, D0), + // D2 = z2 * x2; + c.call(f2mPrefix + "_mul", z2, x2, D2), + // D4 = z4 * x4; + c.call(f2mPrefix + "_mul", z4, x4, D4), + // t2 = z0 + z4; + c.call(f2mPrefix + "_add", z0, z4, t2), + // t1 = z0 + z2; + c.call(f2mPrefix + "_add", z0, z2, t1), + // s0 = z1 + z3 + z5; + c.call(f2mPrefix + "_add", z1, z3, s0), + c.call(f2mPrefix + "_add", s0, z5, s0), + + + // For z.a_.a_ = z0. + // S1 = z1 * x2; + c.call(f2mPrefix + "_mul", z1, x2, S1), + // T3 = S1 + D4; + c.call(f2mPrefix + "_add", S1, D4, T3), + // T4 = my_Fp6::non_residue * T3 + D0; + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), + c.call(f2mPrefix + "_add", T4, D0, z0), + // z0 = T4; + + // For z.a_.b_ = z1 + // T3 = z5 * x4; + c.call(f2mPrefix + "_mul", z5, x4, T3), + // S1 = S1 + T3; + c.call(f2mPrefix + "_add", S1, T3, S1), + // T3 = T3 + D2; + c.call(f2mPrefix + "_add", T3, D2, T3), + // T4 = my_Fp6::non_residue * T3; + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), + // T3 = z1 * x0; + c.call(f2mPrefix + "_mul", z1, x0, T3), + // S1 = S1 + T3; + c.call(f2mPrefix + "_add", S1, T3, S1), + // T4 = T4 + T3; + c.call(f2mPrefix + "_add", T4, T3, z1), + // z1 = T4; + + + + // For z.a_.c_ = z2 + // t0 = x0 + x2; + c.call(f2mPrefix + "_add", x0, x2, t0), + // T3 = t1 * t0 - D0 - D2; + c.call(f2mPrefix + "_mul", t1, t0, T3), + c.call(f2mPrefix + "_add", D0, D2, AUX), + c.call(f2mPrefix + "_sub", T3, AUX, T3), + // T4 = z3 * x4; + c.call(f2mPrefix + "_mul", z3, x4, T4), + // S1 = S1 + T4; + c.call(f2mPrefix + "_add", S1, T4, S1), + + + // For z.b_.a_ = z3 (z3 needs z2) + // t0 = z2 + z4; + c.call(f2mPrefix + "_add", z2, z4, t0), + // T3 = T3 + T4; + // z2 = T3; + c.call(f2mPrefix + "_add", T3, T4, z2), + // t1 = x2 + x4; + c.call(f2mPrefix + "_add", x2, x4, t1), + // T3 = t0 * t1 - D2 - D4; + c.call(f2mPrefix + "_mul", t1, t0, T3), + c.call(f2mPrefix + "_add", D2, D4, AUX), + c.call(f2mPrefix + "_sub", T3, AUX, T3), + // T4 = my_Fp6::non_residue * T3; + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), + // T3 = z3 * x0; + c.call(f2mPrefix + "_mul", z3, x0, T3), + // S1 = S1 + T3; + c.call(f2mPrefix + "_add", S1, T3, S1), + // T4 = T4 + T3; + c.call(f2mPrefix + "_add", T4, T3, z3), + // z3 = T4; + + // For z.b_.b_ = z4 + // T3 = z5 * x2; + c.call(f2mPrefix + "_mul", z5, x2, T3), + // S1 = S1 + T3; + c.call(f2mPrefix + "_add", S1, T3, S1), + // T4 = my_Fp6::non_residue * T3; + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), + // t0 = x0 + x4; + c.call(f2mPrefix + "_add", x0, x4, t0), + // T3 = t2 * t0 - D0 - D4; + c.call(f2mPrefix + "_mul", t2, t0, T3), + c.call(f2mPrefix + "_add", D0, D4, AUX), + c.call(f2mPrefix + "_sub", T3, AUX, T3), + // T4 = T4 + T3; + c.call(f2mPrefix + "_add", T4, T3, z4), + // z4 = T4; + + // For z.b_.c_ = z5. + // t0 = x0 + x2 + x4; + c.call(f2mPrefix + "_add", x0, x2, t0), + c.call(f2mPrefix + "_add", t0, x4, t0), + // T3 = s0 * t0 - S1; + c.call(f2mPrefix + "_mul", s0, t0, T3), + c.call(f2mPrefix + "_sub", T3, S1, z5), + // z5 = T3; + + ); + } + + + function buildMillerLoop() { + const f = module.addFunction(prefix+ "_millerLoop"); + f.addParam("ppreP", "i32"); + f.addParam("ppreQ", "i32"); + f.addParam("r", "i32"); + f.addLocal("pCoef", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const preP_PX = c.getLocal("ppreP"); + const preP_PY = c.i32_add(c.getLocal("ppreP"), c.i32_const(f1size)); + + const ELL_0 = c.getLocal("pCoef"); + const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); + const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); + + + const pVW = module.alloc(f2size); + const VW = c.i32_const(pVW); + const pVV = module.alloc(f2size); + const VV = c.i32_const(pVV); + + const F = c.getLocal("r"); + + + f.addCode( + c.call(ftmPrefix + "_one", F), + + c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), + + c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), + c.block(c.loop( + + + c.call(ftmPrefix + "_square", F, F), + + c.call(f2mPrefix + "_mul1", ELL_VW,preP_PY, VW), + c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), + c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.if( + c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), + [ + ...c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), + ...c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), + + ...c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), + ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + ] + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + + ); + + f.addCode( + c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), + c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), + c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), + c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), + c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + ); + + } + + + function buildFrobeniusMap(n) { + const F12 = [ + [ + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + ], + [ + [1n, 0n], + [8376118865763821496583973867626364092589906065868298776909617916018768340080n, 16469823323077808223889137241176536799009286646108169935659301613961712198316n], + [21888242871839275220042445260109153167277707414472061641714758635765020556617n, 0n], + [11697423496358154304825782922584725312912383441159505038794027105778954184319n, 303847389135065887422783454877609941456349188919719272345083954437860409601n], + [21888242871839275220042445260109153167277707414472061641714758635765020556616n, 0n], + [3321304630594332808241809054958361220322477375291206261884409189760185844239n, 5722266937896532885780051958958348231143373700109372999374820235121374419868n], + [21888242871839275222246405745257275088696311157297823662689037894645226208582n, 0n], + [13512124006075453725662431877630910996106405091429524885779419978626457868503n, 5418419548761466998357268504080738289687024511189653727029736280683514010267n], + [2203960485148121921418603742825762020974279258880205651966n, 0n], + [10190819375481120917420622822672549775783927716138318623895010788866272024264n, 21584395482704209334823622290379665147239961968378104390343953940207365798982n], + [2203960485148121921418603742825762020974279258880205651967n, 0n], + [18566938241244942414004596690298913868373833782006617400804628704885040364344n, 16165975933942742336466353786298926857552937457188450663314217659523851788715n], + ] + ]; + + const F6 = [ + [ + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + ], + [ + [1n, 0n], + [21575463638280843010398324269430826099269044274347216827212613867836435027261n, 10307601595873709700152284273816112264069230130616436755625194854815875713954n], + [21888242871839275220042445260109153167277707414472061641714758635765020556616n, 0n], + [3772000881919853776433695186713858239009073593817195771773381919316419345261n, 2236595495967245188281701248203181795121068902605861227855261137820944008926n], + [2203960485148121921418603742825762020974279258880205651966n, 0n], + [18429021223477853657660792034369865839114504446431234726392080002137598044644n, 9344045779998320333812420223237981029506012124075525679208581902008406485703n], + ], + [ + [1n, 0n], + [2581911344467009335267311115468803099551665605076196740867805258568234346338n, 19937756971775647987995932169929341994314640652964949448313374472400716661030n], + [2203960485148121921418603742825762020974279258880205651966n, 0n], + [5324479202449903542726783395506214481928257762400643279780343368557297135718n, 16208900380737693084919495127334387981393726419856888799917914180988844123039n], + [21888242871839275220042445260109153167277707414472061641714758635765020556616n, 0n], + [13981852324922362344252311234282257507216387789820983642040889267519694726527n, 7629828391165209371577384193250820201684255241773809077146787135900891633097n], + ] + ]; + + const f = module.addFunction(prefix+ "__frobeniusMap"+n); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + for (let i=0; i<6; i++) { + const X = (i==0) ? c.getLocal("x") : c.i32_add(c.getLocal("x"), c.i32_const(i*f2size)); + const Xc0 = X; + const Xc1 = c.i32_add(c.getLocal("x"), c.i32_const(i*f2size + f1size)); + const R = (i==0) ? c.getLocal("r") : c.i32_add(c.getLocal("r"), c.i32_const(i*f2size)); + const Rc0 = R; + const Rc1 = c.i32_add(c.getLocal("r"), c.i32_const(i*f2size + f1size)); + const coef = mul2(F12[Math.floor(i/3)][n%12] , F6[i%3][n%6]); + const pCoef = module.alloc([ + ...utils$2.bigInt2BytesLE(toMontgomery(coef[0]), 32), + ...utils$2.bigInt2BytesLE(toMontgomery(coef[1]), 32), + ]); + if (n%2 == 1) { + f.addCode( + c.call(f1mPrefix + "_copy", Xc0, Rc0), + c.call(f1mPrefix + "_neg", Xc1, Rc1), + c.call(f2mPrefix + "_mul", R, c.i32_const(pCoef), R), + ); + } else { + f.addCode(c.call(f2mPrefix + "_mul", X, c.i32_const(pCoef), R)); + } + } + + function mul2(a, b) { + const ac0 = BigInt(a[0]); + const ac1 = BigInt(a[1]); + const bc0 = BigInt(b[0]); + const bc1 = BigInt(b[1]); + const res = [ + (ac0 * bc0 - ( ac1 * bc1) ) % q, + (ac0 * bc1 + ( ac1 * bc0) ) % q, + ]; + if (isNegative$2(res[0])) res[0] = res[0] + q; + return res; + } + + } + + + + function buildFinalExponentiationFirstChunk() { + + const f = module.addFunction(prefix+ "__finalExponentiationFirstChunk"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const elt = c.getLocal("x"); + const eltC0 = elt; + const eltC1 = c.i32_add(elt, c.i32_const(n8*6)); + const r = c.getLocal("r"); + const pA = module.alloc(ftsize); + const A = c.i32_const(pA); + const Ac0 = A; + const Ac1 = c.i32_const(pA + n8*6); + const B = c.i32_const(module.alloc(ftsize)); + const C = c.i32_const(module.alloc(ftsize)); + const D = c.i32_const(module.alloc(ftsize)); + + f.addCode( + // const alt_bn128_Fq12 A = alt_bn128_Fq12(elt.c0,-elt.c1); + c.call(f6mPrefix + "_copy", eltC0, Ac0), + c.call(f6mPrefix + "_neg", eltC1, Ac1), + + // const alt_bn128_Fq12 B = elt.inverse(); + c.call(ftmPrefix + "_inverse", elt, B), + + // const alt_bn128_Fq12 C = A * B; + c.call(ftmPrefix + "_mul", A, B, C), + // const alt_bn128_Fq12 D = C.Frobenius_map(2); + c.call(prefix + "__frobeniusMap2", C, D), + // const alt_bn128_Fq12 result = D * C; + c.call(ftmPrefix + "_mul", C, D, r), + ); + } + + function buildCyclotomicSquare() { + const f = module.addFunction(prefix+ "__cyclotomicSquare"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x4 = c.i32_add(c.getLocal("x"), c.i32_const(f2size)); + const x3 = c.i32_add(c.getLocal("x"), c.i32_const(2*f2size)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(3*f2size)); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(4*f2size)); + const x5 = c.i32_add(c.getLocal("x"), c.i32_const(5*f2size)); + + const r0 = c.getLocal("r"); + const r4 = c.i32_add(c.getLocal("r"), c.i32_const(f2size)); + const r3 = c.i32_add(c.getLocal("r"), c.i32_const(2*f2size)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(3*f2size)); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(4*f2size)); + const r5 = c.i32_add(c.getLocal("r"), c.i32_const(5*f2size)); + + const t0 = c.i32_const(module.alloc(f2size)); + const t1 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const t3 = c.i32_const(module.alloc(f2size)); + const t4 = c.i32_const(module.alloc(f2size)); + const t5 = c.i32_const(module.alloc(f2size)); + const tmp = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + + f.addCode( + // // t0 + t1*y = (z0 + z1*y)^2 = a^2 + // tmp = z0 * z1; + // t0 = (z0 + z1) * (z0 + my_Fp6::non_residue * z1) - tmp - my_Fp6::non_residue * tmp; + // t1 = tmp + tmp; + c.call(f2mPrefix + "_mul", x0, x1, tmp), + c.call(f2mPrefix + "_mul", x1, c.i32_const(pNonResidueF6), t0), + c.call(f2mPrefix + "_add", x0, t0, t0), + c.call(f2mPrefix + "_add", x0, x1, AUX), + c.call(f2mPrefix + "_mul", AUX, t0, t0), + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t0, AUX, t0), + c.call(f2mPrefix + "_add", tmp, tmp, t1), + + // // t2 + t3*y = (z2 + z3*y)^2 = b^2 + // tmp = z2 * z3; + // t2 = (z2 + z3) * (z2 + my_Fp6::non_residue * z3) - tmp - my_Fp6::non_residue * tmp; + // t3 = tmp + tmp; + c.call(f2mPrefix + "_mul", x2, x3, tmp), + c.call(f2mPrefix + "_mul", x3, c.i32_const(pNonResidueF6), t2), + c.call(f2mPrefix + "_add", x2, t2, t2), + c.call(f2mPrefix + "_add", x2, x3, AUX), + c.call(f2mPrefix + "_mul", AUX, t2, t2), + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t2, AUX, t2), + c.call(f2mPrefix + "_add", tmp, tmp, t3), + + // // t4 + t5*y = (z4 + z5*y)^2 = c^2 + // tmp = z4 * z5; + // t4 = (z4 + z5) * (z4 + my_Fp6::non_residue * z5) - tmp - my_Fp6::non_residue * tmp; + // t5 = tmp + tmp; + c.call(f2mPrefix + "_mul", x4, x5, tmp), + c.call(f2mPrefix + "_mul", x5, c.i32_const(pNonResidueF6), t4), + c.call(f2mPrefix + "_add", x4, t4, t4), + c.call(f2mPrefix + "_add", x4, x5, AUX), + c.call(f2mPrefix + "_mul", AUX, t4, t4), + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t4, AUX, t4), + c.call(f2mPrefix + "_add", tmp, tmp, t5), + + // For A + // z0 = 3 * t0 - 2 * z0 + c.call(f2mPrefix + "_sub", t0, x0, r0), + c.call(f2mPrefix + "_add", r0, r0, r0), + c.call(f2mPrefix + "_add", t0, r0, r0), + // z1 = 3 * t1 + 2 * z1 + c.call(f2mPrefix + "_add", t1, x1, r1), + c.call(f2mPrefix + "_add", r1, r1, r1), + c.call(f2mPrefix + "_add", t1, r1, r1), + + // For B + // z2 = 3 * (xi * t5) + 2 * z2 + c.call(f2mPrefix + "_mul", t5, c.i32_const(pAltBn128Twist), AUX), + c.call(f2mPrefix + "_add", AUX, x2, r2), + c.call(f2mPrefix + "_add", r2, r2, r2), + c.call(f2mPrefix + "_add", AUX, r2, r2), + // z3 = 3 * t4 - 2 * z3 + c.call(f2mPrefix + "_sub", t4, x3, r3), + c.call(f2mPrefix + "_add", r3, r3, r3), + c.call(f2mPrefix + "_add", t4, r3, r3), + + // For C + // z4 = 3 * t2 - 2 * z4 + c.call(f2mPrefix + "_sub", t2, x4, r4), + c.call(f2mPrefix + "_add", r4, r4, r4), + c.call(f2mPrefix + "_add", t2, r4, r4), + // z5 = 3 * t3 + 2 * z5 + c.call(f2mPrefix + "_add", t3, x5, r5), + c.call(f2mPrefix + "_add", r5, r5, r5), + c.call(f2mPrefix + "_add", t3, r5, r5), + + ); + } + + + function buildCyclotomicExp(exponent, fnName) { + const exponentNafBytes = naf(exponent).map( (b) => (b==-1 ? 0xFF: b) ); + const pExponentNafBytes = module.alloc(exponentNafBytes); + + const f = module.addFunction(prefix+ "__cyclotomicExp_"+fnName); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + f.addLocal("bit", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const x = c.getLocal("x"); + + const res = c.getLocal("r"); + + const inverse = c.i32_const(module.alloc(ftsize)); + + + f.addCode( + c.call(ftmPrefix + "_conjugate", x, inverse), + c.call(ftmPrefix + "_one", res), + + c.if( + c.teeLocal("bit", c.i32_load8_s(c.i32_const(exponentNafBytes.length-1), pExponentNafBytes)), + c.if( + c.i32_eq( + c.getLocal("bit"), + c.i32_const(1) + ), + c.call(ftmPrefix + "_mul", res, x, res), + c.call(ftmPrefix + "_mul", res, inverse, res), + ) + ), + + c.setLocal("i", c.i32_const(exponentNafBytes.length-2)), + c.block(c.loop( + c.call(prefix + "__cyclotomicSquare", res, res), + c.if( + c.teeLocal("bit", c.i32_load8_s(c.getLocal("i"), pExponentNafBytes)), + c.if( + c.i32_eq( + c.getLocal("bit"), + c.i32_const(1) + ), + c.call(ftmPrefix + "_mul", res, x, res), + c.call(ftmPrefix + "_mul", res, inverse, res), + ) + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + + + function buildFinalExponentiationLastChunk() { + buildCyclotomicSquare(); + buildCyclotomicExp(finalExpZ, "w0"); + + const f = module.addFunction(prefix+ "__finalExponentiationLastChunk"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const elt = c.getLocal("x"); + const result = c.getLocal("r"); + const A = c.i32_const(module.alloc(ftsize)); + const B = c.i32_const(module.alloc(ftsize)); + const C = c.i32_const(module.alloc(ftsize)); + const D = c.i32_const(module.alloc(ftsize)); + const E = c.i32_const(module.alloc(ftsize)); + const F = c.i32_const(module.alloc(ftsize)); + const G = c.i32_const(module.alloc(ftsize)); + const H = c.i32_const(module.alloc(ftsize)); + const I = c.i32_const(module.alloc(ftsize)); + const J = c.i32_const(module.alloc(ftsize)); + const K = c.i32_const(module.alloc(ftsize)); + const L = c.i32_const(module.alloc(ftsize)); + const M = c.i32_const(module.alloc(ftsize)); + const N = c.i32_const(module.alloc(ftsize)); + const O = c.i32_const(module.alloc(ftsize)); + const P = c.i32_const(module.alloc(ftsize)); + const Q = c.i32_const(module.alloc(ftsize)); + const R = c.i32_const(module.alloc(ftsize)); + const S = c.i32_const(module.alloc(ftsize)); + const T = c.i32_const(module.alloc(ftsize)); + const U = c.i32_const(module.alloc(ftsize)); + + f.addCode( + + + // A = exp_by_neg_z(elt) // = elt^(-z) + c.call(prefix + "__cyclotomicExp_w0", elt, A), + c.call(ftmPrefix + "_conjugate", A, A), + // B = A^2 // = elt^(-2*z) + c.call(prefix + "__cyclotomicSquare", A, B), + // C = B^2 // = elt^(-4*z) + c.call(prefix + "__cyclotomicSquare", B, C), + // D = C * B // = elt^(-6*z) + c.call(ftmPrefix + "_mul", C, B, D), + // E = exp_by_neg_z(D) // = elt^(6*z^2) + c.call(prefix + "__cyclotomicExp_w0", D, E), + c.call(ftmPrefix + "_conjugate", E, E), + // F = E^2 // = elt^(12*z^2) + c.call(prefix + "__cyclotomicSquare", E, F), + // G = epx_by_neg_z(F) // = elt^(-12*z^3) + c.call(prefix + "__cyclotomicExp_w0", F, G), + c.call(ftmPrefix + "_conjugate", G, G), + // H = conj(D) // = elt^(6*z) + c.call(ftmPrefix + "_conjugate", D, H), + // I = conj(G) // = elt^(12*z^3) + c.call(ftmPrefix + "_conjugate", G, I), + // J = I * E // = elt^(12*z^3 + 6*z^2) + c.call(ftmPrefix + "_mul", I, E, J), + // K = J * H // = elt^(12*z^3 + 6*z^2 + 6*z) + c.call(ftmPrefix + "_mul", J, H, K), + // L = K * B // = elt^(12*z^3 + 6*z^2 + 4*z) + c.call(ftmPrefix + "_mul", K, B, L), + // M = K * E // = elt^(12*z^3 + 12*z^2 + 6*z) + c.call(ftmPrefix + "_mul", K, E, M), + + // N = M * elt // = elt^(12*z^3 + 12*z^2 + 6*z + 1) + c.call(ftmPrefix + "_mul", M, elt, N), + + // O = L.Frobenius_map(1) // = elt^(q*(12*z^3 + 6*z^2 + 4*z)) + c.call(prefix + "__frobeniusMap1", L, O), + // P = O * N // = elt^(q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) + c.call(ftmPrefix + "_mul", O, N, P), + // Q = K.Frobenius_map(2) // = elt^(q^2 * (12*z^3 + 6*z^2 + 6*z)) + c.call(prefix + "__frobeniusMap2", K, Q), + // R = Q * P // = elt^(q^2 * (12*z^3 + 6*z^2 + 6*z) + q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) + c.call(ftmPrefix + "_mul", Q, P, R), + // S = conj(elt) // = elt^(-1) + c.call(ftmPrefix + "_conjugate", elt, S), + // T = S * L // = elt^(12*z^3 + 6*z^2 + 4*z - 1) + c.call(ftmPrefix + "_mul", S, L, T), + // U = T.Frobenius_map(3) // = elt^(q^3(12*z^3 + 6*z^2 + 4*z - 1)) + c.call(prefix + "__frobeniusMap3", T, U), + // V = U * R // = elt^(q^3(12*z^3 + 6*z^2 + 4*z - 1) + q^2 * (12*z^3 + 6*z^2 + 6*z) + q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) + c.call(ftmPrefix + "_mul", U, R, result), + // result = V + ); + } + + + function buildFinalExponentiation() { + buildFinalExponentiationFirstChunk(); + buildFinalExponentiationLastChunk(); + const f = module.addFunction(prefix+ "_finalExponentiation"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const elt = c.getLocal("x"); + const result = c.getLocal("r"); + const eltToFirstChunk = c.i32_const(module.alloc(ftsize)); + + f.addCode( + c.call(prefix + "__finalExponentiationFirstChunk", elt, eltToFirstChunk ), + c.call(prefix + "__finalExponentiationLastChunk", eltToFirstChunk, result ) + ); + } + + + function buildFinalExponentiationOld() { + const f = module.addFunction(prefix+ "_finalExponentiationOld"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const exponent = 552484233613224096312617126783173147097382103762957654188882734314196910839907541213974502761540629817009608548654680343627701153829446747810907373256841551006201639677726139946029199968412598804882391702273019083653272047566316584365559776493027495458238373902875937659943504873220554161550525926302303331747463515644711876653177129578303191095900909191624817826566688241804408081892785725967931714097716709526092261278071952560171111444072049229123565057483750161460024353346284167282452756217662335528813519139808291170539072125381230815729071544861602750936964829313608137325426383735122175229541155376346436093930287402089517426973178917569713384748081827255472576937471496195752727188261435633271238710131736096299798168852925540549342330775279877006784354801422249722573783561685179618816480037695005515426162362431072245638324744480n; + + const pExponent = module.alloc(utils$2.bigInt2BytesLE( exponent, 352 )); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(ftmPrefix + "_exp", c.getLocal("x"), c.i32_const(pExponent), c.i32_const(352), c.getLocal("r")), + ); + } + + + + + const pPreP = module.alloc(prePSize); + const pPreQ = module.alloc(preQSize); + + function buildPairingEquation(nPairings) { + + const f = module.addFunction(prefix+ "_pairingEq"+nPairings); + for (let i=0; i acc + ( b!=0 ? 1 : 0) ,0); + const ateNCoefs = ateNAddCoefs + ateNDblCoefs + 1; + const prePSize = 3*2*n8q; + const preQSize = 3*n8q*2 + ateNCoefs*ateCoefSize; + const finalExpIsNegative = true; + + const finalExpZ = 15132376222941642752n; + + + module.modules[prefix] = { + n64q: n64q, + n64r: n64r, + n8q: n8q, + n8r: n8r, + pG1gen: pG1gen, + pG1zero: pG1zero, + pG1b: pG1b, + pG2gen: pG2gen, + pG2zero: pG2zero, + pG2b: pG2b, + pq: module.modules["f1m"].pq, + pr: pr, + pOneT: pOneT, + r: r, + q: q, + prePSize: prePSize, + preQSize: preQSize + }; + + + function naf(n) { + let E = n; + const res = []; + while (E > 0n) { + if (isOdd(E)) { + const z = 2 - Number(E % 4n); + res.push( z ); + E = E - BigInt(z); + } else { + res.push( 0 ); + } + E = E >> 1n; + } + return res; + } + + function bits(n) { + let E = n; + const res = []; + while (E > 0n) { + if (isOdd(E)) { + res.push( 1 ); + } else { + res.push( 0 ); + } + E = E >> 1n; + } + return res; + } + + function buildPrepareG1() { + const f = module.addFunction(prefix+ "_prepareG1"); + f.addParam("pP", "i32"); + f.addParam("ppreP", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(g1mPrefix + "_normalize", c.getLocal("pP"), c.getLocal("ppreP")), // TODO Remove if already in affine + ); + } + + + + function buildPrepDoubleStep() { + const f = module.addFunction(prefix+ "_prepDblStep"); + f.addParam("R", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const Rx = c.getLocal("R"); + const Ry = c.i32_add(c.getLocal("R"), c.i32_const(2*n8q)); + const Rz = c.i32_add(c.getLocal("R"), c.i32_const(4*n8q)); + + const t0 = c.getLocal("r"); + const t3 = c.i32_add(c.getLocal("r"), c.i32_const(2*n8q)); + const t6 = c.i32_add(c.getLocal("r"), c.i32_const(4*n8q)); + + + const zsquared = c.i32_const(module.alloc(f2size)); + const t1 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const t4 = c.i32_const(module.alloc(f2size)); + const t5 = c.i32_const(module.alloc(f2size)); + + f.addCode( + + // tmp0 = r.x.square(); + c.call(f2mPrefix + "_square", Rx, t0), + + // tmp1 = r.y.square(); + c.call(f2mPrefix + "_square", Ry, t1), + + // tmp2 = tmp1.square(); + c.call(f2mPrefix + "_square", t1, t2), + + // tmp3 = (tmp1 + r.x).square() - tmp0 - tmp2; + c.call(f2mPrefix + "_add", t1, Rx, t3), + c.call(f2mPrefix + "_square", t3, t3), + c.call(f2mPrefix + "_sub", t3, t0, t3), + c.call(f2mPrefix + "_sub", t3, t2, t3), + + // tmp3 = tmp3 + tmp3; + c.call(f2mPrefix + "_add", t3, t3, t3), + + // tmp4 = tmp0 + tmp0 + tmp0; + c.call(f2mPrefix + "_add", t0, t0, t4), + c.call(f2mPrefix + "_add", t4, t0, t4), + + // tmp6 = r.x + tmp4; + c.call(f2mPrefix + "_add", Rx, t4, t6), + + // tmp5 = tmp4.square(); + c.call(f2mPrefix + "_square", t4, t5), + + // zsquared = r.z.square(); + c.call(f2mPrefix + "_square", Rz, zsquared), + + // r.x = tmp5 - tmp3 - tmp3; + c.call(f2mPrefix + "_sub", t5, t3, Rx), + c.call(f2mPrefix + "_sub", Rx, t3, Rx), + + // r.z = (r.z + r.y).square() - tmp1 - zsquared; + c.call(f2mPrefix + "_add", Rz, Ry, Rz), + c.call(f2mPrefix + "_square", Rz, Rz), + c.call(f2mPrefix + "_sub", Rz, t1, Rz), + c.call(f2mPrefix + "_sub", Rz, zsquared, Rz), + + // r.y = (tmp3 - r.x) * tmp4; + c.call(f2mPrefix + "_sub", t3, Rx, Ry), + c.call(f2mPrefix + "_mul", Ry, t4, Ry), + + // tmp2 = tmp2 + tmp2; + c.call(f2mPrefix + "_add", t2, t2, t2), + + // tmp2 = tmp2 + tmp2; + c.call(f2mPrefix + "_add", t2, t2, t2), + + // tmp2 = tmp2 + tmp2; + c.call(f2mPrefix + "_add", t2, t2, t2), + + // r.y -= tmp2; + c.call(f2mPrefix + "_sub", Ry, t2, Ry), + + // tmp3 = tmp4 * zsquared; + c.call(f2mPrefix + "_mul", t4, zsquared, t3), + + // tmp3 = tmp3 + tmp3; + c.call(f2mPrefix + "_add", t3, t3, t3), + + // tmp3 = -tmp3; + c.call(f2mPrefix + "_neg", t3, t3), + + // tmp6 = tmp6.square() - tmp0 - tmp5; + c.call(f2mPrefix + "_square", t6, t6), + c.call(f2mPrefix + "_sub", t6, t0, t6), + c.call(f2mPrefix + "_sub", t6, t5, t6), + + // tmp1 = tmp1 + tmp1; + c.call(f2mPrefix + "_add", t1, t1, t1), + + // tmp1 = tmp1 + tmp1; + c.call(f2mPrefix + "_add", t1, t1, t1), + + // tmp6 = tmp6 - tmp1; + c.call(f2mPrefix + "_sub", t6, t1, t6), + + // tmp0 = r.z * zsquared; + c.call(f2mPrefix + "_mul", Rz, zsquared, t0), + + // tmp0 = tmp0 + tmp0; + c.call(f2mPrefix + "_add", t0, t0, t0), + + ); + } + + function buildPrepAddStep() { + const f = module.addFunction(prefix+ "_prepAddStep"); + f.addParam("R", "i32"); + f.addParam("Q", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const Rx = c.getLocal("R"); + const Ry = c.i32_add(c.getLocal("R"), c.i32_const(2*n8q)); + const Rz = c.i32_add(c.getLocal("R"), c.i32_const(4*n8q)); + + const Qx = c.getLocal("Q"); + const Qy = c.i32_add(c.getLocal("Q"), c.i32_const(2*n8q)); + + const t10 = c.getLocal("r"); + const t1 = c.i32_add(c.getLocal("r"), c.i32_const(2*n8q)); + const t9 = c.i32_add(c.getLocal("r"), c.i32_const(4*n8q)); + + const zsquared = c.i32_const(module.alloc(f2size)); + const ysquared = c.i32_const(module.alloc(f2size)); + const ztsquared = c.i32_const(module.alloc(f2size)); + const t0 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const t3 = c.i32_const(module.alloc(f2size)); + const t4 = c.i32_const(module.alloc(f2size)); + const t5 = c.i32_const(module.alloc(f2size)); + const t6 = c.i32_const(module.alloc(f2size)); + const t7 = c.i32_const(module.alloc(f2size)); + const t8 = c.i32_const(module.alloc(f2size)); + + f.addCode( + + // zsquared = r.z.square(); + c.call(f2mPrefix + "_square", Rz, zsquared), + + // ysquared = q.y.square(); + c.call(f2mPrefix + "_square", Qy, ysquared), + + // t0 = zsquared * q.x; + c.call(f2mPrefix + "_mul", zsquared, Qx, t0), + + // t1 = ((q.y + r.z).square() - ysquared - zsquared) * zsquared; + c.call(f2mPrefix + "_add", Qy, Rz, t1), + c.call(f2mPrefix + "_square", t1, t1), + c.call(f2mPrefix + "_sub", t1, ysquared, t1), + c.call(f2mPrefix + "_sub", t1, zsquared, t1), + c.call(f2mPrefix + "_mul", t1, zsquared, t1), + + // t2 = t0 - r.x; + c.call(f2mPrefix + "_sub", t0, Rx, t2), + + // t3 = t2.square(); + c.call(f2mPrefix + "_square", t2, t3), + + // t4 = t3 + t3; + c.call(f2mPrefix + "_add", t3, t3, t4), + + // t4 = t4 + t4; + c.call(f2mPrefix + "_add", t4, t4, t4), + + // t5 = t4 * t2; + c.call(f2mPrefix + "_mul", t4, t2, t5), + + // t6 = t1 - r.y - r.y; + c.call(f2mPrefix + "_sub", t1, Ry, t6), + c.call(f2mPrefix + "_sub", t6, Ry, t6), + + // t9 = t6 * q.x; + c.call(f2mPrefix + "_mul", t6, Qx, t9), + + // t7 = t4 * r.x; + c.call(f2mPrefix + "_mul", t4, Rx, t7), + + // r.x = t6.square() - t5 - t7 - t7; + c.call(f2mPrefix + "_square", t6, Rx), + c.call(f2mPrefix + "_sub", Rx, t5, Rx), + c.call(f2mPrefix + "_sub", Rx, t7, Rx), + c.call(f2mPrefix + "_sub", Rx, t7, Rx), + + // r.z = (r.z + t2).square() - zsquared - t3; + c.call(f2mPrefix + "_add", Rz, t2, Rz), + c.call(f2mPrefix + "_square", Rz, Rz), + c.call(f2mPrefix + "_sub", Rz, zsquared, Rz), + c.call(f2mPrefix + "_sub", Rz, t3, Rz), + + // t10 = q.y + r.z; + c.call(f2mPrefix + "_add", Qy, Rz, t10), + + // t8 = (t7 - r.x) * t6; + c.call(f2mPrefix + "_sub", t7, Rx, t8), + c.call(f2mPrefix + "_mul", t8, t6, t8), + + // t0 = r.y * t5; + c.call(f2mPrefix + "_mul", Ry, t5, t0), + + // t0 = t0 + t0; + c.call(f2mPrefix + "_add", t0, t0, t0), + + // r.y = t8 - t0; + c.call(f2mPrefix + "_sub", t8, t0, Ry), + + // t10 = t10.square() - ysquared; + c.call(f2mPrefix + "_square", t10, t10), + c.call(f2mPrefix + "_sub", t10, ysquared, t10), + + // ztsquared = r.z.square(); + c.call(f2mPrefix + "_square", Rz, ztsquared), + + // t10 = t10 - ztsquared; + c.call(f2mPrefix + "_sub", t10, ztsquared, t10), + + // t9 = t9 + t9 - t10; + c.call(f2mPrefix + "_add", t9, t9, t9), + c.call(f2mPrefix + "_sub", t9, t10, t9), + + // t10 = r.z + r.z; + c.call(f2mPrefix + "_add", Rz, Rz, t10), + + // t6 = -t6; + c.call(f2mPrefix + "_neg", t6, t6), + + // t1 = t6 + t6; + c.call(f2mPrefix + "_add", t6, t6, t1), + ); + } + + + function buildPrepareG2() { + const f = module.addFunction(prefix+ "_prepareG2"); + f.addParam("pQ", "i32"); + f.addParam("ppreQ", "i32"); + f.addLocal("pCoef", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + + const Q = c.getLocal("pQ"); + + const pR = module.alloc(f2size*3); + const R = c.i32_const(pR); + + const base = c.getLocal("ppreQ"); + + f.addCode( + c.call(g2mPrefix + "_normalize", Q, base), + c.if( + c.call(g2mPrefix + "_isZero", base), + c.ret([]) + ), + c.call(g2mPrefix + "_copy", base, R), + c.setLocal("pCoef", c.i32_add(c.getLocal("ppreQ"), c.i32_const(f2size*3))), + ); + + f.addCode( + c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), + c.block(c.loop( + + c.call(prefix + "_prepDblStep", R, c.getLocal("pCoef")), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.if( + c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), + [ + ...c.call(prefix + "_prepAddStep", R, base, c.getLocal("pCoef")), + ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + ] + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + + function buildF6Mul1() { + const f = module.addFunction(f6mPrefix+ "_mul1"); + f.addParam("pA", "i32"); // F6 + f.addParam("pC1", "i32"); // F2 + f.addParam("pR", "i32"); // F6 + + const c = f.getCodeBuilder(); + + const A_c0 = c.getLocal("pA"); + const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*2)); + const A_c2 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*4)); + + const c1 = c.getLocal("pC1"); + + const t1 = c.getLocal("pR"); + const t2 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*2)); + const b_b = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*4)); + + const Ac0_Ac1 = c.i32_const(module.alloc(f1size*2)); + const Ac1_Ac2 = c.i32_const(module.alloc(f1size*2)); + + f.addCode( + + c.call(f2mPrefix + "_add", A_c0, A_c1, Ac0_Ac1), + c.call(f2mPrefix + "_add", A_c1, A_c2, Ac1_Ac2), + + // let b_b = self.c1 * c1; + c.call(f2mPrefix + "_mul", A_c1, c1, b_b), + + // let t1 = (self.c1 + self.c2) * c1 - b_b; + c.call(f2mPrefix + "_mul", Ac1_Ac2, c1, t1), + c.call(f2mPrefix + "_sub", t1, b_b, t1), + + // let t1 = t1.mul_by_nonresidue(); + c.call(f2mPrefix + "_mulNR", t1, t1), + + // let t2 = (self.c0 + self.c1) * c1 - b_b; + c.call(f2mPrefix + "_mul", Ac0_Ac1, c1, t2), + c.call(f2mPrefix + "_sub", t2, b_b, t2), + ); + } + buildF6Mul1(); + + function buildF6Mul01() { + const f = module.addFunction(f6mPrefix+ "_mul01"); + f.addParam("pA", "i32"); // F6 + f.addParam("pC0", "i32"); // F2 + f.addParam("pC1", "i32"); // F2 + f.addParam("pR", "i32"); // F6 + + const c = f.getCodeBuilder(); + + const A_c0 = c.getLocal("pA"); + const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*2)); + const A_c2 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*4)); + + const c0 = c.getLocal("pC0"); + const c1 = c.getLocal("pC1"); + + const t1 = c.getLocal("pR"); + const t2 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*2)); + const t3 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*4)); + + const a_a = c.i32_const(module.alloc(f1size*2)); + const b_b = c.i32_const(module.alloc(f1size*2)); + const Ac0_Ac1 = c.i32_const(module.alloc(f1size*2)); + const Ac0_Ac2 = c.i32_const(module.alloc(f1size*2)); + + f.addCode( + // let a_a = self.c0 * c0; + c.call(f2mPrefix + "_mul", A_c0, c0, a_a), + + // let b_b = self.c1 * c1; + c.call(f2mPrefix + "_mul", A_c1, c1, b_b), + + + c.call(f2mPrefix + "_add", A_c0, A_c1, Ac0_Ac1), + c.call(f2mPrefix + "_add", A_c0, A_c2, Ac0_Ac2), + + // let t1 = (self.c1 + self.c2) * c1 - b_b; + c.call(f2mPrefix + "_add", A_c1, A_c2, t1), + c.call(f2mPrefix + "_mul", t1, c1, t1), + c.call(f2mPrefix + "_sub", t1, b_b, t1), + + // let t1 = t1.mul_by_nonresidue() + a_a; + c.call(f2mPrefix + "_mulNR", t1, t1), + c.call(f2mPrefix + "_add", t1, a_a, t1), + + // let t2 = (c0 + c1) * (self.c0 + self.c1) - a_a - b_b; + c.call(f2mPrefix + "_add", c0, c1, t2), + c.call(f2mPrefix + "_mul", t2, Ac0_Ac1, t2), + c.call(f2mPrefix + "_sub", t2, a_a, t2), + c.call(f2mPrefix + "_sub", t2, b_b, t2), + + // let t3 = (self.c0 + self.c2) * c0 - a_a + b_b; + c.call(f2mPrefix + "_mul", Ac0_Ac2, c0, t3), + c.call(f2mPrefix + "_sub", t3, a_a, t3), + c.call(f2mPrefix + "_add", t3, b_b, t3), + + + ); + } + buildF6Mul01(); + + + function buildF12Mul014() { + + const f = module.addFunction(ftmPrefix+ "_mul014"); + f.addParam("pA", "i32"); // F12 + f.addParam("pC0", "i32"); // F2 + f.addParam("pC1", "i32"); // F2 + f.addParam("pC4", "i32"); // F2 + f.addParam("pR", "i32"); // F12 + + const c = f.getCodeBuilder(); + + + const A_c0 = c.getLocal("pA"); + const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*6)); + + const c0 = c.getLocal("pC0"); + const c1 = c.getLocal("pC1"); + const c4 = c.getLocal("pC4"); + + const aa = c.i32_const(module.alloc(f1size*6)); + const bb = c.i32_const(module.alloc(f1size*6)); + const o = c.i32_const(module.alloc(f1size*2)); + + const R_c0 = c.getLocal("pR"); + const R_c1 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*6)); + + f.addCode( + // let aa = self.c0.mul_by_01(c0, c1); + c.call(f6mPrefix + "_mul01", A_c0, c0, c1, aa), + + // let bb = self.c1.mul_by_1(c4); + c.call(f6mPrefix + "_mul1", A_c1, c4, bb), + + // let o = c1 + c4; + c.call(f2mPrefix + "_add", c1, c4, o), + + // let c1 = self.c1 + self.c0; + c.call(f6mPrefix + "_add", A_c1, A_c0, R_c1), + + // let c1 = c1.mul_by_01(c0, &o); + c.call(f6mPrefix + "_mul01", R_c1, c0, o, R_c1), + + // let c1 = c1 - aa - bb; + c.call(f6mPrefix + "_sub", R_c1, aa, R_c1), + c.call(f6mPrefix + "_sub", R_c1, bb, R_c1), + + // let c0 = bb; + c.call(f6mPrefix + "_copy", bb, R_c0), + + // let c0 = c0.mul_by_nonresidue(); + c.call(f6mPrefix + "_mulNR", R_c0, R_c0), + + // let c0 = c0 + aa; + c.call(f6mPrefix + "_add", R_c0, aa, R_c0), + ); + } + buildF12Mul014(); + + + function buildELL() { + const f = module.addFunction(prefix+ "_ell"); + f.addParam("pP", "i32"); + f.addParam("pCoefs", "i32"); + f.addParam("pF", "i32"); + + const c = f.getCodeBuilder(); + + const Px = c.getLocal("pP"); + const Py = c.i32_add(c.getLocal("pP"), c.i32_const(n8q)); + + const F = c.getLocal("pF"); + + const coef0_0 = c.getLocal("pCoefs"); + const coef0_1 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size)); + const coef1_0 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*2)); + const coef1_1 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*3)); + const coef2 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*4)); + + const pc0 = module.alloc(f1size*2); + const c0 = c.i32_const(pc0); + const c0_c0 = c.i32_const(pc0); + const c0_c1 = c.i32_const(pc0+f1size); + + const pc1 = module.alloc(f1size*2); + const c1 = c.i32_const(pc1); + const c1_c0 = c.i32_const(pc1); + const c1_c1 = c.i32_const(pc1+f1size); + f.addCode( + // let mut c0 = coeffs.0; + // let mut c1 = coeffs.1; + // + // c0.c0 *= p.y; + // c0.c1 *= p.y; + // + // c1.c0 *= p.x; + // c1.c1 *= p.x; + // + // f.mul_by_014(&coeffs.2, &c1, &c0) + + c.call(f1mPrefix + "_mul", coef0_0, Py, c0_c0), + c.call(f1mPrefix + "_mul", coef0_1, Py, c0_c1), + c.call(f1mPrefix + "_mul", coef1_0, Px, c1_c0), + c.call(f1mPrefix + "_mul", coef1_1, Px, c1_c1), + + c.call(ftmPrefix + "_mul014", F, coef2, c1, c0, F), + + ); + + } + buildELL(); + + function buildMillerLoop() { + const f = module.addFunction(prefix+ "_millerLoop"); + f.addParam("ppreP", "i32"); + f.addParam("ppreQ", "i32"); + f.addParam("r", "i32"); + f.addLocal("pCoef", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const preP = c.getLocal("ppreP"); + + const coefs = c.getLocal("pCoef"); + + const F = c.getLocal("r"); + + + f.addCode( + c.call(ftmPrefix + "_one", F), + + c.if( + c.call(g1mPrefix + "_isZero", preP), + c.ret([]) + ), + c.if( + c.call(g1mPrefix + "_isZero", c.getLocal("ppreQ")), + c.ret([]) + ), + c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), + + c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), + c.block(c.loop( + + + c.call(prefix + "_ell", preP, coefs, F), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.if( + c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), + [ + ...c.call(prefix + "_ell", preP, coefs, F), + ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + ] + ), + c.call(ftmPrefix + "_square", F, F), + + c.br_if(1, c.i32_eq ( c.getLocal("i"), c.i32_const(1) )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + c.call(prefix + "_ell", preP, coefs, F), + + ); + + + { + f.addCode( + c.call(ftmPrefix + "_conjugate", F, F), + ); + } + } + + + function buildFrobeniusMap(n) { + const F12 = [ + [ + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + ], + [ + [1n, 0n], + [3850754370037169011952147076051364057158807420970682438676050522613628423219637725072182697113062777891589506424760n, 151655185184498381465642749684540099398075398968325446656007613510403227271200139370504932015952886146304766135027n], + [793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620351n, 0n], + [2973677408986561043442465346520108879172042883009249989176415018091420807192182638567116318576472649347015917690530n, 1028732146235106349975324479215795277384839936929757896155643118032610843298655225875571310552543014690878354869257n], + [793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350n, 0n], + [3125332594171059424908108096204648978570118281977575435832422631601824034463382777937621250592425535493320683825557n, 877076961050607968509681729531255177986764537961432449499635504522207616027455086505066378536590128544573588734230n], + [4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786n, 0n], + [151655185184498381465642749684540099398075398968325446656007613510403227271200139370504932015952886146304766135027n, 3850754370037169011952147076051364057158807420970682438676050522613628423219637725072182697113062777891589506424760n], + [4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436n, 0n], + [1028732146235106349975324479215795277384839936929757896155643118032610843298655225875571310552543014690878354869257n, 2973677408986561043442465346520108879172042883009249989176415018091420807192182638567116318576472649347015917690530n], + [4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939437n, 0n], + [877076961050607968509681729531255177986764537961432449499635504522207616027455086505066378536590128544573588734230n, 3125332594171059424908108096204648978570118281977575435832422631601824034463382777937621250592425535493320683825557n], + ] + ]; + + const F6 = [ + [ + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + ], + [ + [1n, 0n], + [0n, 4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436n], + [793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350n, 0n], + [0n, 1n], + [4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436n, 0n], + [0n, 793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350n], + ], + [ + [1n, 0n], + [4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939437n, 0n], + [4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436n, 0n], + [4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786n, 0n], + [793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350n, 0n], + [793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620351n, 0n], + ] + ]; + + const f = module.addFunction(ftmPrefix + "_frobeniusMap"+n); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + for (let i=0; i<6; i++) { + const X = (i==0) ? c.getLocal("x") : c.i32_add(c.getLocal("x"), c.i32_const(i*f2size)); + const Xc0 = X; + const Xc1 = c.i32_add(c.getLocal("x"), c.i32_const(i*f2size + f1size)); + const R = (i==0) ? c.getLocal("r") : c.i32_add(c.getLocal("r"), c.i32_const(i*f2size)); + const Rc0 = R; + const Rc1 = c.i32_add(c.getLocal("r"), c.i32_const(i*f2size + f1size)); + const coef = mul2(F12[Math.floor(i/3)][n%12] , F6[i%3][n%6]); + const pCoef = module.alloc([ + ...utils$1.bigInt2BytesLE(toMontgomery(coef[0]), n8q), + ...utils$1.bigInt2BytesLE(toMontgomery(coef[1]), n8q), + ]); + if (n%2 == 1) { + f.addCode( + c.call(f1mPrefix + "_copy", Xc0, Rc0), + c.call(f1mPrefix + "_neg", Xc1, Rc1), + c.call(f2mPrefix + "_mul", R, c.i32_const(pCoef), R), + ); + } else { + f.addCode(c.call(f2mPrefix + "_mul", X, c.i32_const(pCoef), R)); + } + } + + function mul2(a, b) { + const ac0 = a[0]; + const ac1 = a[1]; + const bc0 = b[0]; + const bc1 = b[1]; + const res = [ + (ac0 * bc0 - (ac1 * bc1)) % q, + (ac0 * bc1 + (ac1 * bc0)) % q, + ]; + if (isNegative$1(res[0])) res[0] = res[0] + q; + return res; + } + + } + + + function buildCyclotomicSquare() { + const f = module.addFunction(prefix+ "__cyclotomicSquare"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x4 = c.i32_add(c.getLocal("x"), c.i32_const(f2size)); + const x3 = c.i32_add(c.getLocal("x"), c.i32_const(2*f2size)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(3*f2size)); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(4*f2size)); + const x5 = c.i32_add(c.getLocal("x"), c.i32_const(5*f2size)); + + const r0 = c.getLocal("r"); + const r4 = c.i32_add(c.getLocal("r"), c.i32_const(f2size)); + const r3 = c.i32_add(c.getLocal("r"), c.i32_const(2*f2size)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(3*f2size)); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(4*f2size)); + const r5 = c.i32_add(c.getLocal("r"), c.i32_const(5*f2size)); + + const t0 = c.i32_const(module.alloc(f2size)); + const t1 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const t3 = c.i32_const(module.alloc(f2size)); + const t4 = c.i32_const(module.alloc(f2size)); + const t5 = c.i32_const(module.alloc(f2size)); + const tmp = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + + f.addCode( + // // t0 + t1*y = (z0 + z1*y)^2 = a^2 + // tmp = z0 * z1; + // t0 = (z0 + z1) * (z0 + my_Fp6::non_residue * z1) - tmp - my_Fp6::non_residue * tmp; + // t1 = tmp + tmp; + c.call(f2mPrefix + "_mul", x0, x1, tmp), + c.call(f2mPrefix + "_mulNR", x1, t0), + c.call(f2mPrefix + "_add", x0, t0, t0), + c.call(f2mPrefix + "_add", x0, x1, AUX), + c.call(f2mPrefix + "_mul", AUX, t0, t0), + c.call(f2mPrefix + "_mulNR", tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t0, AUX, t0), + c.call(f2mPrefix + "_add", tmp, tmp, t1), + + // // t2 + t3*y = (z2 + z3*y)^2 = b^2 + // tmp = z2 * z3; + // t2 = (z2 + z3) * (z2 + my_Fp6::non_residue * z3) - tmp - my_Fp6::non_residue * tmp; + // t3 = tmp + tmp; + c.call(f2mPrefix + "_mul", x2, x3, tmp), + c.call(f2mPrefix + "_mulNR", x3, t2), + c.call(f2mPrefix + "_add", x2, t2, t2), + c.call(f2mPrefix + "_add", x2, x3, AUX), + c.call(f2mPrefix + "_mul", AUX, t2, t2), + c.call(f2mPrefix + "_mulNR", tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t2, AUX, t2), + c.call(f2mPrefix + "_add", tmp, tmp, t3), + + // // t4 + t5*y = (z4 + z5*y)^2 = c^2 + // tmp = z4 * z5; + // t4 = (z4 + z5) * (z4 + my_Fp6::non_residue * z5) - tmp - my_Fp6::non_residue * tmp; + // t5 = tmp + tmp; + c.call(f2mPrefix + "_mul", x4, x5, tmp), + c.call(f2mPrefix + "_mulNR", x5, t4), + c.call(f2mPrefix + "_add", x4, t4, t4), + c.call(f2mPrefix + "_add", x4, x5, AUX), + c.call(f2mPrefix + "_mul", AUX, t4, t4), + c.call(f2mPrefix + "_mulNR", tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t4, AUX, t4), + c.call(f2mPrefix + "_add", tmp, tmp, t5), + + // For A + // z0 = 3 * t0 - 2 * z0 + c.call(f2mPrefix + "_sub", t0, x0, r0), + c.call(f2mPrefix + "_add", r0, r0, r0), + c.call(f2mPrefix + "_add", t0, r0, r0), + // z1 = 3 * t1 + 2 * z1 + c.call(f2mPrefix + "_add", t1, x1, r1), + c.call(f2mPrefix + "_add", r1, r1, r1), + c.call(f2mPrefix + "_add", t1, r1, r1), + + // For B + // z2 = 3 * (xi * t5) + 2 * z2 + c.call(f2mPrefix + "_mul", t5, c.i32_const(pBls12381Twist), AUX), + c.call(f2mPrefix + "_add", AUX, x2, r2), + c.call(f2mPrefix + "_add", r2, r2, r2), + c.call(f2mPrefix + "_add", AUX, r2, r2), + // z3 = 3 * t4 - 2 * z3 + c.call(f2mPrefix + "_sub", t4, x3, r3), + c.call(f2mPrefix + "_add", r3, r3, r3), + c.call(f2mPrefix + "_add", t4, r3, r3), + + // For C + // z4 = 3 * t2 - 2 * z4 + c.call(f2mPrefix + "_sub", t2, x4, r4), + c.call(f2mPrefix + "_add", r4, r4, r4), + c.call(f2mPrefix + "_add", t2, r4, r4), + // z5 = 3 * t3 + 2 * z5 + c.call(f2mPrefix + "_add", t3, x5, r5), + c.call(f2mPrefix + "_add", r5, r5, r5), + c.call(f2mPrefix + "_add", t3, r5, r5), + + ); + } + + + function buildCyclotomicExp(exponent, isExpNegative, fnName) { + const exponentNafBytes = naf(exponent).map( (b) => (b==-1 ? 0xFF: b) ); + const pExponentNafBytes = module.alloc(exponentNafBytes); + // const pExponent = module.alloc(utils.bigInt2BytesLE(exponent, n8)); + + const f = module.addFunction(prefix+ "__cyclotomicExp_"+fnName); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + f.addLocal("bit", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const x = c.getLocal("x"); + + const res = c.getLocal("r"); + + const inverse = c.i32_const(module.alloc(ftsize)); + + + f.addCode( + c.call(ftmPrefix + "_conjugate", x, inverse), + c.call(ftmPrefix + "_one", res), + + c.if( + c.teeLocal("bit", c.i32_load8_s(c.i32_const(exponentNafBytes.length-1), pExponentNafBytes)), + c.if( + c.i32_eq( + c.getLocal("bit"), + c.i32_const(1) + ), + c.call(ftmPrefix + "_mul", res, x, res), + c.call(ftmPrefix + "_mul", res, inverse, res), + ) + ), + + c.setLocal("i", c.i32_const(exponentNafBytes.length-2)), + c.block(c.loop( + c.call(prefix + "__cyclotomicSquare", res, res), + c.if( + c.teeLocal("bit", c.i32_load8_s(c.getLocal("i"), pExponentNafBytes)), + c.if( + c.i32_eq( + c.getLocal("bit"), + c.i32_const(1) + ), + c.call(ftmPrefix + "_mul", res, x, res), + c.call(ftmPrefix + "_mul", res, inverse, res), + ) + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + + if (isExpNegative) { + f.addCode( + c.call(ftmPrefix + "_conjugate", res, res), + ); + } + + } + + function buildFinalExponentiation() { + buildCyclotomicSquare(); + buildCyclotomicExp(finalExpZ, finalExpIsNegative, "w0"); + + const f = module.addFunction(prefix+ "_finalExponentiation"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const elt = c.getLocal("x"); + const res = c.getLocal("r"); + const t0 = c.i32_const(module.alloc(ftsize)); + const t1 = c.i32_const(module.alloc(ftsize)); + const t2 = c.i32_const(module.alloc(ftsize)); + const t3 = c.i32_const(module.alloc(ftsize)); + const t4 = c.i32_const(module.alloc(ftsize)); + const t5 = c.i32_const(module.alloc(ftsize)); + const t6 = c.i32_const(module.alloc(ftsize)); + + f.addCode( + + // let mut t0 = f.frobenius_map(6) + c.call(ftmPrefix + "_frobeniusMap6", elt, t0), + + // let t1 = f.invert() + c.call(ftmPrefix + "_inverse", elt, t1), + + // let mut t2 = t0 * t1; + c.call(ftmPrefix + "_mul", t0, t1, t2), + + // t1 = t2.clone(); + c.call(ftmPrefix + "_copy", t2, t1), + + // t2 = t2.frobenius_map().frobenius_map(); + c.call(ftmPrefix + "_frobeniusMap2", t2, t2), + + // t2 *= t1; + c.call(ftmPrefix + "_mul", t2, t1, t2), + + + // t1 = cyclotomic_square(t2).conjugate(); + c.call(prefix + "__cyclotomicSquare", t2, t1), + c.call(ftmPrefix + "_conjugate", t1, t1), + + // let mut t3 = cycolotomic_exp(t2); + c.call(prefix + "__cyclotomicExp_w0", t2, t3), + + // let mut t4 = cyclotomic_square(t3); + c.call(prefix + "__cyclotomicSquare", t3, t4), + + // let mut t5 = t1 * t3; + c.call(ftmPrefix + "_mul", t1, t3, t5), + + // t1 = cycolotomic_exp(t5); + c.call(prefix + "__cyclotomicExp_w0", t5, t1), + + // t0 = cycolotomic_exp(t1); + c.call(prefix + "__cyclotomicExp_w0", t1, t0), + + // let mut t6 = cycolotomic_exp(t0); + c.call(prefix + "__cyclotomicExp_w0", t0, t6), + + // t6 *= t4; + c.call(ftmPrefix + "_mul", t6, t4, t6), + + // t4 = cycolotomic_exp(t6); + c.call(prefix + "__cyclotomicExp_w0", t6, t4), + + // t5 = t5.conjugate(); + c.call(ftmPrefix + "_conjugate", t5, t5), + + // t4 *= t5 * t2; + c.call(ftmPrefix + "_mul", t4, t5, t4), + c.call(ftmPrefix + "_mul", t4, t2, t4), + + // t5 = t2.conjugate(); + c.call(ftmPrefix + "_conjugate", t2, t5), + + // t1 *= t2; + c.call(ftmPrefix + "_mul", t1, t2, t1), + + // t1 = t1.frobenius_map().frobenius_map().frobenius_map(); + c.call(ftmPrefix + "_frobeniusMap3", t1, t1), + + // t6 *= t5; + c.call(ftmPrefix + "_mul", t6, t5, t6), + + // t6 = t6.frobenius_map(); + c.call(ftmPrefix + "_frobeniusMap1", t6, t6), + + // t3 *= t0; + c.call(ftmPrefix + "_mul", t3, t0, t3), + + // t3 = t3.frobenius_map().frobenius_map(); + c.call(ftmPrefix + "_frobeniusMap2", t3, t3), + + // t3 *= t1; + c.call(ftmPrefix + "_mul", t3, t1, t3), + + // t3 *= t6; + c.call(ftmPrefix + "_mul", t3, t6, t3), + + // f = t3 * t4; + c.call(ftmPrefix + "_mul", t3, t4, res), + + ); + } + + + function buildFinalExponentiationOld() { + const f = module.addFunction(prefix+ "_finalExponentiationOld"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const exponent = 322277361516934140462891564586510139908379969514828494218366688025288661041104682794998680497580008899973249814104447692778988208376779573819485263026159588510513834876303014016798809919343532899164848730280942609956670917565618115867287399623286813270357901731510188149934363360381614501334086825442271920079363289954510565375378443704372994881406797882676971082200626541916413184642520269678897559532260949334760604962086348898118982248842634379637598665468817769075878555493752214492790122785850202957575200176084204422751485957336465472324810982833638490904279282696134323072515220044451592646885410572234451732790590013479358343841220074174848221722017083597872017638514103174122784843925578370430843522959600095676285723737049438346544753168912974976791528535276317256904336520179281145394686565050419250614107803233314658825463117900250701199181529205942363159325765991819433914303908860460720581408201373164047773794825411011922305820065611121544561808414055302212057471395719432072209245600258134364584636810093520285711072578721435517884103526483832733289802426157301542744476740008494780363354305116978805620671467071400711358839553375340724899735460480144599782014906586543813292157922220645089192130209334926661588737007768565838519456601560804957985667880395221049249803753582637708560n; + + const pExponent = module.alloc(utils$1.bigInt2BytesLE( exponent, 544 )); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(ftmPrefix + "_exp", c.getLocal("x"), c.i32_const(pExponent), c.i32_const(544), c.getLocal("r")), + ); + } + + + const pPreP = module.alloc(prePSize); + const pPreQ = module.alloc(preQSize); + + function buildPairingEquation(nPairings) { + + const f = module.addFunction(prefix+ "_pairingEq"+nPairings); + for (let i=0; i. */ -const bigInt = __webpack_require__(92096); +// module.exports.bn128_wasm = require("./build/bn128_wasm.js"); +// module.exports.bls12381_wasm = require("./build/bls12381_wasm.js"); +// module.exports.mnt6753_wasm = require("./build/mnt6753_wasm.js"); -exports.bigInt2BytesLE = function bigInt2BytesLE(_a, len) { - const b = Array(len); - let v = bigInt(_a); - for (let i=0; i { - -"use strict"; - - -var forEach = __webpack_require__(82682); -var availableTypedArrays = __webpack_require__(39209); -var callBind = __webpack_require__(10487); -var callBound = __webpack_require__(38075); -var gOPD = __webpack_require__(75795); - -/** @type {(O: object) => string} */ -var $toString = callBound('Object.prototype.toString'); -var hasToStringTag = __webpack_require__(49092)(); - -var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; -var typedArrays = availableTypedArrays(); - -var $slice = callBound('String.prototype.slice'); -var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); - -/** @type {(array: readonly T[], value: unknown) => number} */ -var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) { - for (var i = 0; i < array.length; i += 1) { - if (array[i] === value) { - return i; - } - } - return -1; -}; - -/** @typedef {(receiver: import('.').TypedArray) => string | typeof Uint8Array.prototype.slice.call | typeof Uint8Array.prototype.set.call} Getter */ -/** @type {{ [k in `\$${import('.').TypedArrayName}`]?: Getter } & { __proto__: null }} */ -var cache = { __proto__: null }; -if (hasToStringTag && gOPD && getPrototypeOf) { - forEach(typedArrays, function (typedArray) { - var arr = new g[typedArray](); - if (Symbol.toStringTag in arr) { - var proto = getPrototypeOf(arr); - // @ts-expect-error TS won't narrow inside a closure - var descriptor = gOPD(proto, Symbol.toStringTag); - if (!descriptor) { - var superProto = getPrototypeOf(proto); - // @ts-expect-error TS won't narrow inside a closure - descriptor = gOPD(superProto, Symbol.toStringTag); - } - // @ts-expect-error TODO: fix - cache['$' + typedArray] = callBind(descriptor.get); - } - }); -} else { - forEach(typedArrays, function (typedArray) { - var arr = new g[typedArray](); - var fn = arr.slice || arr.set; - if (fn) { - // @ts-expect-error TODO: fix - cache['$' + typedArray] = callBind(fn); - } - }); -} - -/** @type {(value: object) => false | import('.').TypedArrayName} */ -var tryTypedArrays = function tryAllTypedArrays(value) { - /** @type {ReturnType} */ var found = false; - forEach( - // eslint-disable-next-line no-extra-parens - /** @type {Record<`\$${TypedArrayName}`, Getter>} */ /** @type {any} */ (cache), - /** @type {(getter: Getter, name: `\$${import('.').TypedArrayName}`) => void} */ - function (getter, typedArray) { - if (!found) { - try { - // @ts-expect-error TODO: fix - if ('$' + getter(value) === typedArray) { - found = $slice(typedArray, 1); - } - } catch (e) { /**/ } - } - } - ); - return found; -}; - -/** @type {(value: object) => false | import('.').TypedArrayName} */ -var trySlices = function tryAllSlices(value) { - /** @type {ReturnType} */ var found = false; - forEach( - // eslint-disable-next-line no-extra-parens - /** @type {Record<`\$${TypedArrayName}`, Getter>} */ /** @type {any} */ (cache), - /** @type {(getter: typeof cache, name: `\$${import('.').TypedArrayName}`) => void} */ function (getter, name) { - if (!found) { - try { - // @ts-expect-error TODO: fix - getter(value); - found = $slice(name, 1); - } catch (e) { /**/ } - } - } - ); - return found; -}; - -/** @type {import('.')} */ -module.exports = function whichTypedArray(value) { - if (!value || typeof value !== 'object') { return false; } - if (!hasToStringTag) { - /** @type {string} */ - var tag = $slice($toString(value), 8, -1); - if ($indexOf(typedArrays, tag) > -1) { - return tag; - } - if (tag !== 'Object') { - return false; - } - // node < 0.6 hits here on real Typed Arrays - return trySlices(value); - } - if (!gOPD) { return null; } // unknown engine - return tryTypedArrays(value); -}; - - -/***/ }), - -/***/ 57510: -/***/ ((module) => { - -module.exports = extend - -var hasOwnProperty = Object.prototype.hasOwnProperty; - -function extend() { - var target = {} - - for (var i = 0; i < arguments.length; i++) { - var source = arguments[i] - - for (var key in source) { - if (hasOwnProperty.call(source, key)) { - target[key] = source[key] - } - } - } - - return target -} - - -/***/ }), - -/***/ 40259: -/***/ ((module) => { - -"use strict"; - -module.exports = function (Yallist) { - Yallist.prototype[Symbol.iterator] = function* () { - for (let walker = this.head; walker; walker = walker.next) { - yield walker.value - } - } -} - - -/***/ }), - -/***/ 28799: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - -module.exports = Yallist - -Yallist.Node = Node -Yallist.create = Yallist - -function Yallist (list) { - var self = this - if (!(self instanceof Yallist)) { - self = new Yallist() - } - - self.tail = null - self.head = null - self.length = 0 - - if (list && typeof list.forEach === 'function') { - list.forEach(function (item) { - self.push(item) - }) - } else if (arguments.length > 0) { - for (var i = 0, l = arguments.length; i < l; i++) { - self.push(arguments[i]) - } - } - - return self -} - -Yallist.prototype.removeNode = function (node) { - if (node.list !== this) { - throw new Error('removing node which does not belong to this list') - } - - var next = node.next - var prev = node.prev - - if (next) { - next.prev = prev - } - - if (prev) { - prev.next = next - } - - if (node === this.head) { - this.head = next - } - if (node === this.tail) { - this.tail = prev - } - - node.list.length-- - node.next = null - node.prev = null - node.list = null - - return next -} - -Yallist.prototype.unshiftNode = function (node) { - if (node === this.head) { - return - } - - if (node.list) { - node.list.removeNode(node) - } - - var head = this.head - node.list = this - node.next = head - if (head) { - head.prev = node - } - - this.head = node - if (!this.tail) { - this.tail = node - } - this.length++ -} - -Yallist.prototype.pushNode = function (node) { - if (node === this.tail) { - return - } - - if (node.list) { - node.list.removeNode(node) - } - - var tail = this.tail - node.list = this - node.prev = tail - if (tail) { - tail.next = node - } - - this.tail = node - if (!this.head) { - this.head = node - } - this.length++ -} - -Yallist.prototype.push = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - push(this, arguments[i]) - } - return this.length -} - -Yallist.prototype.unshift = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - unshift(this, arguments[i]) - } - return this.length -} - -Yallist.prototype.pop = function () { - if (!this.tail) { - return undefined - } - - var res = this.tail.value - this.tail = this.tail.prev - if (this.tail) { - this.tail.next = null - } else { - this.head = null - } - this.length-- - return res -} - -Yallist.prototype.shift = function () { - if (!this.head) { - return undefined - } - - var res = this.head.value - this.head = this.head.next - if (this.head) { - this.head.prev = null - } else { - this.tail = null - } - this.length-- - return res -} - -Yallist.prototype.forEach = function (fn, thisp) { - thisp = thisp || this - for (var walker = this.head, i = 0; walker !== null; i++) { - fn.call(thisp, walker.value, i, this) - walker = walker.next - } -} - -Yallist.prototype.forEachReverse = function (fn, thisp) { - thisp = thisp || this - for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { - fn.call(thisp, walker.value, i, this) - walker = walker.prev - } -} - -Yallist.prototype.get = function (n) { - for (var i = 0, walker = this.head; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.next - } - if (i === n && walker !== null) { - return walker.value - } -} - -Yallist.prototype.getReverse = function (n) { - for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.prev - } - if (i === n && walker !== null) { - return walker.value - } -} - -Yallist.prototype.map = function (fn, thisp) { - thisp = thisp || this - var res = new Yallist() - for (var walker = this.head; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)) - walker = walker.next - } - return res -} - -Yallist.prototype.mapReverse = function (fn, thisp) { - thisp = thisp || this - var res = new Yallist() - for (var walker = this.tail; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)) - walker = walker.prev - } - return res -} - -Yallist.prototype.reduce = function (fn, initial) { - var acc - var walker = this.head - if (arguments.length > 1) { - acc = initial - } else if (this.head) { - walker = this.head.next - acc = this.head.value - } else { - throw new TypeError('Reduce of empty list with no initial value') - } - - for (var i = 0; walker !== null; i++) { - acc = fn(acc, walker.value, i) - walker = walker.next - } - - return acc -} - -Yallist.prototype.reduceReverse = function (fn, initial) { - var acc - var walker = this.tail - if (arguments.length > 1) { - acc = initial - } else if (this.tail) { - walker = this.tail.prev - acc = this.tail.value - } else { - throw new TypeError('Reduce of empty list with no initial value') - } - - for (var i = this.length - 1; walker !== null; i--) { - acc = fn(acc, walker.value, i) - walker = walker.prev - } - - return acc -} - -Yallist.prototype.toArray = function () { - var arr = new Array(this.length) - for (var i = 0, walker = this.head; walker !== null; i++) { - arr[i] = walker.value - walker = walker.next - } - return arr -} - -Yallist.prototype.toArrayReverse = function () { - var arr = new Array(this.length) - for (var i = 0, walker = this.tail; walker !== null; i++) { - arr[i] = walker.value - walker = walker.prev - } - return arr -} - -Yallist.prototype.slice = function (from, to) { - to = to || this.length - if (to < 0) { - to += this.length - } - from = from || 0 - if (from < 0) { - from += this.length - } - var ret = new Yallist() - if (to < from || to < 0) { - return ret - } - if (from < 0) { - from = 0 - } - if (to > this.length) { - to = this.length - } - for (var i = 0, walker = this.head; walker !== null && i < from; i++) { - walker = walker.next - } - for (; walker !== null && i < to; i++, walker = walker.next) { - ret.push(walker.value) - } - return ret -} - -Yallist.prototype.sliceReverse = function (from, to) { - to = to || this.length - if (to < 0) { - to += this.length - } - from = from || 0 - if (from < 0) { - from += this.length - } - var ret = new Yallist() - if (to < from || to < 0) { - return ret - } - if (from < 0) { - from = 0 - } - if (to > this.length) { - to = this.length - } - for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { - walker = walker.prev - } - for (; walker !== null && i > from; i--, walker = walker.prev) { - ret.push(walker.value) - } - return ret -} - -Yallist.prototype.splice = function (start, deleteCount, ...nodes) { - if (start > this.length) { - start = this.length - 1 - } - if (start < 0) { - start = this.length + start; - } - - for (var i = 0, walker = this.head; walker !== null && i < start; i++) { - walker = walker.next - } - - var ret = [] - for (var i = 0; walker && i < deleteCount; i++) { - ret.push(walker.value) - walker = this.removeNode(walker) - } - if (walker === null) { - walker = this.tail - } - - if (walker !== this.head && walker !== this.tail) { - walker = walker.prev - } - - for (var i = 0; i < nodes.length; i++) { - walker = insert(this, walker, nodes[i]) - } - return ret; -} - -Yallist.prototype.reverse = function () { - var head = this.head - var tail = this.tail - for (var walker = head; walker !== null; walker = walker.prev) { - var p = walker.prev - walker.prev = walker.next - walker.next = p - } - this.head = tail - this.tail = head - return this -} - -function insert (self, node, value) { - var inserted = node === self.head ? - new Node(value, null, node, self) : - new Node(value, node, node.next, self) - - if (inserted.next === null) { - self.tail = inserted - } - if (inserted.prev === null) { - self.head = inserted - } - - self.length++ - - return inserted -} - -function push (self, item) { - self.tail = new Node(item, self.tail, null, self) - if (!self.head) { - self.head = self.tail - } - self.length++ -} - -function unshift (self, item) { - self.head = new Node(item, null, self.head, self) - if (!self.tail) { - self.tail = self.head - } - self.length++ -} - -function Node (value, prev, next, list) { - if (!(this instanceof Node)) { - return new Node(value, prev, next, list) - } - - this.list = list - this.value = value - - if (prev) { - prev.next = this - this.prev = prev - } else { - this.prev = null - } - - if (next) { - next.prev = this - this.next = next - } else { - this.next = null - } -} - -try { - // add if support for Symbol.iterator is present - __webpack_require__(40259)(Yallist) -} catch (er) {} - - -/***/ }), - -/***/ 5183: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 78982: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 47790: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 73776: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 21638: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 92668: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 77965: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 66089: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 79368: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 23276: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 59676: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 64688: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 51069: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 15340: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 79838: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 59817: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 71281: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 60513: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 2378: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 60290: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 47882: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 39209: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -var possibleNames = __webpack_require__(76578); - -var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; - -/** @type {import('.')} */ -module.exports = function availableTypedArrays() { - var /** @type {ReturnType} */ out = []; - for (var i = 0; i < possibleNames.length; i++) { - if (typeof g[possibleNames[i]] === 'function') { - // @ts-expect-error - out[out.length] = possibleNames[i]; - } - } - return out; -}; - - -/***/ }), - -/***/ 89082: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - HI: () => (/* reexport */ mimcsponge_buildMimcSponge), - vu: () => (/* reexport */ pedersen_hash_buildPedersenHash) -}); - -// UNUSED EXPORTS: SMT, SMTMemDb, buildBabyjub, buildEddsa, buildMimc7, buildPoseidon, buildPoseidonOpt, buildPoseidonReference, buildPoseidonWasm, buildSMT, evmasm, mimc7Contract, mimcSpongecontract, newMemEmptyTrie, poseidonContract - -// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/scalar_native.js -var scalar_native_namespaceObject = {}; -__webpack_require__.r(scalar_native_namespaceObject); -__webpack_require__.d(scalar_native_namespaceObject, { - abs: () => (abs), - add: () => (add), - band: () => (band), - bitLength: () => (bitLength), - bits: () => (bits), - bor: () => (bor), - bxor: () => (bxor), - div: () => (div), - e: () => (e), - eq: () => (eq), - exp: () => (exp), - fromArray: () => (fromArray), - fromString: () => (fromString), - geq: () => (geq), - gt: () => (gt), - isNegative: () => (isNegative), - isOdd: () => (isOdd), - isZero: () => (isZero), - land: () => (land), - leq: () => (leq), - lnot: () => (lnot), - lor: () => (lor), - lt: () => (lt), - mod: () => (mod), - mul: () => (mul), - naf: () => (naf), - neg: () => (neg), - neq: () => (neq), - pow: () => (pow), - shiftLeft: () => (shiftLeft), - shiftRight: () => (shiftRight), - shl: () => (shl), - shr: () => (shr), - square: () => (square), - sub: () => (sub), - toArray: () => (toArray), - toNumber: () => (toNumber) -}); - -// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/scalar_bigint.js -var scalar_bigint_namespaceObject = {}; -__webpack_require__.r(scalar_bigint_namespaceObject); -__webpack_require__.d(scalar_bigint_namespaceObject, { - abs: () => (scalar_bigint_abs), - add: () => (scalar_bigint_add), - band: () => (scalar_bigint_band), - bitLength: () => (scalar_bigint_bitLength), - bits: () => (scalar_bigint_bits), - bor: () => (scalar_bigint_bor), - bxor: () => (scalar_bigint_bxor), - div: () => (scalar_bigint_div), - e: () => (scalar_bigint_e), - eq: () => (scalar_bigint_eq), - exp: () => (scalar_bigint_exp), - fromArray: () => (scalar_bigint_fromArray), - fromString: () => (scalar_bigint_fromString), - geq: () => (scalar_bigint_geq), - gt: () => (scalar_bigint_gt), - isNegative: () => (scalar_bigint_isNegative), - isOdd: () => (scalar_bigint_isOdd), - isZero: () => (scalar_bigint_isZero), - land: () => (scalar_bigint_land), - leq: () => (scalar_bigint_leq), - lnot: () => (scalar_bigint_lnot), - lor: () => (scalar_bigint_lor), - lt: () => (scalar_bigint_lt), - mod: () => (scalar_bigint_mod), - mul: () => (scalar_bigint_mul), - naf: () => (scalar_bigint_naf), - neg: () => (scalar_bigint_neg), - neq: () => (scalar_bigint_neq), - pow: () => (scalar_bigint_pow), - shiftLeft: () => (scalar_bigint_shiftLeft), - shiftRight: () => (scalar_bigint_shiftRight), - shl: () => (scalar_bigint_shl), - shr: () => (scalar_bigint_shr), - square: () => (scalar_bigint_square), - sub: () => (scalar_bigint_sub), - toArray: () => (scalar_bigint_toArray), - toNumber: () => (scalar_bigint_toNumber) -}); - -// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/scalar.js -var scalar_namespaceObject = {}; -__webpack_require__.r(scalar_namespaceObject); -__webpack_require__.d(scalar_namespaceObject, { - abs: () => (scalar_abs), - add: () => (scalar_add), - band: () => (scalar_band), - bitLength: () => (scalar_bitLength), - bits: () => (scalar_bits), - bor: () => (scalar_bor), - bxor: () => (scalar_bxor), - div: () => (scalar_div), - e: () => (scalar_e), - eq: () => (scalar_eq), - exp: () => (scalar_exp), - fromArray: () => (scalar_fromArray), - fromRprBE: () => (fromRprBE), - fromRprLE: () => (fromRprLE), - fromString: () => (scalar_fromString), - geq: () => (scalar_geq), - gt: () => (scalar_gt), - isNegative: () => (scalar_isNegative), - isOdd: () => (scalar_isOdd), - isZero: () => (scalar_isZero), - land: () => (scalar_land), - leq: () => (scalar_leq), - lnot: () => (scalar_lnot), - lor: () => (scalar_lor), - lt: () => (scalar_lt), - mod: () => (scalar_mod), - mul: () => (scalar_mul), - naf: () => (scalar_naf), - neg: () => (scalar_neg), - neq: () => (scalar_neq), - one: () => (one), - pow: () => (scalar_pow), - shiftLeft: () => (scalar_shiftLeft), - shiftRight: () => (scalar_shiftRight), - shl: () => (scalar_shl), - shr: () => (scalar_shr), - square: () => (scalar_square), - sub: () => (scalar_sub), - toArray: () => (scalar_toArray), - toLEBuff: () => (toLEBuff), - toNumber: () => (scalar_toNumber), - toRprBE: () => (toRprBE), - toRprLE: () => (toRprLE), - toString: () => (scalar_toString), - zero: () => (zero) -}); - -// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/utils_native.js -var utils_native_namespaceObject = {}; -__webpack_require__.r(utils_native_namespaceObject); -__webpack_require__.d(utils_native_namespaceObject, { - beBuff2int: () => (beBuff2int), - beInt2Buff: () => (beInt2Buff), - leBuff2int: () => (leBuff2int), - leInt2Buff: () => (leInt2Buff), - stringifyBigInts: () => (stringifyBigInts), - stringifyFElements: () => (stringifyFElements), - unstringifyBigInts: () => (unstringifyBigInts), - unstringifyFElements: () => (unstringifyFElements) -}); - -// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/utils_bigint.js -var utils_bigint_namespaceObject = {}; -__webpack_require__.r(utils_bigint_namespaceObject); -__webpack_require__.d(utils_bigint_namespaceObject, { - beBuff2int: () => (utils_bigint_beBuff2int), - beInt2Buff: () => (utils_bigint_beInt2Buff), - leBuff2int: () => (utils_bigint_leBuff2int), - leInt2Buff: () => (utils_bigint_leInt2Buff), - stringifyBigInts: () => (utils_bigint_stringifyBigInts), - unstringifyBigInts: () => (utils_bigint_unstringifyBigInts) -}); - -// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/utils.js -var utils_namespaceObject = {}; -__webpack_require__.r(utils_namespaceObject); -__webpack_require__.d(utils_namespaceObject, { - array2buffer: () => (array2buffer), - beBuff2int: () => (utils_beBuff2int), - beInt2Buff: () => (utils_beInt2Buff), - bitReverse: () => (bitReverse), - buffReverseBits: () => (buffReverseBits), - buffer2array: () => (buffer2array), - leBuff2int: () => (utils_leBuff2int), - leInt2Buff: () => (utils_leInt2Buff), - log2: () => (utils_log2), - stringifyBigInts: () => (utils_stringifyBigInts), - stringifyFElements: () => (utils_stringifyFElements), - unstringifyBigInts: () => (utils_unstringifyBigInts), - unstringifyFElements: () => (utils_unstringifyFElements) -}); - -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/scalar_native.js /* global BigInt */ -const hexLen = [ 0, 1, 2, 2, 3, 3, 3, 3, 4 ,4 ,4 ,4 ,4 ,4 ,4 ,4]; - -function fromString(s, radix) { - if ((!radix)||(radix==10)) { - return BigInt(s); - } else if (radix==16) { - if (s.slice(0,2) == "0x") { - return BigInt(s); - } else { - return BigInt("0x"+s); - } - } -} - -const e = fromString; - -function fromArray(a, radix) { - let acc =BigInt(0); - radix = BigInt(radix); - for (let i=0; i> BigInt(n); -} - -const shl = shiftLeft; -const shr = shiftRight; - -function isOdd(a) { - return (BigInt(a) & BigInt(1)) == BigInt(1); -} - - -function naf(n) { - let E = BigInt(n); - const res = []; - while (E) { - if (E & BigInt(1)) { - const z = 2 - Number(E % BigInt(4)); - res.push( z ); - E = E - BigInt(z); - } else { - res.push( 0 ); - } - E = E >> BigInt(1); - } - return res; -} - - -function bits(n) { - let E = BigInt(n); - const res = []; - while (E) { - if (E & BigInt(1)) { - res.push(1); - } else { - res.push( 0 ); - } - E = E >> BigInt(1); - } - return res; -} - -function toNumber(s) { - if (s>BigInt(Number.MAX_SAFE_INTEGER )) { - throw new Error("Number too big"); - } - return Number(s); -} - -function toArray(s, radix) { - const res = []; - let rem = BigInt(s); - radix = BigInt(radix); - while (rem) { - res.unshift( Number(rem % radix)); - rem = rem / radix; - } - return res; -} - - -function add(a, b) { - return BigInt(a) + BigInt(b); -} - -function sub(a, b) { - return BigInt(a) - BigInt(b); -} - -function neg(a) { - return -BigInt(a); -} - -function mul(a, b) { - return BigInt(a) * BigInt(b); -} - -function square(a) { - return BigInt(a) * BigInt(a); -} - -function pow(a, b) { - return BigInt(a) ** BigInt(b); -} - -function exp(a, b) { - return BigInt(a) ** BigInt(b); -} - -function abs(a) { - return BigInt(a) >= 0 ? BigInt(a) : -BigInt(a); -} - -function div(a, b) { - return BigInt(a) / BigInt(b); -} - -function mod(a, b) { - return BigInt(a) % BigInt(b); -} - -function eq(a, b) { - return BigInt(a) == BigInt(b); -} - -function neq(a, b) { - return BigInt(a) != BigInt(b); -} - -function lt(a, b) { - return BigInt(a) < BigInt(b); -} - -function gt(a, b) { - return BigInt(a) > BigInt(b); -} - -function leq(a, b) { - return BigInt(a) <= BigInt(b); -} - -function geq(a, b) { - return BigInt(a) >= BigInt(b); -} - -function band(a, b) { - return BigInt(a) & BigInt(b); -} - -function bor(a, b) { - return BigInt(a) | BigInt(b); -} - -function bxor(a, b) { - return BigInt(a) ^ BigInt(b); -} - -function land(a, b) { - return BigInt(a) && BigInt(b); -} - -function lor(a, b) { - return BigInt(a) || BigInt(b); -} - -function lnot(a) { - return !BigInt(a); -} - - -// EXTERNAL MODULE: ./node_modules/big-integer/BigInteger.js -var BigInteger = __webpack_require__(92096); -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/scalar_bigint.js - - -function scalar_bigint_fromString(s, radix) { - if (typeof s == "string") { - if (s.slice(0,2) == "0x") { - return BigInteger(s.slice(2), 16); - } else { - return BigInteger(s,radix); - } - } else { - return BigInteger(s, radix); - } -} - -const scalar_bigint_e = scalar_bigint_fromString; - -function scalar_bigint_fromArray(a, radix) { - return BigInteger.fromArray(a, radix); -} - -function scalar_bigint_bitLength(a) { - return BigInteger(a).bitLength(); -} - -function scalar_bigint_isNegative(a) { - return BigInteger(a).isNegative(); -} - -function scalar_bigint_isZero(a) { - return BigInteger(a).isZero(); -} - -function scalar_bigint_shiftLeft(a, n) { - return BigInteger(a).shiftLeft(n); -} - -function scalar_bigint_shiftRight(a, n) { - return BigInteger(a).shiftRight(n); -} - -const scalar_bigint_shl = scalar_bigint_shiftLeft; -const scalar_bigint_shr = scalar_bigint_shiftRight; - -function scalar_bigint_isOdd(a) { - return BigInteger(a).isOdd(); -} - - -function scalar_bigint_naf(n) { - let E = BigInteger(n); - const res = []; - while (E.gt(BigInteger.zero)) { - if (E.isOdd()) { - const z = 2 - E.mod(4).toJSNumber(); - res.push( z ); - E = E.minus(z); - } else { - res.push( 0 ); - } - E = E.shiftRight(1); - } - return res; -} - -function scalar_bigint_bits(n) { - let E = BigInteger(n); - const res = []; - while (E.gt(BigInteger.zero)) { - if (E.isOdd()) { - res.push(1); - } else { - res.push( 0 ); - } - E = E.shiftRight(1); - } - return res; -} - -function scalar_bigint_toNumber(s) { - if (!s.lt(BigInteger("9007199254740992", 10))) { - throw new Error("Number too big"); - } - return s.toJSNumber(); -} - -function scalar_bigint_toArray(s, radix) { - return BigInteger(s).toArray(radix); -} - -function scalar_bigint_add(a, b) { - return BigInteger(a).add(BigInteger(b)); -} - -function scalar_bigint_sub(a, b) { - return BigInteger(a).minus(BigInteger(b)); -} - -function scalar_bigint_neg(a) { - return BigInteger.zero.minus(BigInteger(a)); -} - -function scalar_bigint_mul(a, b) { - return BigInteger(a).times(BigInteger(b)); -} - -function scalar_bigint_square(a) { - return BigInteger(a).square(); -} - -function scalar_bigint_pow(a, b) { - return BigInteger(a).pow(BigInteger(b)); -} - -function scalar_bigint_exp(a, b) { - return BigInteger(a).pow(BigInteger(b)); -} - -function scalar_bigint_abs(a) { - return BigInteger(a).abs(); -} - -function scalar_bigint_div(a, b) { - return BigInteger(a).divide(BigInteger(b)); -} - -function scalar_bigint_mod(a, b) { - return BigInteger(a).mod(BigInteger(b)); -} - -function scalar_bigint_eq(a, b) { - return BigInteger(a).eq(BigInteger(b)); -} - -function scalar_bigint_neq(a, b) { - return BigInteger(a).neq(BigInteger(b)); -} - -function scalar_bigint_lt(a, b) { - return BigInteger(a).lt(BigInteger(b)); -} - -function scalar_bigint_gt(a, b) { - return BigInteger(a).gt(BigInteger(b)); -} - -function scalar_bigint_leq(a, b) { - return BigInteger(a).leq(BigInteger(b)); -} - -function scalar_bigint_geq(a, b) { - return BigInteger(a).geq(BigInteger(b)); -} - -function scalar_bigint_band(a, b) { - return BigInteger(a).and(BigInteger(b)); -} - -function scalar_bigint_bor(a, b) { - return BigInteger(a).or(BigInteger(b)); -} - -function scalar_bigint_bxor(a, b) { - return BigInteger(a).xor(BigInteger(b)); -} - -function scalar_bigint_land(a, b) { - return (!BigInteger(a).isZero()) && (!BigInteger(b).isZero()); -} - -function scalar_bigint_lor(a, b) { - return (!BigInteger(a).isZero()) || (!BigInteger(b).isZero()); -} - -function scalar_bigint_lnot(a) { - return BigInteger(a).isZero(); -} - - - -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/scalar.js - - - - -const supportsNativeBigInt = typeof BigInt === "function"; - -let scalar_Scalar = {}; -if (supportsNativeBigInt) { - Object.assign(scalar_Scalar, scalar_native_namespaceObject); -} else { - Object.assign(scalar_Scalar, scalar_bigint_namespaceObject); -} - - -// Returns a buffer with Little Endian Representation -scalar_Scalar.toRprLE = function rprBE(buff, o, e, n8) { - const s = "0000000" + e.toString(16); - const v = new Uint32Array(buff.buffer, o, n8/4); - const l = (((s.length-7)*4 - 1) >> 5)+1; // Number of 32bit words; - for (let i=0; i> 5)+1; // Number of 32bit words; - for (let i=0; i a[a.length-i-1] = ch.toString(16).padStart(8,"0") ); - return scalar_Scalar.fromString(a.join(""), 16); -}; - -// Pases a buffer with Big Endian Representation -scalar_Scalar.fromRprBE = function rprLEM(buff, o, n8) { - n8 = n8 || buff.byteLength; - o = o || 0; - const v = new DataView(buff.buffer, buff.byteOffset + o, n8); - const a = new Array(n8/4); - for (let i=0; i. -*/ - -/* - This library does operations on polynomials with coefficients in a field F. - - A polynomial P(x) = p0 + p1 * x + p2 * x^2 + ... + pn * x^n is represented - by the array [ p0, p1, p2, ... , pn ]. - */ - -class PolField { - constructor (F) { - this.F = F; - - let rem = F.sqrt_t; - let s = F.sqrt_s; - - const five = this.F.add(this.F.add(this.F.two, this.F.two), this.F.one); - - this.w = new Array(s+1); - this.wi = new Array(s+1); - this.w[s] = this.F.pow(five, rem); - this.wi[s] = this.F.inv(this.w[s]); - - let n=s-1; - while (n>=0) { - this.w[n] = this.F.square(this.w[n+1]); - this.wi[n] = this.F.square(this.wi[n+1]); - n--; - } - - - this.roots = []; -/* for (let i=0; i<16; i++) { - let r = this.F.one; - n = 1 << i; - const rootsi = new Array(n); - for (let j=0; j this.F.sqrt_s) n = this.s; - for (let i=n; (i>=0) && (!this.roots[i]); i--) { - let r = this.F.one; - const nroots = 1 << i; - const rootsi = new Array(nroots); - for (let j=0; j a.length) { - [b, a] = [a, b]; - } - - if ((b.length <= 2) || (b.length < log2(a.length))) { - return this.mulNormal(a,b); - } else { - return this.mulFFT(a,b); - } - } - - mulNormal(a, b) { - let res = []; - for (let i=0; i0) { - const z = new Array(n).fill(this.F.zero); - return z.concat(p); - } else { - if (-n >= p.length) return []; - return p.slice(-n); - } - } - - eval2(p, x) { - let v = this.F.zero; - let ix = this.F.one; - for (let i=0; i> 1), - F.mul( - x, - _eval(p, newX, offset+step , step << 1, n >> 1))); - return res; - } - } - - lagrange(points) { - let roots = [this.F.one]; - for (let i=0; i> 1; - const p1 = this._fft(pall, bits-1, offset, step*2); - const p2 = this._fft(pall, bits-1, offset+step, step*2); - - const out = new Array(n); - - let m= this.F.one; - for (let i=0; i0 && this.F.eq(p[i], this.F.zero) ) i--; - return p.slice(0, i+1); - } - - eq(a, b) { - const pa = this.reduce(a); - const pb = this.reduce(b); - - if (pa.length != pb.length) return false; - for (let i=0; i=0; i--) { - res[i] = this.F.add(this.F.mul(res[i+1], r), p[i+1]); - } - return res; - } - - _next2Power(v) { - v--; - v |= v >> 1; - v |= v >> 2; - v |= v >> 4; - v |= v >> 8; - v |= v >> 16; - v++; - return v; - } - - toString(p) { - const ap = this.normalize(p); - let S = ""; - for (let i=ap.length-1; i>=0; i--) { - if (!this.F.eq(p[i], this.F.zero)) { - if (S!="") S += " + "; - S = S + p[i].toString(10); - if (i>0) { - S = S + "x"; - if (i>1) { - S = S + "^" +i; - } - } - } - } - return S; - } - - normalize(p) { - const res = new Array(p.length); - for (let i=0; i - // rec = x^(k-2-scaleV)/ v - // - // res = x^m/v = x^(m + (2*k-2 - scaleV) - (2*k-2 - scaleV)) /v => - // res = rec * x^(m - (2*k-2 - scaleV)) => - // res = rec * x^(m - 2*k + 2 + scaleV) - - const rec = this._reciprocal(this.scaleX(v, scaleV), kbits); - const res = this.scaleX(rec, m - 2*k + 2 + scaleV); - - return res; - } - - div(_u, _v) { - if (_u.length < _v.length) return []; - const kbits = log2(_v.length-1)+1; - const k = 1 << kbits; - - const u = this.scaleX(_u, k-_v.length); - const v = this.scaleX(_v, k-_v.length); - - const n = v.length-1; - let m = u.length-1; - - const s = this._reciprocal(v, kbits); - let t; - if (m>2*n) { - t = this.sub(this.scaleX([this.F.one], 2*n), this.mul(s, v)); - } - - let q = []; - let rem = u; - let us, ut; - let finish = false; - - while (!finish) { - us = this.mul(rem, s); - q = this.add(q, this.scaleX(us, -2*n)); - - if ( m > 2*n ) { - ut = this.mul(rem, t); - rem = this.scaleX(ut, -2*n); - m = rem.length-1; - } else { - finish = true; - } - } - - return q; - } - - - // returns the ith nth-root of one - oneRoot(n, i) { - let nbits = log2(n-1)+1; - let res = this.F.one; - let r = i; - - if(i>=n) { - throw new Error("Given 'i' should be lower than 'n'"); - } - else if (1<0) { - if (r & 1 == 1) { - res = this.F.mul(res, this.w[nbits]); - } - r = r >> 1; - nbits --; - } - return res; - } - - computeVanishingPolinomial(bits, t) { - const m = 1 << bits; - return this.F.sub(this.F.pow(t, m), this.F.one); - } - - evaluateLagrangePolynomials(bits, t) { - const m= 1 << bits; - const tm = this.F.pow(t, m); - const u= new Array(m).fill(this.F.zero); - this._setRoots(bits); - const omega = this.w[bits]; - - if (this.F.eq(tm, this.F.one)) { - for (let i = 0; i < m; i++) { - if (this.F.eq(this.roots[bits][0],t)) { // i.e., t equals omega^i - u[i] = this.F.one; - return u; - } - } - } - - const z = this.F.sub(tm, this.F.one); - // let l = this.F.mul(z, this.F.pow(this.F.twoinv, m)); - let l = this.F.mul(z, this.F.inv(this.F.e(m))); - for (let i = 0; i < m; i++) { - u[i] = this.F.mul(l, this.F.inv(this.F.sub(t,this.roots[bits][i]))); - l = this.F.mul(l, omega); - } - - return u; - } - - log2(V) { - return log2(V); - } -} - -function log2( V ) -{ - return( ( ( V & 0xFFFF0000 ) !== 0 ? ( V &= 0xFFFF0000, 16 ) : 0 ) | ( ( V & 0xFF00FF00 ) !== 0 ? ( V &= 0xFF00FF00, 8 ) : 0 ) | ( ( V & 0xF0F0F0F0 ) !== 0 ? ( V &= 0xF0F0F0F0, 4 ) : 0 ) | ( ( V & 0xCCCCCCCC ) !== 0 ? ( V &= 0xCCCCCCCC, 2 ) : 0 ) | ( ( V & 0xAAAAAAAA ) !== 0 ) ); -} - - -function __fft(PF, pall, bits, offset, step) { - - const n = 1 << bits; - if (n==1) { - return [ pall[offset] ]; - } else if (n==2) { - return [ - PF.F.add(pall[offset], pall[offset + step]), - PF.F.sub(pall[offset], pall[offset + step])]; - } - - const ndiv2 = n >> 1; - const p1 = __fft(PF, pall, bits-1, offset, step*2); - const p2 = __fft(PF, pall, bits-1, offset+step, step*2); - - const out = new Array(n); - - for (let i=0; i> 1; - const p1 = __fft2(PF, pall.slice(0, ndiv2), bits-1); - const p2 = __fft2(PF, pall.slice(ndiv2), bits-1); - - const out = new Array(n); - - for (let i=0; i>=1; - } - return res; -} - -function rev(idx, bits) { - return ( - _revTable[idx >>> 24] | - (_revTable[(idx >>> 16) & 0xFF] << 8) | - (_revTable[(idx >>> 8) & 0xFF] << 16) | - (_revTable[idx & 0xFF] << 24) - ) >>> (32-bits); -} - -function __bitReverse(p, bits) { - for (let k=0; kk) { - const tmp= p[k]; - p[k] = p[r]; - p[r] = tmp; - } - } - -} - - - -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/futils.js -/* - Copyright 2018 0kims association. - - This file is part of snarkjs. - - snarkjs is a free software: you can redistribute it and/or - modify it under the terms of the GNU General Public License as published by the - Free Software Foundation, either version 3 of the License, or (at your option) - any later version. - - snarkjs is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - more details. - - You should have received a copy of the GNU General Public License along with - snarkjs. If not, see . -*/ - - - - -function mulScalar(F, base, e) { - let res; - - if (Scalar.isZero(e)) return F.zero; - - const n = Scalar.naf(e); - - if (n[n.length-1] == 1) { - res = base; - } else if (n[n.length-1] == -1) { - res = F.neg(base); - } else { - throw new Error("invlaud NAF"); - } - - for (let i=n.length-2; i>=0; i--) { - - res = F.double(res); - - if (n[i] == 1) { - res = F.add(res, base); - } else if (n[i] == -1) { - res = F.sub(res, base); - } - } - - return res; -} - - -/* -exports.mulScalar = (F, base, e) =>{ - let res = F.zero; - let rem = bigInt(e); - let exp = base; - - while (! rem.eq(bigInt.zero)) { - if (rem.and(bigInt.one).eq(bigInt.one)) { - res = F.add(res, exp); - } - exp = F.double(exp); - rem = rem.shiftRight(1); - } - - return res; -}; -*/ - - -function futils_exp(F, base, e) { - - if (scalar_isZero(e)) return F.one; - - const n = scalar_bits(e); - - if (n.legth==0) return F.one; - - let res = base; - - for (let i=n.length-2; i>=0; i--) { - - res = F.square(res); - - if (n[i]) { - res = F.mul(res, base); - } - } - - return res; -} - - - -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/fsqrt.js - -// Check here: https://eprint.iacr.org/2012/685.pdf - -function fsqrt_buildSqrt (F) { - if ((F.m % 2) == 1) { - if (scalar_eq(scalar_mod(F.p, 4), 1 )) { - if (scalar_eq(scalar_mod(F.p, 8), 1 )) { - if (scalar_eq(scalar_mod(F.p, 16), 1 )) { - // alg7_muller(F); - alg5_tonelliShanks(F); - } else if (scalar_eq(scalar_mod(F.p, 16), 9 )) { - alg4_kong(F); - } else { - throw new Error("Field withot sqrt"); - } - } else if (scalar_eq(scalar_mod(F.p, 8), 5 )) { - alg3_atkin(F); - } else { - throw new Error("Field withot sqrt"); - } - } else if (scalar_eq(scalar_mod(F.p, 4), 3 )) { - alg2_shanks(F); - } - } else { - const pm2mod4 = scalar_mod(scalar_pow(F.p, F.m/2), 4); - if (pm2mod4 == 1) { - alg10_adj(F); - } else if (pm2mod4 == 3) { - alg9_adj(F); - } else { - alg8_complex(F); - } - - } -} - - -function alg5_tonelliShanks(F) { - F.sqrt_q = scalar_pow(F.p, F.m); - - F.sqrt_s = 0; - F.sqrt_t = scalar_sub(F.sqrt_q, 1); - - while (!scalar_isOdd(F.sqrt_t)) { - F.sqrt_s = F.sqrt_s + 1; - F.sqrt_t = scalar_div(F.sqrt_t, 2); - } - - let c0 = F.one; - - while (F.eq(c0, F.one)) { - const c = F.random(); - F.sqrt_z = F.pow(c, F.sqrt_t); - c0 = F.pow(F.sqrt_z, 2 ** (F.sqrt_s-1) ); - } - - F.sqrt_tm1d2 = scalar_div(scalar_sub(F.sqrt_t, 1),2); - - F.sqrt = function(a) { - const F=this; - if (F.isZero(a)) return F.zero; - let w = F.pow(a, F.sqrt_tm1d2); - const a0 = F.pow( F.mul(F.square(w), a), 2 ** (F.sqrt_s-1) ); - if (F.eq(a0, F.negone)) return null; - - let v = F.sqrt_s; - let x = F.mul(a, w); - let b = F.mul(x, w); - let z = F.sqrt_z; - while (!F.eq(b, F.one)) { - let b2k = F.square(b); - let k=1; - while (!F.eq(b2k, F.one)) { - b2k = F.square(b2k); - k++; - } - - w = z; - for (let i=0; i>> 0; - st[d] = (st[d] ^ st[a]) >>> 0; - st[d] = ((st[d] << 16) | ((st[d]>>>16) & 0xFFFF)) >>> 0; - - st[c] = (st[c] + st[d]) >>> 0; - st[b] = (st[b] ^ st[c]) >>> 0; - st[b] = ((st[b] << 12) | ((st[b]>>>20) & 0xFFF)) >>> 0; - - st[a] = (st[a] + st[b]) >>> 0; - st[d] = (st[d] ^ st[a]) >>> 0; - st[d] = ((st[d] << 8) | ((st[d]>>>24) & 0xFF)) >>> 0; - - st[c] = (st[c] + st[d]) >>> 0; - st[b] = (st[b] ^ st[c]) >>> 0; - st[b] = ((st[b] << 7) | ((st[b]>>>25) & 0x7F)) >>> 0; -} - -function doubleRound(st) { - quarterRound(st, 0, 4, 8,12); - quarterRound(st, 1, 5, 9,13); - quarterRound(st, 2, 6,10,14); - quarterRound(st, 3, 7,11,15); - - quarterRound(st, 0, 5,10,15); - quarterRound(st, 1, 6,11,12); - quarterRound(st, 2, 7, 8,13); - quarterRound(st, 3, 4, 9,14); -} - -class ChaCha { - - constructor(seed) { - seed = seed || [0,0,0,0,0,0,0,0]; - this.state = [ - 0x61707865, - 0x3320646E, - 0x79622D32, - 0x6B206574, - seed[0], - seed[1], - seed[2], - seed[3], - seed[4], - seed[5], - seed[6], - seed[7], - 0, - 0, - 0, - 0 - ]; - this.idx = 16; - this.buff = new Array(16); - } - - nextU32() { - if (this.idx == 16) this.update(); - return this.buff[this.idx++]; - } - - nextU64() { - return scalar_add(scalar_mul(this.nextU32(), 0x100000000), this.nextU32()); - } - - nextBool() { - return (this.nextU32() & 1) == 1; - } - - update() { - // Copy the state - for (let i=0; i<16; i++) this.buff[i] = this.state[i]; - - // Apply the rounds - for (let i=0; i<10; i++) doubleRound(this.buff); - - // Add to the initial - for (let i=0; i<16; i++) this.buff[i] = (this.buff[i] + this.state[i]) >>> 0; - - this.idx = 0; - - this.state[12] = (this.state[12] + 1) >>> 0; - if (this.state[12] != 0) return; - this.state[13] = (this.state[13] + 1) >>> 0; - if (this.state[13] != 0) return; - this.state[14] = (this.state[14] + 1) >>> 0; - if (this.state[14] != 0) return; - this.state[15] = (this.state[15] + 1) >>> 0; - } -} - -// EXTERNAL MODULE: ./node_modules/crypto-browserify/index.js -var crypto_browserify = __webpack_require__(91565); -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/random.js -/* provided dependency */ var process = __webpack_require__(65606); - - - -function getRandomBytes(n) { - let array = new Uint8Array(n); - if (process.browser) { // Browser - if (typeof globalThis.crypto !== "undefined") { // Supported - globalThis.crypto.getRandomValues(array); - } else { // fallback - for (let i=0; i>>0; - } - } - } - else { // NodeJS - crypto_browserify.randomFillSync(array); - } - return array; -} - -function getRandomSeed() { - const arr = getRandomBytes(32); - const arrV = new Uint32Array(arr.buffer); - const seed = []; - for (let i=0; i<8; i++) { - seed.push(arrV[i]); - } - return seed; -} - -let threadRng = null; - -function getThreadRng() { - if (threadRng) return threadRng; - threadRng = new ChaCha(getRandomSeed()); - return threadRng; -} - -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/f1field_native.js -/* global BigInt */ - - - - - -class ZqField { - constructor(p) { - this.type="F1"; - this.one = BigInt(1); - this.zero = BigInt(0); - this.p = BigInt(p); - this.m = 1; - this.negone = this.p-this.one; - this.two = BigInt(2); - this.half = this.p >> this.one; - this.bitLength = scalar_bitLength(this.p); - this.mask = (this.one << BigInt(this.bitLength)) - this.one; - - this.n64 = Math.floor((this.bitLength - 1) / 64)+1; - this.n32 = this.n64*2; - this.n8 = this.n64*8; - this.R = this.e(this.one << BigInt(this.n64*64)); - this.Ri = this.inv(this.R); - - const e = this.negone >> this.one; - this.nqr = this.two; - let r = this.pow(this.nqr, e); - while (!this.eq(r, this.negone)) { - this.nqr = this.nqr + this.one; - r = this.pow(this.nqr, e); - } - - - this.s = 0; - this.t = this.negone; - - while ((this.t & this.one) == this.zero) { - this.s = this.s + 1; - this.t = this.t >> this.one; - } - - this.nqr_to_t = this.pow(this.nqr, this.t); - - fsqrt_buildSqrt(this); - } - - e(a,b) { - let res; - if (!b) { - res = BigInt(a); - } else if (b==16) { - res = BigInt("0x"+a); - } - if (res < 0) { - let nres = -res; - if (nres >= this.p) nres = nres % this.p; - return this.p - nres; - } else { - return (res>= this.p) ? res%this.p : res; - } - - } - - add(a, b) { - const res = a + b; - return res >= this.p ? res-this.p : res; - } - - sub(a, b) { - return (a >= b) ? a-b : this.p-b+a; - } - - neg(a) { - return a ? this.p-a : a; - } - - mul(a, b) { - return (a*b)%this.p; - } - - mulScalar(base, s) { - return (base * this.e(s)) % this.p; - } - - square(a) { - return (a*a) % this.p; - } - - eq(a, b) { - return a==b; - } - - neq(a, b) { - return a!=b; - } - - lt(a, b) { - const aa = (a > this.half) ? a - this.p : a; - const bb = (b > this.half) ? b - this.p : b; - return aa < bb; - } - - gt(a, b) { - const aa = (a > this.half) ? a - this.p : a; - const bb = (b > this.half) ? b - this.p : b; - return aa > bb; - } - - leq(a, b) { - const aa = (a > this.half) ? a - this.p : a; - const bb = (b > this.half) ? b - this.p : b; - return aa <= bb; - } - - geq(a, b) { - const aa = (a > this.half) ? a - this.p : a; - const bb = (b > this.half) ? b - this.p : b; - return aa >= bb; - } - - div(a, b) { - return this.mul(a, this.inv(b)); - } - - idiv(a, b) { - if (!b) throw new Error("Division by zero"); - return a / b; - } - - inv(a) { - if (!a) throw new Error("Division by zero"); - - let t = this.zero; - let r = this.p; - let newt = this.one; - let newr = a % this.p; - while (newr) { - let q = r/newr; - [t, newt] = [newt, t-q*newt]; - [r, newr] = [newr, r-q*newr]; - } - if (t= this.p ? res-this.p : res; - } - - bor(a, b) { - const res = ((a | b) & this.mask); - return res >= this.p ? res-this.p : res; - } - - bxor(a, b) { - const res = ((a ^ b) & this.mask); - return res >= this.p ? res-this.p : res; - } - - bnot(a) { - const res = a ^ this.mask; - return res >= this.p ? res-this.p : res; - } - - shl(a, b) { - if (Number(b) < this.bitLength) { - const res = (a << b) & this.mask; - return res >= this.p ? res-this.p : res; - } else { - const nb = this.p - b; - if (Number(nb) < this.bitLength) { - return a >> nb; - } else { - return this.zero; - } - } - } - - shr(a, b) { - if (Number(b) < this.bitLength) { - return a >> b; - } else { - const nb = this.p - b; - if (Number(nb) < this.bitLength) { - const res = (a << nb) & this.mask; - return res >= this.p ? res-this.p : res; - } else { - return 0; - } - } - } - - land(a, b) { - return (a && b) ? this.one : this.zero; - } - - lor(a, b) { - return (a || b) ? this.one : this.zero; - } - - lnot(a) { - return (a) ? this.zero : this.one; - } - - sqrt_old(n) { - - if (n == this.zero) return this.zero; - - // Test that have solution - const res = this.pow(n, this.negone >> this.one); - if ( res != this.one ) return null; - - let m = this.s; - let c = this.nqr_to_t; - let t = this.pow(n, this.t); - let r = this.pow(n, this.add(this.t, this.one) >> this.one ); - - while ( t != this.one ) { - let sq = this.square(t); - let i = 1; - while (sq != this.one ) { - i++; - sq = this.square(sq); - } - - // b = c ^ m-i-1 - let b = c; - for (let j=0; j< m-i-1; j ++) b = this.square(b); - - m = i; - c = this.square(b); - t = this.mul(t, c); - r = this.mul(r, b); - } - - if (r > (this.p >> this.one)) { - r = this.neg(r); - } - - return r; - } - - normalize(a, b) { - a = BigInt(a,b); - if (a < 0) { - let na = -a; - if (na >= this.p) na = na % this.p; - return this.p - na; - } else { - return (a>= this.p) ? a%this.p : a; - } - } - - random() { - const nBytes = (this.bitLength*2 / 8); - let res =this.zero; - for (let i=0; i this.half) { - const v = this.p-a; - vs = "-"+v.toString(base); - } else { - vs = a.toString(base); - } - return vs; - } - - isZero(a) { - return a == this.zero; - } - - fromRng(rng) { - let v; - do { - v=this.zero; - for (let i=0; i= this.p); - v = (v * this.Ri) % this.p; // Convert from montgomery - return v; - } - -} - - -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/f1field_bigint.js - - - - -class f1field_bigint_ZqField { - constructor(p) { - this.type="F1"; - this.one = BigInteger.one; - this.zero = BigInteger.zero; - this.p = BigInteger(p); - this.m = 1; - this.negone = this.p.minus(BigInteger.one); - this.two = BigInteger(2); - this.half = this.p.shiftRight(1); - this.bitLength = this.p.bitLength(); - this.mask = BigInteger.one.shiftLeft(this.bitLength).minus(BigInteger.one); - - this.n64 = Math.floor((this.bitLength - 1) / 64)+1; - this.n32 = this.n64*2; - this.n8 = this.n64*8; - this.R = BigInteger.one.shiftLeft(this.n64*64); - this.Ri = this.inv(this.R); - - const e = this.negone.shiftRight(this.one); - this.nqr = this.two; - let r = this.pow(this.nqr, e); - while (!r.equals(this.negone)) { - this.nqr = this.nqr.add(this.one); - r = this.pow(this.nqr, e); - } - - this.s = this.zero; - this.t = this.negone; - - while (!this.t.isOdd()) { - this.s = this.s.add(this.one); - this.t = this.t.shiftRight(this.one); - } - - this.nqr_to_t = this.pow(this.nqr, this.t); - - fsqrt_buildSqrt(this); - } - - e(a,b) { - - const res = BigInteger(a,b); - - return this.normalize(res); - - } - - add(a, b) { - let res = a.add(b); - if (res.geq(this.p)) { - res = res.minus(this.p); - } - return res; - } - - sub(a, b) { - if (a.geq(b)) { - return a.minus(b); - } else { - return this.p.minus(b.minus(a)); - } - } - - neg(a) { - if (a.isZero()) return a; - return this.p.minus(a); - } - - mul(a, b) { - return a.times(b).mod(this.p); - } - - mulScalar(base, s) { - return base.times(BigInteger(s)).mod(this.p); - } - - square(a) { - return a.square().mod(this.p); - } - - eq(a, b) { - return a.eq(b); - } - - neq(a, b) { - return a.neq(b); - } - - lt(a, b) { - const aa = a.gt(this.half) ? a.minus(this.p) : a; - const bb = b.gt(this.half) ? b.minus(this.p) : b; - return aa.lt(bb); - } - - gt(a, b) { - const aa = a.gt(this.half) ? a.minus(this.p) : a; - const bb = b.gt(this.half) ? b.minus(this.p) : b; - return aa.gt(bb); - } - - leq(a, b) { - const aa = a.gt(this.half) ? a.minus(this.p) : a; - const bb = b.gt(this.half) ? b.minus(this.p) : b; - return aa.leq(bb); - } - - geq(a, b) { - const aa = a.gt(this.half) ? a.minus(this.p) : a; - const bb = b.gt(this.half) ? b.minus(this.p) : b; - return aa.geq(bb); - } - - div(a, b) { - if (b.isZero()) throw new Error("Division by zero"); - return a.times(b.modInv(this.p)).mod(this.p); - } - - idiv(a, b) { - if (b.isZero()) throw new Error("Division by zero"); - return a.divide(b); - } - - inv(a) { - if (a.isZero()) throw new Error("Division by zero"); - return a.modInv(this.p); - } - - mod(a, b) { - return a.mod(b); - } - - pow(a, b) { - return a.modPow(b, this.p); - } - - exp(a, b) { - return a.modPow(b, this.p); - } - - band(a, b) { - return a.and(b).and(this.mask).mod(this.p); - } - - bor(a, b) { - return a.or(b).and(this.mask).mod(this.p); - } - - bxor(a, b) { - return a.xor(b).and(this.mask).mod(this.p); - } - - bnot(a) { - return a.xor(this.mask).mod(this.p); - } - - shl(a, b) { - if (b.lt(this.bitLength)) { - return a.shiftLeft(b).and(this.mask).mod(this.p); - } else { - const nb = this.p.minus(b); - if (nb.lt(this.bitLength)) { - return this.shr(a, nb); - } else { - return BigInteger.zero; - } - } - } - - shr(a, b) { - if (b.lt(this.bitLength)) { - return a.shiftRight(b); - } else { - const nb = this.p.minus(b); - if (nb.lt(this.bitLength)) { - return this.shl(a, nb); - } else { - return BigInteger.zero; - } - } - } - - land(a, b) { - return (a.isZero() || b.isZero()) ? BigInteger.zero : BigInteger.one; - } - - lor(a, b) { - return (a.isZero() && b.isZero()) ? BigInteger.zero : BigInteger.one; - } - - lnot(a) { - return a.isZero() ? BigInteger.one : BigInteger.zero; - } - - sqrt_old(n) { - - if (n.equals(this.zero)) return this.zero; - - // Test that have solution - const res = this.pow(n, this.negone.shiftRight(this.one)); - if (!res.equals(this.one)) return null; - - let m = parseInt(this.s); - let c = this.nqr_to_t; - let t = this.pow(n, this.t); - let r = this.pow(n, this.add(this.t, this.one).shiftRight(this.one) ); - - while (!t.equals(this.one)) { - let sq = this.square(t); - let i = 1; - while (!sq.equals(this.one)) { - i++; - sq = this.square(sq); - } - - // b = c ^ m-i-1 - let b = c; - for (let j=0; j< m-i-1; j ++) b = this.square(b); - - m = i; - c = this.square(b); - t = this.mul(t, c); - r = this.mul(r, b); - } - - if (r.greater(this.p.shiftRight(this.one))) { - r = this.neg(r); - } - - return r; - } - - normalize(a) { - a = BigInteger(a); - if (a.isNegative()) { - return this.p.minus(a.abs().mod(this.p)); - } else { - return a.mod(this.p); - } - } - - random() { - let res = BigInteger(0); - let n = BigInteger(this.p.square()); - while (!n.isZero()) { - res = res.shiftLeft(8).add(BigInteger(getRandomBytes(1)[0])); - n = n.shiftRight(8); - } - return res.mod(this.p); - } - - toString(a, base) { - let vs; - if (!a.lesserOrEquals(this.p.shiftRight(BigInteger(1)))) { - const v = this.p.minus(a); - vs = "-"+v.toString(base); - } else { - vs = a.toString(base); - } - - return vs; - } - - isZero(a) { - return a.isZero(); - } - - fromRng(rng) { - let v; - do { - v = BigInteger(0); - for (let i=0; i. -*/ - - - - -class F2Field { - constructor(F, nonResidue) { - this.type="F2"; - this.F = F; - this.zero = [this.F.zero, this.F.zero]; - this.one = [this.F.one, this.F.zero]; - this.negone = this.neg(this.one); - this.nonResidue = nonResidue; - this.m = F.m*2; - this.p = F.p; - this.n64 = F.n64*2; - this.n32 = this.n64*2; - this.n8 = this.n64*8; - - buildSqrt(this); - } - - _mulByNonResidue(a) { - return this.F.mul(this.nonResidue, a); - } - - copy(a) { - return [this.F.copy(a[0]), this.F.copy(a[1])]; - } - - add(a, b) { - return [ - this.F.add(a[0], b[0]), - this.F.add(a[1], b[1]) - ]; - } - - double(a) { - return this.add(a,a); - } - - sub(a, b) { - return [ - this.F.sub(a[0], b[0]), - this.F.sub(a[1], b[1]) - ]; - } - - neg(a) { - return this.sub(this.zero, a); - } - - conjugate(a) { - return [ - a[0], - this.F.neg(a[1]) - ]; - } - - mul(a, b) { - const aA = this.F.mul(a[0] , b[0]); - const bB = this.F.mul(a[1] , b[1]); - - return [ - this.F.add( aA , this._mulByNonResidue(bB)), - this.F.sub( - this.F.mul( - this.F.add(a[0], a[1]), - this.F.add(b[0], b[1])), - this.F.add(aA, bB))]; - } - - inv(a) { - const t0 = this.F.square(a[0]); - const t1 = this.F.square(a[1]); - const t2 = this.F.sub(t0, this._mulByNonResidue(t1)); - const t3 = this.F.inv(t2); - return [ - this.F.mul(a[0], t3), - this.F.neg(this.F.mul( a[1], t3)) ]; - } - - div(a, b) { - return this.mul(a, this.inv(b)); - } - - square(a) { - const ab = this.F.mul(a[0] , a[1]); - - /* - [ - (a + b) * (a + non_residue * b) - ab - non_residue * ab, - ab + ab - ]; - */ - - return [ - this.F.sub( - this.F.mul( - this.F.add(a[0], a[1]) , - this.F.add( - a[0] , - this._mulByNonResidue(a[1]))), - this.F.add( - ab, - this._mulByNonResidue(ab))), - this.F.add(ab, ab) - ]; - } - - isZero(a) { - return this.F.isZero(a[0]) && this.F.isZero(a[1]); - } - - eq(a, b) { - return this.F.eq(a[0], b[0]) && this.F.eq(a[1], b[1]); - } - - mulScalar(base, e) { - return fUtils.mulScalar(this, base, e); - } - - pow(base, e) { - return fUtils.exp(this, base, e); - } - - exp(base, e) { - return fUtils.exp(this, base, e); - } - - toString(a) { - return `[ ${this.F.toString(a[0])} , ${this.F.toString(a[1])} ]`; - } - - fromRng(rng) { - const c0 = this.F.fromRng(rng); - const c1 = this.F.fromRng(rng); - return [c0, c1]; - } - - gt(a, b) { - if (this.F.gt(a[0], b[0])) return true; - if (this.F.gt(b[0], a[0])) return false; - if (this.F.gt(a[1], b[1])) return true; - return false; - } - - geq(a, b) { - return this.gt(a, b) || this.eq(a, b); - } - - lt(a, b) { - return !this.geq(a,b); - } - - leq(a, b) { - return !this.gt(a,b); - } - - neq(a, b) { - return !this.eq(a,b); - } - - random() { - return [this.F.random(), this.F.random()]; - } - - - toRprLE(buff, o, e) { - this.F.toRprLE(buff, o, e[0]); - this.F.toRprLE(buff, o+this.F.n8, e[1]); - } - - toRprBE(buff, o, e) { - this.F.toRprBE(buff, o, e[1]); - this.F.toRprBE(buff, o+this.F.n8, e[0]); - } - - toRprLEM(buff, o, e) { - this.F.toRprLEM(buff, o, e[0]); - this.F.toRprLEM(buff, o+this.F.n8, e[1]); - } - - - toRprBEM(buff, o, e) { - this.F.toRprBEM(buff, o, e[1]); - this.F.toRprBEM(buff, o+this.F.n8, e[0]); - } - - fromRprLE(buff, o) { - o = o || 0; - const c0 = this.F.fromRprLE(buff, o); - const c1 = this.F.fromRprLE(buff, o+this.F.n8); - return [c0, c1]; - } - - fromRprBE(buff, o) { - o = o || 0; - const c1 = this.F.fromRprBE(buff, o); - const c0 = this.F.fromRprBE(buff, o+this.F.n8); - return [c0, c1]; - } - - fromRprLEM(buff, o) { - o = o || 0; - const c0 = this.F.fromRprLEM(buff, o); - const c1 = this.F.fromRprLEM(buff, o+this.F.n8); - return [c0, c1]; - } - - fromRprBEM(buff, o) { - o = o || 0; - const c1 = this.F.fromRprBEM(buff, o); - const c0 = this.F.fromRprBEM(buff, o+this.F.n8); - return [c0, c1]; - } - -} - - -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/f3field.js -/* - Copyright 2018 0kims association. - - This file is part of snarkjs. - - snarkjs is a free software: you can redistribute it and/or - modify it under the terms of the GNU General Public License as published by the - Free Software Foundation, either version 3 of the License, or (at your option) - any later version. - - snarkjs is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - more details. - - You should have received a copy of the GNU General Public License along with - snarkjs. If not, see . -*/ - - - -class F3Field { - constructor(F, nonResidue) { - this.type="F3"; - this.F = F; - this.zero = [this.F.zero, this.F.zero, this.F.zero]; - this.one = [this.F.one, this.F.zero, this.F.zero]; - this.negone = this.neg(this.one); - this.nonResidue = nonResidue; - this.m = F.m*3; - this.p = F.p; - this.n64 = F.n64*3; - this.n32 = this.n64*2; - this.n8 = this.n64*8; - } - - _mulByNonResidue(a) { - return this.F.mul(this.nonResidue, a); - } - - copy(a) { - return [this.F.copy(a[0]), this.F.copy(a[1]), this.F.copy(a[2])]; - } - - add(a, b) { - return [ - this.F.add(a[0], b[0]), - this.F.add(a[1], b[1]), - this.F.add(a[2], b[2]) - ]; - } - - double(a) { - return this.add(a,a); - } - - sub(a, b) { - return [ - this.F.sub(a[0], b[0]), - this.F.sub(a[1], b[1]), - this.F.sub(a[2], b[2]) - ]; - } - - neg(a) { - return this.sub(this.zero, a); - } - - mul(a, b) { - - const aA = this.F.mul(a[0] , b[0]); - const bB = this.F.mul(a[1] , b[1]); - const cC = this.F.mul(a[2] , b[2]); - - return [ - this.F.add( - aA, - this._mulByNonResidue( - this.F.sub( - this.F.mul( - this.F.add(a[1], a[2]), - this.F.add(b[1], b[2])), - this.F.add(bB, cC)))), // aA + non_residue*((b+c)*(B+C)-bB-cC), - - this.F.add( - this.F.sub( - this.F.mul( - this.F.add(a[0], a[1]), - this.F.add(b[0], b[1])), - this.F.add(aA, bB)), - this._mulByNonResidue( cC)), // (a+b)*(A+B)-aA-bB+non_residue*cC - - this.F.add( - this.F.sub( - this.F.mul( - this.F.add(a[0], a[2]), - this.F.add(b[0], b[2])), - this.F.add(aA, cC)), - bB)]; // (a+c)*(A+C)-aA+bB-cC) - } - - inv(a) { - const t0 = this.F.square(a[0]); // t0 = a^2 ; - const t1 = this.F.square(a[1]); // t1 = b^2 ; - const t2 = this.F.square(a[2]); // t2 = c^2; - const t3 = this.F.mul(a[0],a[1]); // t3 = ab - const t4 = this.F.mul(a[0],a[2]); // t4 = ac - const t5 = this.F.mul(a[1],a[2]); // t5 = bc; - // c0 = t0 - non_residue * t5; - const c0 = this.F.sub(t0, this._mulByNonResidue(t5)); - // c1 = non_residue * t2 - t3; - const c1 = this.F.sub(this._mulByNonResidue(t2), t3); - const c2 = this.F.sub(t1, t4); // c2 = t1-t4 - - // t6 = (a * c0 + non_residue * (c * c1 + b * c2)).inv(); - const t6 = - this.F.inv( - this.F.add( - this.F.mul(a[0], c0), - this._mulByNonResidue( - this.F.add( - this.F.mul(a[2], c1), - this.F.mul(a[1], c2))))); - - return [ - this.F.mul(t6, c0), // t6*c0 - this.F.mul(t6, c1), // t6*c1 - this.F.mul(t6, c2)]; // t6*c2 - } - - div(a, b) { - return this.mul(a, this.inv(b)); - } - - square(a) { - const s0 = this.F.square(a[0]); // s0 = a^2 - const ab = this.F.mul(a[0], a[1]); // ab = a*b - const s1 = this.F.add(ab, ab); // s1 = 2ab; - const s2 = this.F.square( - this.F.add(this.F.sub(a[0],a[1]), a[2])); // s2 = (a - b + c)^2; - const bc = this.F.mul(a[1],a[2]); // bc = b*c - const s3 = this.F.add(bc, bc); // s3 = 2*bc - const s4 = this.F.square(a[2]); // s4 = c^2 - - - return [ - this.F.add( - s0, - this._mulByNonResidue(s3)), // s0 + non_residue * s3, - this.F.add( - s1, - this._mulByNonResidue(s4)), // s1 + non_residue * s4, - this.F.sub( - this.F.add( this.F.add(s1, s2) , s3 ), - this.F.add(s0, s4))]; // s1 + s2 + s3 - s0 - s4 - } - - isZero(a) { - return this.F.isZero(a[0]) && this.F.isZero(a[1]) && this.F.isZero(a[2]); - } - - eq(a, b) { - return this.F.eq(a[0], b[0]) && this.F.eq(a[1], b[1]) && this.F.eq(a[2], b[2]); - } - - affine(a) { - return [this.F.affine(a[0]), this.F.affine(a[1]), this.F.affine(a[2])]; - } - - mulScalar(base, e) { - return fUtils.mulScalar(this, base, e); - } - - pow(base, e) { - return fUtils.exp(this, base, e); - } - - exp(base, e) { - return fUtils.exp(this, base, e); - } - - toString(a) { - return `[ ${this.F.toString(a[0])} , ${this.F.toString(a[1])}, ${this.F.toString(a[2])} ]`; - } - - fromRng(rng) { - const c0 = this.F.fromRng(rng); - const c1 = this.F.fromRng(rng); - const c2 = this.F.fromRng(rng); - return [c0, c1, c2]; - } - - gt(a, b) { - if (this.F.gt(a[0], b[0])) return true; - if (this.F.gt(b[0], a[0])) return false; - if (this.F.gt(a[1], b[1])) return true; - if (this.F.gt(b[1], a[1])) return false; - if (this.F.gt(a[2], b[2])) return true; - return false; - } - - - geq(a, b) { - return this.gt(a, b) || this.eq(a, b); - } - - lt(a, b) { - return !this.geq(a,b); - } - - leq(a, b) { - return !this.gt(a,b); - } - - neq(a, b) { - return !this.eq(a,b); - } - - random() { - return [this.F.random(), this.F.random(), this.F.random()]; - } - - - toRprLE(buff, o, e) { - this.F.toRprLE(buff, o, e[0]); - this.F.toRprLE(buff, o+this.F.n8, e[1]); - this.F.toRprLE(buff, o+this.F.n8*2, e[2]); - } - - toRprBE(buff, o, e) { - this.F.toRprBE(buff, o, e[2]); - this.F.toRprBE(buff, o+this.F.n8, e[1]); - this.F.toRprBE(buff, o+this.F.n8*2, e[0]); - } - - toRprLEM(buff, o, e) { - this.F.toRprLEM(buff, o, e[0]); - this.F.toRprLEM(buff, o+this.F.n8, e[1]); - this.F.toRprLEM(buff, o+this.F.n8*2, e[2]); - } - - - toRprBEM(buff, o, e) { - this.F.toRprBEM(buff, o, e[2]); - this.F.toRprBEM(buff, o+this.F.n8, e[1]); - this.F.toRprBEM(buff, o+this.F.n8*2, e[0]); - } - - fromRprLE(buff, o) { - o = o || 0; - const c0 = this.F.fromRprLE(buff, o); - const c1 = this.F.fromRprLE(buff, o+this.n8); - const c2 = this.F.fromRprLE(buff, o+this.n8*2); - return [c0, c1, c2]; - } - - fromRprBE(buff, o) { - o = o || 0; - const c2 = this.F.fromRprBE(buff, o); - const c1 = this.F.fromRprBE(buff, o+this.n8); - const c0 = this.F.fromRprBE(buff, o+this.n8*2); - return [c0, c1, c2]; - } - - fromRprLEM(buff, o) { - o = o || 0; - const c0 = this.F.fromRprLEM(buff, o); - const c1 = this.F.fromRprLEM(buff, o+this.n8); - const c2 = this.F.fromRprLEM(buff, o+this.n8*2); - return [c0, c1, c2]; - } - - fromRprBEM(buff, o) { - o = o || 0; - const c2 = this.F.fromRprBEM(buff, o); - const c1 = this.F.fromRprBEM(buff, o+this.n8); - const c0 = this.F.fromRprBEM(buff, o+this.n8*2); - return [c0, c1, c2]; - } - -} - -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/ec.js -/* - Copyright 2018 0kims association. - - This file is part of snarkjs. - - snarkjs is a free software: you can redistribute it and/or - modify it under the terms of the GNU General Public License as published by the - Free Software Foundation, either version 3 of the License, or (at your option) - any later version. - - snarkjs is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - more details. - - You should have received a copy of the GNU General Public License along with - snarkjs. If not, see . -*/ - - - - - - - -function isGreatest(F, a) { - if (Array.isArray(a)) { - for (let i=a.length-1; i>=0; i--) { - if (!F.F.isZero(a[i])) { - return isGreatest(F.F, a[i]); - } - } - return 0; - } else { - const na = F.neg(a); - return Scalar.gt(a, na); - } -} - - -class EC { - - constructor(F, g) { - this.F = F; - this.g = g; - if (this.g.length == 2) this.g[2] = this.F.one; - this.zero = [this.F.zero, this.F.one, this.F.zero]; - } - - add(p1, p2) { - - const F = this.F; - - if (this.eq(p1, this.zero)) return p2; - if (this.eq(p2, this.zero)) return p1; - - const res = new Array(3); - - const Z1Z1 = F.square( p1[2] ); - const Z2Z2 = F.square( p2[2] ); - - const U1 = F.mul( p1[0] , Z2Z2 ); // U1 = X1 * Z2Z2 - const U2 = F.mul( p2[0] , Z1Z1 ); // U2 = X2 * Z1Z1 - - const Z1_cubed = F.mul( p1[2] , Z1Z1); - const Z2_cubed = F.mul( p2[2] , Z2Z2); - - const S1 = F.mul( p1[1] , Z2_cubed); // S1 = Y1 * Z2 * Z2Z2 - const S2 = F.mul( p2[1] , Z1_cubed); // S2 = Y2 * Z1 * Z1Z1 - - if (F.eq(U1,U2) && F.eq(S1,S2)) { - return this.double(p1); - } - - const H = F.sub( U2 , U1 ); // H = U2-U1 - - const S2_minus_S1 = F.sub( S2 , S1 ); - - const I = F.square( F.add(H,H) ); // I = (2 * H)^2 - const J = F.mul( H , I ); // J = H * I - - const r = F.add( S2_minus_S1 , S2_minus_S1 ); // r = 2 * (S2-S1) - const V = F.mul( U1 , I ); // V = U1 * I - - res[0] = - F.sub( - F.sub( F.square(r) , J ), - F.add( V , V )); // X3 = r^2 - J - 2 * V - - const S1_J = F.mul( S1 , J ); - - res[1] = - F.sub( - F.mul( r , F.sub(V,res[0])), - F.add( S1_J,S1_J )); // Y3 = r * (V-X3)-2 S1 J - - res[2] = - F.mul( - H, - F.sub( - F.square( F.add(p1[2],p2[2]) ), - F.add( Z1Z1 , Z2Z2 ))); // Z3 = ((Z1+Z2)^2-Z1Z1-Z2Z2) * H - - return res; - } - - neg(p) { - return [p[0], this.F.neg(p[1]), p[2]]; - } - - sub(a, b) { - return this.add(a, this.neg(b)); - } - - double(p) { - const F = this.F; - - const res = new Array(3); - - if (this.eq(p, this.zero)) return p; - - const A = F.square( p[0] ); // A = X1^2 - const B = F.square( p[1] ); // B = Y1^2 - const C = F.square( B ); // C = B^2 - - let D = - F.sub( - F.square( F.add(p[0] , B )), - F.add( A , C)); - D = F.add(D,D); // D = 2 * ((X1 + B)^2 - A - C) - - const E = F.add( F.add(A,A), A); // E = 3 * A - const FF =F.square( E ); // F = E^2 - - res[0] = F.sub( FF , F.add(D,D) ); // X3 = F - 2 D - - let eightC = F.add( C , C ); - eightC = F.add( eightC , eightC ); - eightC = F.add( eightC , eightC ); - - res[1] = - F.sub( - F.mul( - E, - F.sub( D, res[0] )), - eightC); // Y3 = E * (D - X3) - 8 * C - - const Y1Z1 = F.mul( p[1] , p[2] ); - res[2] = F.add( Y1Z1 , Y1Z1 ); // Z3 = 2 * Y1 * Z1 - - return res; - } - - timesScalar(base, e) { - return fUtils.mulScalar(this, base, e); - } - - mulScalar(base, e) { - return fUtils.mulScalar(this, base, e); - } - - affine(p) { - const F = this.F; - if (this.isZero(p)) { - return this.zero; - } else if (F.eq(p[2], F.one)) { - return p; - } else { - const Z_inv = F.inv(p[2]); - const Z2_inv = F.square(Z_inv); - const Z3_inv = F.mul(Z2_inv, Z_inv); - - const res = new Array(3); - res[0] = F.mul(p[0],Z2_inv); - res[1] = F.mul(p[1],Z3_inv); - res[2] = F.one; - - return res; - } - } - - multiAffine(arr) { - const keys = Object.keys(arr); - const F = this.F; - const accMul = new Array(keys.length+1); - accMul[0] = F.one; - for (let i = 0; i< keys.length; i++) { - if (F.eq(arr[keys[i]][2], F.zero)) { - accMul[i+1] = accMul[i]; - } else { - accMul[i+1] = F.mul(accMul[i], arr[keys[i]][2]); - } - } - - accMul[keys.length] = F.inv(accMul[keys.length]); - - for (let i = keys.length-1; i>=0; i--) { - if (F.eq(arr[keys[i]][2], F.zero)) { - accMul[i] = accMul[i+1]; - arr[keys[i]] = this.zero; - } else { - const Z_inv = F.mul(accMul[i], accMul[i+1]); - accMul[i] = F.mul(arr[keys[i]][2], accMul[i+1]); - - const Z2_inv = F.square(Z_inv); - const Z3_inv = F.mul(Z2_inv, Z_inv); - - arr[keys[i]][0] = F.mul(arr[keys[i]][0],Z2_inv); - arr[keys[i]][1] = F.mul(arr[keys[i]][1],Z3_inv); - arr[keys[i]][2] = F.one; - } - } - - } - - eq(p1, p2) { - const F = this.F; - - if (this.F.eq(p1[2], this.F.zero)) return this.F.eq(p2[2], this.F.zero); - if (this.F.eq(p2[2], this.F.zero)) return false; - - const Z1Z1 = F.square( p1[2] ); - const Z2Z2 = F.square( p2[2] ); - - const U1 = F.mul( p1[0] , Z2Z2 ); - const U2 = F.mul( p2[0] , Z1Z1 ); - - const Z1_cubed = F.mul( p1[2] , Z1Z1); - const Z2_cubed = F.mul( p2[2] , Z2Z2); - - const S1 = F.mul( p1[1] , Z2_cubed); - const S2 = F.mul( p2[1] , Z1_cubed); - - return (F.eq(U1,U2) && F.eq(S1,S2)); - } - - isZero(p) { - return this.F.isZero(p[2]); - } - - toString(p) { - const cp = this.affine(p); - return `[ ${this.F.toString(cp[0])} , ${this.F.toString(cp[1])} ]`; - } - - fromRng(rng) { - const F = this.F; - let P = []; - let greatest; - do { - P[0] = F.fromRng(rng); - greatest = rng.nextBool(); - const x3b = F.add(F.mul(F.square(P[0]), P[0]), this.b); - P[1] = F.sqrt(x3b); - } while ((P[1] == null)||(F.isZero[P])); - - const s = isGreatest(F, P[1]); - if (greatest ^ s) P[1] = F.neg(P[1]); - P[2] = F.one; - - if (this.cofactor) { - P = this.mulScalar(P, this.cofactor); - } - - P = this.affine(P); - - return P; - - } - - toRprLE(buff, o, p) { - p = this.affine(p); - if (this.isZero(p)) { - const BuffV = new Uint8Array(buff, o, this.F.n8*2); - BuffV.fill(0); - return; - } - this.F.toRprLE(buff, o, p[0]); - this.F.toRprLE(buff, o+this.F.n8, p[1]); - } - - toRprBE(buff, o, p) { - p = this.affine(p); - if (this.isZero(p)) { - const BuffV = new Uint8Array(buff, o, this.F.n8*2); - BuffV.fill(0); - return; - } - this.F.toRprBE(buff, o, p[0]); - this.F.toRprBE(buff, o+this.F.n8, p[1]); - } - - toRprLEM(buff, o, p) { - p = this.affine(p); - if (this.isZero(p)) { - const BuffV = new Uint8Array(buff, o, this.F.n8*2); - BuffV.fill(0); - return; - } - this.F.toRprLEM(buff, o, p[0]); - this.F.toRprLEM(buff, o+this.F.n8, p[1]); - } - - toRprLEJM(buff, o, p) { - p = this.affine(p); - if (this.isZero(p)) { - const BuffV = new Uint8Array(buff, o, this.F.n8*2); - BuffV.fill(0); - return; - } - this.F.toRprLEM(buff, o, p[0]); - this.F.toRprLEM(buff, o+this.F.n8, p[1]); - this.F.toRprLEM(buff, o+2*this.F.n8, p[2]); - } - - - toRprBEM(buff, o, p) { - p = this.affine(p); - if (this.isZero(p)) { - const BuffV = new Uint8Array(buff, o, this.F.n8*2); - BuffV.fill(0); - return; - } - this.F.toRprBEM(buff, o, p[0]); - this.F.toRprBEM(buff, o+this.F.n8, p[1]); - } - - fromRprLE(buff, o) { - o = o || 0; - const x = this.F.fromRprLE(buff, o); - const y = this.F.fromRprLE(buff, o+this.F.n8); - if (this.F.isZero(x) && this.F.isZero(y)) { - return this.zero; - } - return [x, y, this.F.one]; - } - - fromRprBE(buff, o) { - o = o || 0; - const x = this.F.fromRprBE(buff, o); - const y = this.F.fromRprBE(buff, o+this.F.n8); - if (this.F.isZero(x) && this.F.isZero(y)) { - return this.zero; - } - return [x, y, this.F.one]; - } - - fromRprLEM(buff, o) { - o = o || 0; - const x = this.F.fromRprLEM(buff, o); - const y = this.F.fromRprLEM(buff, o+this.F.n8); - if (this.F.isZero(x) && this.F.isZero(y)) { - return this.zero; - } - return [x, y, this.F.one]; - } - - fromRprLEJM(buff, o) { - o = o || 0; - const x = this.F.fromRprLEM(buff, o); - const y = this.F.fromRprLEM(buff, o+this.F.n8); - const z = this.F.fromRprLEM(buff, o+this.F.n8*2); - if (this.F.isZero(x) && this.F.isZero(y)) { - return this.zero; - } - return [x, y, z]; - } - - fromRprBEM(buff, o) { - o = o || 0; - const x = this.F.fromRprBEM(buff, o); - const y = this.F.fromRprBEM(buff, o+this.F.n8); - if (this.F.isZero(x) && this.F.isZero(y)) { - return this.zero; - } - return [x, y, this.F.one]; - } - - fromRprCompressed(buff, o) { - const F = this.F; - const v = new Uint8Array(buff.buffer, o, F.n8); - if (v[0] & 0x40) return this.zero; - const P = new Array(3); - - const greatest = ((v[0] & 0x80) != 0); - v[0] = v[0] & 0x7F; - P[0] = F.fromRprBE(buff, o); - if (greatest) v[0] = v[0] | 0x80; // set back again the old value - - const x3b = F.add(F.mul(F.square(P[0]), P[0]), this.b); - P[1] = F.sqrt(x3b); - - if (P[1] === null) { - throw new Error("Invalid Point!"); - } - - const s = isGreatest(F, P[1]); - if (greatest ^ s) P[1] = F.neg(P[1]); - P[2] = F.one; - - return P; - } - - toRprCompressed(buff, o, p) { - p = this.affine(p); - const v = new Uint8Array(buff.buffer, o, this.F.n8); - if (this.isZero(p)) { - v.fill(0); - v[0] = 0x40; - return; - } - this.F.toRprBE(buff, o, p[0]); - - if (isGreatest(this.F, p[1])) { - v[0] = v[0] | 0x80; - } - } - - - fromRprUncompressed(buff, o) { - if (buff[0] & 0x40) return this.zero; - - return this.fromRprBE(buff, o); - } - - toRprUncompressed(buff, o, p) { - this.toRprBE(buff, o, p); - - if (this.isZero(p)) { - buff[o] = buff[o] | 0x40; - } - } - - -} - - - -// EXTERNAL MODULE: ./node_modules/wasmcurves/index.js -var wasmcurves = __webpack_require__(70189); -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/utils_native.js -/* global BigInt */ - function stringifyBigInts(o) { - if ((typeof(o) == "bigint") || o.eq !== undefined) { + if (typeof o == "bigint" || o.eq !== undefined) { return o.toString(10); } else if (o instanceof Uint8Array) { return fromRprLE(o, 0); @@ -127057,7 +124538,7 @@ function stringifyBigInts(o) { } else if (typeof o == "object") { const res = {}; const keys = Object.keys(o); - keys.forEach( (k) => { + keys.forEach((k) => { res[k] = stringifyBigInts(o[k]); }); return res; @@ -127067,17 +124548,17 @@ function stringifyBigInts(o) { } function unstringifyBigInts(o) { - if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) { + if (typeof o == "string" && /^[0-9]+$/.test(o)) { return BigInt(o); - } else if ((typeof(o) == "string") && (/^0x[0-9a-fA-F]+$/.test(o) )) { + } else if (typeof o == "string" && /^0x[0-9a-fA-F]+$/.test(o)) { return BigInt(o); } else if (Array.isArray(o)) { return o.map(unstringifyBigInts); } else if (typeof o == "object") { - if (o===null) return null; + if (o === null) return null; const res = {}; const keys = Object.keys(o); - keys.forEach( (k) => { + keys.forEach((k) => { res[k] = unstringifyBigInts(o[k]); }); return res; @@ -127091,18 +124572,18 @@ function beBuff2int(buff) { let i = buff.length; let offset = 0; const buffV = new DataView(buff.buffer, buff.byteOffset, buff.byteLength); - while (i>0) { + while (i > 0) { if (i >= 4) { i -= 4; - res += BigInt(buffV.getUint32(i)) << BigInt(offset*8); + res += BigInt(buffV.getUint32(i)) << BigInt(offset * 8); offset += 4; } else if (i >= 2) { i -= 2; - res += BigInt(buffV.getUint16(i)) << BigInt(offset*8); + res += BigInt(buffV.getUint16(i)) << BigInt(offset * 8); offset += 2; } else { i -= 1; - res += BigInt(buffV.getUint8(i)) << BigInt(offset*8); + res += BigInt(buffV.getUint8(i)) << BigInt(offset * 8); offset += 1; } } @@ -127115,17 +124596,17 @@ function beInt2Buff(n, len) { const buffV = new DataView(buff.buffer); let o = len; while (o > 0) { - if (o-4 >= 0) { + if (o - 4 >= 0) { o -= 4; - buffV.setUint32(o, Number(r & BigInt(0xFFFFFFFF))); + buffV.setUint32(o, Number(r & BigInt(0xffffffff))); r = r >> BigInt(32); - } else if (o-2 >= 0) { + } else if (o - 2 >= 0) { o -= 2; - buffV.setUint16(o, Number(r & BigInt(0xFFFF))); + buffV.setUint16(o, Number(r & BigInt(0xffff))); r = r >> BigInt(16); } else { o -= 1; - buffV.setUint8(o, Number(r & BigInt(0xFF))); + buffV.setUint8(o, Number(r & BigInt(0xff))); r = r >> BigInt(8); } } @@ -127135,20 +124616,19 @@ function beInt2Buff(n, len) { return buff; } - function leBuff2int(buff) { let res = BigInt(0); let i = 0; const buffV = new DataView(buff.buffer, buff.byteOffset, buff.byteLength); - while (i> BigInt(32); - } else if (o+2 <= len) { - buffV.setUint16(Number(o, r & BigInt(0xFFFF)), true ); + } else if (o + 2 <= len) { + buffV.setUint16(o, Number(r & BigInt(0xffff)), true); o += 2; r = r >> BigInt(16); } else { - buffV.setUint8(Number(o, r & BigInt(0xFF)), true ); + buffV.setUint8(o, Number(r & BigInt(0xff)), true); o += 1; r = r >> BigInt(8); } @@ -127185,18 +124665,17 @@ function leInt2Buff(n, len) { return buff; } - function stringifyFElements(F, o) { - if ((typeof(o) == "bigint") || o.eq !== undefined) { + if (typeof o == "bigint" || o.eq !== undefined) { return o.toString(10); } else if (o instanceof Uint8Array) { return F.toString(F.e(o)); } else if (Array.isArray(o)) { - return o.map(stringifyFElements.bind(this,F)); + return o.map(stringifyFElements.bind(this, F)); } else if (typeof o == "object") { const res = {}; const keys = Object.keys(o); - keys.forEach( (k) => { + keys.forEach((k) => { res[k] = stringifyFElements(F, o[k]); }); return res; @@ -127205,19 +124684,18 @@ function stringifyFElements(F, o) { } } - function unstringifyFElements(F, o) { - if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) { + if (typeof o == "string" && /^[0-9]+$/.test(o)) { return F.e(o); - } else if ((typeof(o) == "string") && (/^0x[0-9a-fA-F]+$/.test(o) )) { + } else if (typeof o == "string" && /^0x[0-9a-fA-F]+$/.test(o)) { return F.e(o); } else if (Array.isArray(o)) { - return o.map(unstringifyFElements.bind(this,F)); + return o.map(unstringifyFElements.bind(this, F)); } else if (typeof o == "object") { - if (o===null) return null; + if (o === null) return null; const res = {}; const keys = Object.keys(o); - keys.forEach( (k) => { + keys.forEach((k) => { res[k] = unstringifyFElements(F, o[k]); }); return res; @@ -127226,195 +124704,93 @@ function unstringifyFElements(F, o) { } } -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/utils_bigint.js - - -function utils_bigint_stringifyBigInts(o) { - if ((typeof(o) == "bigint") || o.eq !== undefined) { - return o.toString(10); - } else if (Array.isArray(o)) { - return o.map(utils_bigint_stringifyBigInts); - } else if (typeof o == "object") { - const res = {}; - const keys = Object.keys(o); - keys.forEach( (k) => { - res[k] = utils_bigint_stringifyBigInts(o[k]); - }); - return res; - } else { - return o; - } +const _revTable = []; +for (let i = 0; i < 256; i++) { + _revTable[i] = _revSlow(i, 8); } -function utils_bigint_unstringifyBigInts(o) { - if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) { - return BigInteger(o); - } else if ((typeof(o) == "string") && (/^0x[0-9a-fA-F]+$/.test(o) )) { - return BigInteger(o); - } else if (Array.isArray(o)) { - return o.map(utils_bigint_unstringifyBigInts); - } else if (typeof o == "object") { - const res = {}; - const keys = Object.keys(o); - keys.forEach( (k) => { - res[k] = utils_bigint_unstringifyBigInts(o[k]); - }); - return res; - } else { - return o; - } -} - -function utils_bigint_beBuff2int(buff) { - let res = BigInteger.zero; - for (let i=0; i=0)) { - let c = Number(r.and(BigInteger("255"))); - buff[o] = c; - o--; - r = r.shiftRight(8); - } - if (!r.eq(BigInteger.zero)) { - throw new Error("Number does not fit in this length"); - } - return buff; -} - - -function utils_bigint_leBuff2int (buff) { - let res = BigInteger.zero; - for (let i=0; i>=1; + res = res | (a & 1); + a >>= 1; } return res; } -utils.bitReverse = function bitReverse(idx, bits) { +function bitReverse(idx, bits) { return ( - utils_revTable[idx >>> 24] | - (utils_revTable[(idx >>> 16) & 0xFF] << 8) | - (utils_revTable[(idx >>> 8) & 0xFF] << 16) | - (utils_revTable[idx & 0xFF] << 24) - ) >>> (32-bits); -}; + (_revTable[idx >>> 24] | + (_revTable[(idx >>> 16) & 0xff] << 8) | + (_revTable[(idx >>> 8) & 0xff] << 16) | + (_revTable[idx & 0xff] << 24)) >>> + (32 - bits) + ); +} +function log2(V) { + return ( + ((V & 0xffff0000) !== 0 ? ((V &= 0xffff0000), 16) : 0) | + ((V & 0xff00ff00) !== 0 ? ((V &= 0xff00ff00), 8) : 0) | + ((V & 0xf0f0f0f0) !== 0 ? ((V &= 0xf0f0f0f0), 4) : 0) | + ((V & 0xcccccccc) !== 0 ? ((V &= 0xcccccccc), 2) : 0) | + ((V & 0xaaaaaaaa) !== 0) + ); +} -utils.log2 = function log2( V ) -{ - return( ( ( V & 0xFFFF0000 ) !== 0 ? ( V &= 0xFFFF0000, 16 ) : 0 ) | ( ( V & 0xFF00FF00 ) !== 0 ? ( V &= 0xFF00FF00, 8 ) : 0 ) | ( ( V & 0xF0F0F0F0 ) !== 0 ? ( V &= 0xF0F0F0F0, 4 ) : 0 ) | ( ( V & 0xCCCCCCCC ) !== 0 ? ( V &= 0xCCCCCCCC, 2 ) : 0 ) | ( ( V & 0xAAAAAAAA ) !== 0 ) ); -}; - -utils.buffReverseBits = function buffReverseBits(buff, eSize) { - const n = buff.byteLength /eSize; - const bits = utils.log2(n); - if (n != (1 << bits)) { +function buffReverseBits(buff, eSize) { + const n = buff.byteLength / eSize; + const bits = log2(n); + if (n != 1 << bits) { throw new Error("Invalid number of pointers"); } - for (let i=0; ir) { - const tmp = buff.slice(i*eSize, (i+1)*eSize); - buff.set( buff.slice(r*eSize, (r+1)*eSize), i*eSize); - buff.set(tmp, r*eSize); + for (let i = 0; i < n; i++) { + const r = bitReverse(i, bits); + if (i > r) { + const tmp = buff.slice(i * eSize, (i + 1) * eSize); + buff.set(buff.slice(r * eSize, (r + 1) * eSize), i * eSize); + buff.set(tmp, r * eSize); } } -}; +} +function array2buffer(arr, sG) { + const buff = new Uint8Array(sG * arr.length); -utils.array2buffer = function(arr, sG) { - const buff = new Uint8Array(sG*arr.length); - - for (let i=0; i { @@ -128854,14 +126183,12 @@ function sleep(ms) { } function stringToBase64(str) { - if (threadman_process.browser) { + { return globalThis.btoa(str); - } else { - return Buffer.from(str).toString("base64"); } } -const threadSource = stringToBase64("(" + thread.toString() + ")(self)"); +const threadSource = stringToBase64("(" + "function thread(self) {\n const MAXMEM = 32767;\n let instance;\n let memory;\n\n if (self) {\n self.onmessage = function(e) {\n let data;\n if (e.data) {\n data = e.data;\n } else {\n data = e;\n }\n\n if (data[0].cmd == \"INIT\") {\n init(data[0]).then(function() {\n self.postMessage(data.result);\n });\n } else if (data[0].cmd == \"TERMINATE\") {\n self.close();\n } else {\n const res = runTask(data);\n self.postMessage(res);\n }\n };\n }\n\n async function init(data) {\n const code = new Uint8Array(data.code);\n const wasmModule = await WebAssembly.compile(code);\n memory = new WebAssembly.Memory({initial:data.init, maximum: MAXMEM});\n\n instance = await WebAssembly.instantiate(wasmModule, {\n env: {\n \"memory\": memory\n }\n });\n }\n\n\n\n function alloc(length) {\n const u32 = new Uint32Array(memory.buffer, 0, 1);\n while (u32[0] & 3) u32[0]++; // Return always aligned pointers\n const res = u32[0];\n u32[0] += length;\n if (u32[0] + length > memory.buffer.byteLength) {\n const currentPages = memory.buffer.byteLength / 0x10000;\n let requiredPages = Math.floor((u32[0] + length) / 0x10000)+1;\n if (requiredPages>MAXMEM) requiredPages=MAXMEM;\n memory.grow(requiredPages-currentPages);\n }\n return res;\n }\n\n function allocBuffer(buffer) {\n const p = alloc(buffer.byteLength);\n setBuffer(p, buffer);\n return p;\n }\n\n function getBuffer(pointer, length) {\n const u8 = new Uint8Array(memory.buffer);\n return new Uint8Array(u8.buffer, u8.byteOffset + pointer, length);\n }\n\n function setBuffer(pointer, buffer) {\n const u8 = new Uint8Array(memory.buffer);\n u8.set(new Uint8Array(buffer), pointer);\n }\n\n function runTask(task) {\n if (task[0].cmd == \"INIT\") {\n return init(task[0]);\n }\n const ctx = {\n vars: [],\n out: []\n };\n const u32a = new Uint32Array(memory.buffer, 0, 1);\n const oldAlloc = u32a[0];\n for (let i=0; i. +*/ + +function toNumber(n) { + return BigInt(n); +} + +function isNegative(n) { + return n < 0n; +} + +function isZero(n) { + return n === 0n; +} + +function bitLength(n) { + if (isNegative(n)) { + return n.toString(2).length - 1; // discard the - sign + } else { + return n.toString(2).length; + } +} + +function u32(n) { + const b = []; + const v = toNumber(n); + b.push(Number(v & 0xFFn)); + b.push(Number(v >> 8n & 0xFFn)); + b.push(Number(v >> 16n & 0xFFn)); + b.push(Number(v >> 24n & 0xFFn)); + return b; +} + +function toUTF8Array(str) { + var utf8 = []; + for (var i=0; i < str.length; i++) { + var charcode = str.charCodeAt(i); + if (charcode < 0x80) utf8.push(charcode); + else if (charcode < 0x800) { + utf8.push(0xc0 | (charcode >> 6), + 0x80 | (charcode & 0x3f)); + } + else if (charcode < 0xd800 || charcode >= 0xe000) { + utf8.push(0xe0 | (charcode >> 12), + 0x80 | ((charcode>>6) & 0x3f), + 0x80 | (charcode & 0x3f)); + } + // surrogate pair + else { + i++; + // UTF-16 encodes 0x10000-0x10FFFF by + // subtracting 0x10000 and splitting the + // 20 bits of 0x0-0xFFFFF into two halves + charcode = 0x10000 + (((charcode & 0x3ff)<<10) + | (str.charCodeAt(i) & 0x3ff)); + utf8.push(0xf0 | (charcode >>18), + 0x80 | ((charcode>>12) & 0x3f), + 0x80 | ((charcode>>6) & 0x3f), + 0x80 | (charcode & 0x3f)); + } + } + return utf8; +} + +function string(str) { + const bytes = toUTF8Array(str); + return [ ...varuint32(bytes.length), ...bytes ]; +} + +function varuint(n) { + const code = []; + let v = toNumber(n); + if (isNegative(v)) throw new Error("Number cannot be negative"); + while (!isZero(v)) { + code.push(Number(v & 0x7Fn)); + v = v >> 7n; + } + if (code.length==0) code.push(0); + for (let i=0; i 0xFFFFFFFFn) throw new Error("Number too big"); + if (v > 0x7FFFFFFFn) v = v - 0x100000000n; + // bigInt("-80000000", 16) as base10 + if (v < -2147483648n) throw new Error("Number too small"); + return varint(v); +} + +function varint64(n) { + let v = toNumber(n); + if (v > 0xFFFFFFFFFFFFFFFFn) throw new Error("Number too big"); + if (v > 0x7FFFFFFFFFFFFFFFn) v = v - 0x10000000000000000n; + // bigInt("-8000000000000000", 16) as base10 + if (v < -9223372036854775808n) throw new Error("Number too small"); + return varint(v); +} + +function varuint32(n) { + let v = toNumber(n); + if (v > 0xFFFFFFFFn) throw new Error("Number too big"); + return varuint(v); +} + +function toHexString(byteArray) { + return Array.from(byteArray, function(byte) { + return ("0" + (byte & 0xFF).toString(16)).slice(-2); + }).join(""); +} + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ -// EXTERNAL MODULE: ./node_modules/wasmbuilder/index.js -var wasmbuilder = __webpack_require__(14400); -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/bn128.js +class CodeBuilder { + constructor(func) { + this.func = func; + this.functionName = func.functionName; + this.module = func.module; + } + + setLocal(localName, valCode) { + const idx = this.func.localIdxByName[localName]; + if (idx === undefined) + throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); + return [...valCode, 0x21, ...varuint32( idx )]; + } + + teeLocal(localName, valCode) { + const idx = this.func.localIdxByName[localName]; + if (idx === undefined) + throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); + return [...valCode, 0x22, ...varuint32( idx )]; + } + + getLocal(localName) { + const idx = this.func.localIdxByName[localName]; + if (idx === undefined) + throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); + return [0x20, ...varuint32( idx )]; + } + + i64_load8_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 0 : _align; // 8 bits alignment by default + return [...idxCode, 0x30, align, ...varuint32(offset)]; + } + + i64_load8_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 0 : _align; // 8 bits alignment by default + return [...idxCode, 0x31, align, ...varuint32(offset)]; + } + + i64_load16_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 1 : _align; // 16 bits alignment by default + return [...idxCode, 0x32, align, ...varuint32(offset)]; + } + + i64_load16_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 1 : _align; // 16 bits alignment by default + return [...idxCode, 0x33, align, ...varuint32(offset)]; + } + + i64_load32_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default + return [...idxCode, 0x34, align, ...varuint32(offset)]; + } + + i64_load32_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default + return [...idxCode, 0x35, align, ...varuint32(offset)]; + } + + i64_load(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 3 : _align; // 64 bits alignment by default + return [...idxCode, 0x29, align, ...varuint32(offset)]; + } + i64_store(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 3; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 3; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x37, align, ...varuint32(offset)]; + } + + i64_store32(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 2; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 2; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3e, align, ...varuint32(offset)]; + } + i64_store16(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 1; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 1; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3d, align, ...varuint32(offset)]; + } + + + i64_store8(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 0; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 0; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3c, align, ...varuint32(offset)]; + } + + i32_load8_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default + return [...idxCode, 0x2c, align, ...varuint32(offset)]; + } + + i32_load8_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default + return [...idxCode, 0x2d, align, ...varuint32(offset)]; + } + + i32_load16_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default + return [...idxCode, 0x2e, align, ...varuint32(offset)]; + } + + i32_load16_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default + return [...idxCode, 0x2f, align, ...varuint32(offset)]; + } + + i32_load(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default + return [...idxCode, 0x28, align, ...varuint32(offset)]; + } + + i32_store(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 2; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 2; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x36, align, ...varuint32(offset)]; + } + + + i32_store16(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 1; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 1; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3b, align, ...varuint32(offset)]; + } + + i32_store8(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 0; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 0; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3a, align, ...varuint32(offset)]; + } + + call(fnName, ...args) { + const idx = this.module.functionIdxByName[fnName]; + if (idx === undefined) + throw new Error(`Function not defined: Function: ${fnName}`); + return [...[].concat(...args), 0x10, ...varuint32(idx)]; + } + + call_indirect(fnIdx, ...args) { + return [...[].concat(...args), ...fnIdx, 0x11, 0, 0]; + } + + if(condCode, thenCode, elseCode) { + if (elseCode) { + return [...condCode, 0x04, 0x40, ...thenCode, 0x05, ...elseCode, 0x0b]; + } else { + return [...condCode, 0x04, 0x40, ...thenCode, 0x0b]; + } + } + + block(bCode) { return [0x02, 0x40, ...bCode, 0x0b]; } + loop(...args) { + return [0x03, 0x40, ...[].concat(...[...args]), 0x0b]; + } + br_if(relPath, condCode) { return [...condCode, 0x0d, ...varuint32(relPath)]; } + br(relPath) { return [0x0c, ...varuint32(relPath)]; } + ret(rCode) { return [...rCode, 0x0f]; } + drop(dCode) { return [...dCode, 0x1a]; } + + i64_const(num) { return [0x42, ...varint64(num)]; } + i32_const(num) { return [0x41, ...varint32(num)]; } + + + i64_eqz(opcode) { return [...opcode, 0x50]; } + i64_eq(op1code, op2code) { return [...op1code, ...op2code, 0x51]; } + i64_ne(op1code, op2code) { return [...op1code, ...op2code, 0x52]; } + i64_lt_s(op1code, op2code) { return [...op1code, ...op2code, 0x53]; } + i64_lt_u(op1code, op2code) { return [...op1code, ...op2code, 0x54]; } + i64_gt_s(op1code, op2code) { return [...op1code, ...op2code, 0x55]; } + i64_gt_u(op1code, op2code) { return [...op1code, ...op2code, 0x56]; } + i64_le_s(op1code, op2code) { return [...op1code, ...op2code, 0x57]; } + i64_le_u(op1code, op2code) { return [...op1code, ...op2code, 0x58]; } + i64_ge_s(op1code, op2code) { return [...op1code, ...op2code, 0x59]; } + i64_ge_u(op1code, op2code) { return [...op1code, ...op2code, 0x5a]; } + i64_add(op1code, op2code) { return [...op1code, ...op2code, 0x7c]; } + i64_sub(op1code, op2code) { return [...op1code, ...op2code, 0x7d]; } + i64_mul(op1code, op2code) { return [...op1code, ...op2code, 0x7e]; } + i64_div_s(op1code, op2code) { return [...op1code, ...op2code, 0x7f]; } + i64_div_u(op1code, op2code) { return [...op1code, ...op2code, 0x80]; } + i64_rem_s(op1code, op2code) { return [...op1code, ...op2code, 0x81]; } + i64_rem_u(op1code, op2code) { return [...op1code, ...op2code, 0x82]; } + i64_and(op1code, op2code) { return [...op1code, ...op2code, 0x83]; } + i64_or(op1code, op2code) { return [...op1code, ...op2code, 0x84]; } + i64_xor(op1code, op2code) { return [...op1code, ...op2code, 0x85]; } + i64_shl(op1code, op2code) { return [...op1code, ...op2code, 0x86]; } + i64_shr_s(op1code, op2code) { return [...op1code, ...op2code, 0x87]; } + i64_shr_u(op1code, op2code) { return [...op1code, ...op2code, 0x88]; } + i64_extend_i32_s(op1code) { return [...op1code, 0xac]; } + i64_extend_i32_u(op1code) { return [...op1code, 0xad]; } + i64_clz(op1code) { return [...op1code, 0x79]; } + i64_ctz(op1code) { return [...op1code, 0x7a]; } + + i32_eqz(op1code) { return [...op1code, 0x45]; } + i32_eq(op1code, op2code) { return [...op1code, ...op2code, 0x46]; } + i32_ne(op1code, op2code) { return [...op1code, ...op2code, 0x47]; } + i32_lt_s(op1code, op2code) { return [...op1code, ...op2code, 0x48]; } + i32_lt_u(op1code, op2code) { return [...op1code, ...op2code, 0x49]; } + i32_gt_s(op1code, op2code) { return [...op1code, ...op2code, 0x4a]; } + i32_gt_u(op1code, op2code) { return [...op1code, ...op2code, 0x4b]; } + i32_le_s(op1code, op2code) { return [...op1code, ...op2code, 0x4c]; } + i32_le_u(op1code, op2code) { return [...op1code, ...op2code, 0x4d]; } + i32_ge_s(op1code, op2code) { return [...op1code, ...op2code, 0x4e]; } + i32_ge_u(op1code, op2code) { return [...op1code, ...op2code, 0x4f]; } + i32_add(op1code, op2code) { return [...op1code, ...op2code, 0x6a]; } + i32_sub(op1code, op2code) { return [...op1code, ...op2code, 0x6b]; } + i32_mul(op1code, op2code) { return [...op1code, ...op2code, 0x6c]; } + i32_div_s(op1code, op2code) { return [...op1code, ...op2code, 0x6d]; } + i32_div_u(op1code, op2code) { return [...op1code, ...op2code, 0x6e]; } + i32_rem_s(op1code, op2code) { return [...op1code, ...op2code, 0x6f]; } + i32_rem_u(op1code, op2code) { return [...op1code, ...op2code, 0x70]; } + i32_and(op1code, op2code) { return [...op1code, ...op2code, 0x71]; } + i32_or(op1code, op2code) { return [...op1code, ...op2code, 0x72]; } + i32_xor(op1code, op2code) { return [...op1code, ...op2code, 0x73]; } + i32_shl(op1code, op2code) { return [...op1code, ...op2code, 0x74]; } + i32_shr_s(op1code, op2code) { return [...op1code, ...op2code, 0x75]; } + i32_shr_u(op1code, op2code) { return [...op1code, ...op2code, 0x76]; } + i32_rotl(op1code, op2code) { return [...op1code, ...op2code, 0x77]; } + i32_rotr(op1code, op2code) { return [...op1code, ...op2code, 0x78]; } + i32_wrap_i64(op1code) { return [...op1code, 0xa7]; } + i32_clz(op1code) { return [...op1code, 0x67]; } + i32_ctz(op1code) { return [...op1code, 0x68]; } + + unreachable() { return [ 0x0 ]; } + + current_memory() { return [ 0x3f, 0]; } + + comment() { return []; } +} + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ + + +const typeCodes = { + "i32": 0x7f, + "i64": 0x7e, + "f32": 0x7d, + "f64": 0x7c, + "anyfunc": 0x70, + "func": 0x60, + "emptyblock": 0x40 +}; + + +class FunctionBuilder { + + constructor (module, fnName, fnType, moduleName, fieldName) { + if (fnType == "import") { + this.fnType = "import"; + this.moduleName = moduleName; + this.fieldName = fieldName; + } else if (fnType == "internal") { + this.fnType = "internal"; + } else { + throw new Error("Invalid function fnType: " + fnType); + } + this.module = module; + this.fnName = fnName; + this.params = []; + this.locals = []; + this.localIdxByName = {}; + this.code = []; + this.returnType = null; + this.nextLocal =0; + } + + addParam(paramName, paramType) { + if (this.localIdxByName[paramName]) + throw new Error(`param already exists. Function: ${this.fnName}, Param: ${paramName} `); + const idx = this.nextLocal++; + this.localIdxByName[paramName] = idx; + this.params.push({ + type: paramType + }); + } + + addLocal(localName, localType, _length) { + const length = _length || 1; + if (this.localIdxByName[localName]) + throw new Error(`local already exists. Function: ${this.fnName}, Param: ${localName} `); + const idx = this.nextLocal++; + this.localIdxByName[localName] = idx; + this.locals.push({ + type: localType, + length: length + }); + } + + setReturnType(returnType) { + if (this.returnType) + throw new Error(`returnType already defined. Function: ${this.fnName}`); + this.returnType = returnType; + } + + getSignature() { + const params = [...varuint32(this.params.length), ...this.params.map((p) => typeCodes[p.type])]; + const returns = this.returnType ? [0x01, typeCodes[this.returnType]] : [0]; + return [0x60, ...params, ...returns]; + } + + getBody() { + const locals = this.locals.map((l) => [ + ...varuint32(l.length), + typeCodes[l.type] + ]); + + const body = [ + ...varuint32(this.locals.length), + ...[].concat(...locals), + ...this.code, + 0x0b + ]; + return [ + ...varuint32(body.length), + ...body + ]; + } + + addCode(...code) { + this.code.push(...[].concat(...[...code])); + } + + getCodeBuilder() { + return new CodeBuilder(this); + } +} + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ + + +class ModuleBuilder { + + constructor() { + this.functions = []; + this.functionIdxByName = {}; + this.nImportFunctions = 0; + this.nInternalFunctions =0; + this.memory = { + pagesSize: 1, + moduleName: "env", + fieldName: "memory" + }; + this.free = 8; + this.datas = []; + this.modules = {}; + this.exports = []; + this.functionsTable = []; + } + + build() { + this._setSignatures(); + return new Uint8Array([ + ...u32(0x6d736100), + ...u32(1), + ...this._buildType(), + ...this._buildImport(), + ...this._buildFunctionDeclarations(), + ...this._buildFunctionsTable(), + ...this._buildExports(), + ...this._buildElements(), + ...this._buildCode(), + ...this._buildData() + ]); + } + + addFunction(fnName) { + if (typeof(this.functionIdxByName[fnName]) !== "undefined") + throw new Error(`Function already defined: ${fnName}`); + + const idx = this.functions.length; + this.functionIdxByName[fnName] = idx; + + this.functions.push(new FunctionBuilder(this, fnName, "internal")); + + this.nInternalFunctions++; + return this.functions[idx]; + } + + addIimportFunction(fnName, moduleName, _fieldName) { + if (typeof(this.functionIdxByName[fnName]) !== "undefined") + throw new Error(`Function already defined: ${fnName}`); + + if ( (this.functions.length>0) + &&(this.functions[this.functions.length-1].type == "internal")) + throw new Error(`Import functions must be declared before internal: ${fnName}`); + + let fieldName = _fieldName || fnName; + + const idx = this.functions.length; + this.functionIdxByName[fnName] = idx; + + this.functions.push(new FunctionBuilder(this, fnName, "import", moduleName, fieldName)); + + this.nImportFunctions ++; + return this.functions[idx]; + } + + setMemory(pagesSize, moduleName, fieldName) { + this.memory = { + pagesSize: pagesSize, + moduleName: moduleName || "env", + fieldName: fieldName || "memory" + }; + } + + exportFunction(fnName, _exportName) { + const exportName = _exportName || fnName; + if (typeof(this.functionIdxByName[fnName]) === "undefined") + throw new Error(`Function not defined: ${fnName}`); + const idx = this.functionIdxByName[fnName]; + if (exportName != fnName) { + this.functionIdxByName[exportName] = idx; + } + this.exports.push({ + exportName: exportName, + idx: idx + }); + } + + addFunctionToTable(fnName) { + const idx = this.functionIdxByName[fnName]; + this.functionsTable.push(idx); + } + + addData(offset, bytes) { + this.datas.push({ + offset: offset, + bytes: bytes + }); + } + + alloc(a, b) { + let size; + let bytes; + if ((Array.isArray(a) || ArrayBuffer.isView(a)) && (typeof(b) === "undefined")) { + size = a.length; + bytes = a; + } else { + size = a; + bytes = b; + } + size = (((size-1)>>3) +1)<<3; // Align to 64 bits. + const p = this.free; + this.free += size; + if (bytes) { + this.addData(p, bytes); + } + return p; + } + + allocString(s) { + const encoder = new globalThis.TextEncoder(); + const uint8array = encoder.encode(s); + return this.alloc([...uint8array, 0]); + } + + _setSignatures() { + this.signatures = []; + const signatureIdxByName = {}; + if (this.functionsTable.length>0) { + const signature = this.functions[this.functionsTable[0]].getSignature(); + const signatureName = "s_"+toHexString(signature); + signatureIdxByName[signatureName] = 0; + this.signatures.push(signature); + } + for (let i=0; i= 0) { - curve = await bn128_buildBn128(singleThread, plugins); + curve = await buildBn128(singleThread, plugins); } else if (["BLS12381"].indexOf(normName) >= 0) { - curve = await bls12381_buildBls12381(singleThread, plugins); + curve = await buildBls12381(singleThread, plugins); } else { throw new Error(`Curve not supported: ${name}`); } @@ -130487,29 +128685,8 @@ async function curves_getCurveFromName(name, singleThread, plugins) { } -;// CONCATENATED MODULE: ./node_modules/ffjavascript/main.js - - -const main_Scalar=scalar_namespaceObject; - - - - - - - - - - - - - - -const main_utils = utils_namespaceObject; - - - - +const browser_esm_Scalar=_Scalar; +const utils = _utils; @@ -130517,15 +128694,15 @@ const main_utils = utils_namespaceObject; async function babyjub_buildBabyJub() { - const bn128 = await curves_getCurveFromName("bn128", true); + const bn128 = await browser_esm_getCurveFromName("bn128", true); return new BabyJub(bn128.Fr); } class BabyJub { constructor(F) { this.F = F; - this.p = main_Scalar.fromString("21888242871839275222246405745257275088548364400416034343698204186575808495617"); - this.pm1d2 = main_Scalar.div(main_Scalar.sub(this.p, main_Scalar.e(1)), main_Scalar.e(2)); + this.p = browser_esm_Scalar.fromString("21888242871839275222246405745257275088548364400416034343698204186575808495617"); + this.pm1d2 = browser_esm_Scalar.div(browser_esm_Scalar.sub(this.p, browser_esm_Scalar.e(1)), browser_esm_Scalar.e(2)); this.Generator = [ F.e("995203441582195749578291179787384436505546430278305826713579947235728471134"), @@ -130535,8 +128712,8 @@ class BabyJub { F.e("5299619240641551281634865583518297030282874472190772894086521144482721001553"), F.e("16950150798460657717958625567821834550301663161624707787222815936182638968203") ]; - this.order = main_Scalar.fromString("21888242871839275222246405745257275088614511777268538073601725287587578984328"); - this.subOrder = main_Scalar.shiftRight(this.order, 3); + this.order = browser_esm_Scalar.fromString("21888242871839275222246405745257275088614511777268538073601725287587578984328"); + this.subOrder = browser_esm_Scalar.shiftRight(this.order, 3); this.A = F.e("168700"); this.D = F.e("168696"); } @@ -130580,12 +128757,12 @@ class BabyJub { let rem = e; let exp = base; - while (! main_Scalar.isZero(rem)) { - if (main_Scalar.isOdd(rem)) { + while (! browser_esm_Scalar.isZero(rem)) { + if (browser_esm_Scalar.isOdd(rem)) { res = this.addPoint(res, exp); } exp = this.addPoint(exp, exp); - rem = main_Scalar.shiftRight(rem, 1); + rem = browser_esm_Scalar.shiftRight(rem, 1); } return res; @@ -130615,7 +128792,7 @@ class BabyJub { const buff = new Uint8Array(32); F.toRprLE(buff, 0, P[1]); const n = F.toObject(P[0]); - if (main_Scalar.gt(n, this.pm1d2)) { + if (browser_esm_Scalar.gt(n, this.pm1d2)) { buff[31] = buff[31] | 0x80; } return buff; @@ -130630,7 +128807,7 @@ class BabyJub { buff[31] = buff[31] & 0x7F; } P[1] = F.fromRprLE(buff, 0); - if (main_Scalar.gt(F.toObject(P[1]), this.p)) return null; + if (browser_esm_Scalar.gt(F.toObject(P[1]), this.p)) return null; const y2 = F.square(P[1]); @@ -130659,7 +128836,7 @@ var blake2b = __webpack_require__(72206); // EXTERNAL MODULE: ./node_modules/blake-hash/js.js var js = __webpack_require__(60654); ;// CONCATENATED MODULE: ./node_modules/circomlibjs/src/pedersen_hash.js -/* provided dependency */ var pedersen_hash_Buffer = __webpack_require__(48287)["Buffer"]; +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; @@ -130685,7 +128862,7 @@ class PedersenHash { if (type == "blake") { return js("blake256").update(S).digest(); } else if (type == "blake2b") { - return pedersen_hash_Buffer.from(blake2b(32).update(pedersen_hash_Buffer.from(S)).digest()); + return Buffer.from(blake2b(32).update(Buffer.from(S)).digest()); } } @@ -130707,29 +128884,29 @@ class PedersenHash { } else { nWindows = nWindowsPerSegment; } - let escalar = main_Scalar.e(0); - let exp = main_Scalar.e(1); + let escalar = browser_esm_Scalar.e(0); + let exp = browser_esm_Scalar.e(1); for (let w=0; w= 0) { + return items.map((item, index) => { + if (item instanceof Result) { + return toObject(getNames(item), item, deep); + } + return item; + }); + } + return names.reduce((accum, name, index) => { + let item = items.getValue(name); + if (!(name in accum)) { + if (deep && item instanceof Result) { + item = toObject(getNames(item), item, deep); + } + accum[name] = item; + } + return accum; + }, {}); +} /** * A [[Result]] is a sub-class of Array, which allows accessing any * of its values either positionally by its index or, if keys are @@ -159736,6 +157939,9 @@ function throwError(name, error) { * @_docloc: api/abi */ class Result extends Array { + // No longer used; but cannot be removed as it will remove the + // #private field from the .d.ts which may break backwards + // compatibility #names; /** * @private @@ -159768,20 +157974,25 @@ class Result extends Array { return accum; }, (new Map())); // Remove any key thats not unique - this.#names = Object.freeze(items.map((item, index) => { + setNames(this, Object.freeze(items.map((item, index) => { const name = names[index]; if (name != null && nameCounts.get(name) === 1) { return name; } return null; - })); + }))); + // Dummy operations to prevent TypeScript from complaining + this.#names = []; + if (this.#names == null) { + void (this.#names); + } if (!wrap) { return; } // A wrapped Result is immutable Object.freeze(this); // Proxy indices and names so we can trap deferred errors - return new Proxy(this, { + const proxy = new Proxy(this, { get: (target, prop, receiver) => { if (typeof (prop) === "string") { // Index accessor @@ -159816,6 +158027,8 @@ class Result extends Array { return Reflect.get(target, prop, receiver); } }); + setNames(proxy, getNames(this)); + return proxy; } /** * Returns the Result as a normal Array. If %%deep%%, any children @@ -159846,19 +158059,12 @@ class Result extends Array { * any outstanding deferred errors. */ toObject(deep) { - return this.#names.reduce((accum, name, index) => { - (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assert */ .vA)(name != null, "value at index ${ index } unnamed", "UNSUPPORTED_OPERATION", { + const names = getNames(this); + return names.reduce((accum, name, index) => { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assert */ .vA)(name != null, `value at index ${index} unnamed`, "UNSUPPORTED_OPERATION", { operation: "toObject()" }); - // Add values for names that don't conflict - if (!(name in accum)) { - let child = this.getValue(name); - if (deep && child instanceof Result) { - child = child.toObject(deep); - } - accum[name] = child; - } - return accum; + return toObject(names, this, deep); }, {}); } /** @@ -159886,10 +158092,11 @@ class Result extends Array { if (end > this.length) { end = this.length; } + const _names = getNames(this); const result = [], names = []; for (let i = start; i < end; i++) { result.push(this[i]); - names.push(this.#names[i]); + names.push(_names[i]); } return new Result(_guard, result, names); } @@ -159897,6 +158104,7 @@ class Result extends Array { * @_ignore */ filter(callback, thisArg) { + const _names = getNames(this); const result = [], names = []; for (let i = 0; i < this.length; i++) { const item = this[i]; @@ -159905,7 +158113,7 @@ class Result extends Array { } if (callback.call(thisArg, item, i, this)) { result.push(item); - names.push(this.#names[i]); + names.push(_names[i]); } } return new Result(_guard, result, names); @@ -159933,7 +158141,7 @@ class Result extends Array { * accessible by name. */ getValue(name) { - const index = this.#names.indexOf(name); + const index = getNames(this).indexOf(name); if (index === -1) { return undefined; } @@ -160755,7 +158963,7 @@ class ParamType { * Walks the **ParamType** with %%value%%, asynchronously calling * %%process%% on each type, destructing the %%value%% recursively. * - * This can be used to resolve ENS naes by walking and resolving each + * This can be used to resolve ENS names by walking and resolving each * ``"address"`` type. */ async walkAsync(value, process) { @@ -161505,7 +159713,6 @@ class StructFragment extends NamedFragment { /* harmony import */ var _coders_abstract_coder_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(21228); /* harmony import */ var _fragments_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(76124); /* harmony import */ var _typed_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(19353); -/* provided dependency */ var console = __webpack_require__(96763); /** * The Interface class is a low-level class that accepts an * ABI and provides all the necessary functionality to encode @@ -162594,7 +160801,11 @@ getSelector(fragment: ErrorFragment | FunctionFragment): string { if (typeof (value) === "string") { return new Interface(JSON.parse(value)); } - // Maybe an interface from an older version, or from a symlinked copy + // An Interface; possibly from another v6 instance + if (typeof (value.formatJson) === "function") { + return new Interface(value.formatJson()); + } + // A legacy Interface; from an older version if (typeof (value.format) === "function") { return new Interface(value.format("json")); } @@ -165719,12 +163930,12 @@ __webpack_require__.r(utils_namespaceObject); __webpack_require__.d(utils_namespaceObject, { OG: () => (bitMask), My: () => (bytesToHex), - bytesToNumberBE: () => (utils_bytesToNumberBE), + Ph: () => (utils_bytesToNumberBE), lX: () => (utils_bytesToNumberLE), Id: () => (utils_concatBytes), fg: () => (createHmacDrbg), qj: () => (utils_ensureBytes), - hexToBytes: () => (hexToBytes), + aT: () => (hexToBytes), lq: () => (utils_numberToBytesBE), z: () => (numberToBytesLE), Q5: () => (validateObject) @@ -166612,7 +164823,7 @@ function validatePointOpts(curve) { return Object.freeze({ ...opts }); } // ASN.1 DER encoding utilities -const { bytesToNumberBE: b2n, hexToBytes: h2b } = utils_namespaceObject; +const { /* bytesToNumberBE */ "Ph": b2n, /* hexToBytes */ "aT": h2b } = utils_namespaceObject; const DER = { // asn.1 DER encoding utils Err: class DERErr extends Error { @@ -172009,7 +170220,7 @@ function _getBytes(value, name, copy) { } return value; } - if (typeof (value) === "string" && value.match(/^0x([0-9a-f][0-9a-f])*$/i)) { + if (typeof (value) === "string" && value.match(/^0x(?:[0-9a-f][0-9a-f])*$/i)) { const result = new Uint8Array((value.length - 2) / 2); let offset = 2; for (let i = 0; i < result.length; i++) { @@ -174461,1072 +172672,6 @@ function randomBytes(bytesLength = 32) { } //# sourceMappingURL=utils.js.map -/***/ }), - -/***/ 2150: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Struct: () => (/* binding */ Struct), -/* harmony export */ StructError: () => (/* binding */ StructError), -/* harmony export */ any: () => (/* binding */ any), -/* harmony export */ array: () => (/* binding */ array), -/* harmony export */ assert: () => (/* binding */ assert), -/* harmony export */ assign: () => (/* binding */ assign), -/* harmony export */ bigint: () => (/* binding */ bigint), -/* harmony export */ boolean: () => (/* binding */ boolean), -/* harmony export */ coerce: () => (/* binding */ coerce), -/* harmony export */ create: () => (/* binding */ create), -/* harmony export */ date: () => (/* binding */ date), -/* harmony export */ defaulted: () => (/* binding */ defaulted), -/* harmony export */ define: () => (/* binding */ define), -/* harmony export */ deprecated: () => (/* binding */ deprecated), -/* harmony export */ dynamic: () => (/* binding */ dynamic), -/* harmony export */ empty: () => (/* binding */ empty), -/* harmony export */ enums: () => (/* binding */ enums), -/* harmony export */ func: () => (/* binding */ func), -/* harmony export */ instance: () => (/* binding */ instance), -/* harmony export */ integer: () => (/* binding */ integer), -/* harmony export */ intersection: () => (/* binding */ intersection), -/* harmony export */ is: () => (/* binding */ is), -/* harmony export */ lazy: () => (/* binding */ lazy), -/* harmony export */ literal: () => (/* binding */ literal), -/* harmony export */ map: () => (/* binding */ map), -/* harmony export */ mask: () => (/* binding */ mask), -/* harmony export */ max: () => (/* binding */ max), -/* harmony export */ min: () => (/* binding */ min), -/* harmony export */ never: () => (/* binding */ never), -/* harmony export */ nonempty: () => (/* binding */ nonempty), -/* harmony export */ nullable: () => (/* binding */ nullable), -/* harmony export */ number: () => (/* binding */ number), -/* harmony export */ object: () => (/* binding */ object), -/* harmony export */ omit: () => (/* binding */ omit), -/* harmony export */ optional: () => (/* binding */ optional), -/* harmony export */ partial: () => (/* binding */ partial), -/* harmony export */ pattern: () => (/* binding */ pattern), -/* harmony export */ pick: () => (/* binding */ pick), -/* harmony export */ record: () => (/* binding */ record), -/* harmony export */ refine: () => (/* binding */ refine), -/* harmony export */ regexp: () => (/* binding */ regexp), -/* harmony export */ set: () => (/* binding */ set), -/* harmony export */ size: () => (/* binding */ size), -/* harmony export */ string: () => (/* binding */ string), -/* harmony export */ struct: () => (/* binding */ struct), -/* harmony export */ trimmed: () => (/* binding */ trimmed), -/* harmony export */ tuple: () => (/* binding */ tuple), -/* harmony export */ type: () => (/* binding */ type), -/* harmony export */ union: () => (/* binding */ union), -/* harmony export */ unknown: () => (/* binding */ unknown), -/* harmony export */ validate: () => (/* binding */ validate) -/* harmony export */ }); -/* provided dependency */ var console = __webpack_require__(96763); -/** - * A `StructFailure` represents a single specific failure in validation. - */ -/** - * `StructError` objects are thrown (or returned) when validation fails. - * - * Validation logic is design to exit early for maximum performance. The error - * represents the first error encountered during validation. For more detail, - * the `error.failures` property is a generator function that can be run to - * continue validation and receive all the failures in the data. - */ -class StructError extends TypeError { - constructor(failure, failures) { - let cached; - const { message, explanation, ...rest } = failure; - const { path } = failure; - const msg = path.length === 0 ? message : `At path: ${path.join('.')} -- ${message}`; - super(explanation ?? msg); - if (explanation != null) - this.cause = msg; - Object.assign(this, rest); - this.name = this.constructor.name; - this.failures = () => { - return (cached ?? (cached = [failure, ...failures()])); - }; - } -} - -/** - * Check if a value is an iterator. - */ -function isIterable(x) { - return isObject(x) && typeof x[Symbol.iterator] === 'function'; -} -/** - * Check if a value is a plain object. - */ -function isObject(x) { - return typeof x === 'object' && x != null; -} -/** - * Check if a value is a plain object. - */ -function isPlainObject(x) { - if (Object.prototype.toString.call(x) !== '[object Object]') { - return false; - } - const prototype = Object.getPrototypeOf(x); - return prototype === null || prototype === Object.prototype; -} -/** - * Return a value as a printable string. - */ -function print(value) { - if (typeof value === 'symbol') { - return value.toString(); - } - return typeof value === 'string' ? JSON.stringify(value) : `${value}`; -} -/** - * Shifts (removes and returns) the first value from the `input` iterator. - * Like `Array.prototype.shift()` but for an `Iterator`. - */ -function shiftIterator(input) { - const { done, value } = input.next(); - return done ? undefined : value; -} -/** - * Convert a single validation result to a failure. - */ -function toFailure(result, context, struct, value) { - if (result === true) { - return; - } - else if (result === false) { - result = {}; - } - else if (typeof result === 'string') { - result = { message: result }; - } - const { path, branch } = context; - const { type } = struct; - const { refinement, message = `Expected a value of type \`${type}\`${refinement ? ` with refinement \`${refinement}\`` : ''}, but received: \`${print(value)}\``, } = result; - return { - value, - type, - refinement, - key: path[path.length - 1], - path, - branch, - ...result, - message, - }; -} -/** - * Convert a validation result to an iterable of failures. - */ -function* toFailures(result, context, struct, value) { - if (!isIterable(result)) { - result = [result]; - } - for (const r of result) { - const failure = toFailure(r, context, struct, value); - if (failure) { - yield failure; - } - } -} -/** - * Check a value against a struct, traversing deeply into nested values, and - * returning an iterator of failures or success. - */ -function* run(value, struct, options = {}) { - const { path = [], branch = [value], coerce = false, mask = false } = options; - const ctx = { path, branch }; - if (coerce) { - value = struct.coercer(value, ctx); - if (mask && - struct.type !== 'type' && - isObject(struct.schema) && - isObject(value) && - !Array.isArray(value)) { - for (const key in value) { - if (struct.schema[key] === undefined) { - delete value[key]; - } - } - } - } - let status = 'valid'; - for (const failure of struct.validator(value, ctx)) { - failure.explanation = options.message; - status = 'not_valid'; - yield [failure, undefined]; - } - for (let [k, v, s] of struct.entries(value, ctx)) { - const ts = run(v, s, { - path: k === undefined ? path : [...path, k], - branch: k === undefined ? branch : [...branch, v], - coerce, - mask, - message: options.message, - }); - for (const t of ts) { - if (t[0]) { - status = t[0].refinement != null ? 'not_refined' : 'not_valid'; - yield [t[0], undefined]; - } - else if (coerce) { - v = t[1]; - if (k === undefined) { - value = v; - } - else if (value instanceof Map) { - value.set(k, v); - } - else if (value instanceof Set) { - value.add(v); - } - else if (isObject(value)) { - if (v !== undefined || k in value) - value[k] = v; - } - } - } - } - if (status !== 'not_valid') { - for (const failure of struct.refiner(value, ctx)) { - failure.explanation = options.message; - status = 'not_refined'; - yield [failure, undefined]; - } - } - if (status === 'valid') { - yield [undefined, value]; - } -} - -/** - * `Struct` objects encapsulate the validation logic for a specific type of - * values. Once constructed, you use the `assert`, `is` or `validate` helpers to - * validate unknown input data against the struct. - */ -class Struct { - constructor(props) { - const { type, schema, validator, refiner, coercer = (value) => value, entries = function* () { }, } = props; - this.type = type; - this.schema = schema; - this.entries = entries; - this.coercer = coercer; - if (validator) { - this.validator = (value, context) => { - const result = validator(value, context); - return toFailures(result, context, this, value); - }; - } - else { - this.validator = () => []; - } - if (refiner) { - this.refiner = (value, context) => { - const result = refiner(value, context); - return toFailures(result, context, this, value); - }; - } - else { - this.refiner = () => []; - } - } - /** - * Assert that a value passes the struct's validation, throwing if it doesn't. - */ - assert(value, message) { - return assert(value, this, message); - } - /** - * Create a value with the struct's coercion logic, then validate it. - */ - create(value, message) { - return create(value, this, message); - } - /** - * Check if a value passes the struct's validation. - */ - is(value) { - return is(value, this); - } - /** - * Mask a value, coercing and validating it, but returning only the subset of - * properties defined by the struct's schema. - */ - mask(value, message) { - return mask(value, this, message); - } - /** - * Validate a value with the struct's validation logic, returning a tuple - * representing the result. - * - * You may optionally pass `true` for the `withCoercion` argument to coerce - * the value before attempting to validate it. If you do, the result will - * contain the coerced result when successful. - */ - validate(value, options = {}) { - return validate(value, this, options); - } -} -/** - * Assert that a value passes a struct, throwing if it doesn't. - */ -function assert(value, struct, message) { - const result = validate(value, struct, { message }); - if (result[0]) { - throw result[0]; - } -} -/** - * Create a value with the coercion logic of struct and validate it. - */ -function create(value, struct, message) { - const result = validate(value, struct, { coerce: true, message }); - if (result[0]) { - throw result[0]; - } - else { - return result[1]; - } -} -/** - * Mask a value, returning only the subset of properties defined by a struct. - */ -function mask(value, struct, message) { - const result = validate(value, struct, { coerce: true, mask: true, message }); - if (result[0]) { - throw result[0]; - } - else { - return result[1]; - } -} -/** - * Check if a value passes a struct. - */ -function is(value, struct) { - const result = validate(value, struct); - return !result[0]; -} -/** - * Validate a value against a struct, returning an error if invalid, or the - * value (with potential coercion) if valid. - */ -function validate(value, struct, options = {}) { - const tuples = run(value, struct, options); - const tuple = shiftIterator(tuples); - if (tuple[0]) { - const error = new StructError(tuple[0], function* () { - for (const t of tuples) { - if (t[0]) { - yield t[0]; - } - } - }); - return [error, undefined]; - } - else { - const v = tuple[1]; - return [undefined, v]; - } -} - -function assign(...Structs) { - const isType = Structs[0].type === 'type'; - const schemas = Structs.map((s) => s.schema); - const schema = Object.assign({}, ...schemas); - return isType ? type(schema) : object(schema); -} -/** - * Define a new struct type with a custom validation function. - */ -function define(name, validator) { - return new Struct({ type: name, schema: null, validator }); -} -/** - * Create a new struct based on an existing struct, but the value is allowed to - * be `undefined`. `log` will be called if the value is not `undefined`. - */ -function deprecated(struct, log) { - return new Struct({ - ...struct, - refiner: (value, ctx) => value === undefined || struct.refiner(value, ctx), - validator(value, ctx) { - if (value === undefined) { - return true; - } - else { - log(value, ctx); - return struct.validator(value, ctx); - } - }, - }); -} -/** - * Create a struct with dynamic validation logic. - * - * The callback will receive the value currently being validated, and must - * return a struct object to validate it with. This can be useful to model - * validation logic that changes based on its input. - */ -function dynamic(fn) { - return new Struct({ - type: 'dynamic', - schema: null, - *entries(value, ctx) { - const struct = fn(value, ctx); - yield* struct.entries(value, ctx); - }, - validator(value, ctx) { - const struct = fn(value, ctx); - return struct.validator(value, ctx); - }, - coercer(value, ctx) { - const struct = fn(value, ctx); - return struct.coercer(value, ctx); - }, - refiner(value, ctx) { - const struct = fn(value, ctx); - return struct.refiner(value, ctx); - }, - }); -} -/** - * Create a struct with lazily evaluated validation logic. - * - * The first time validation is run with the struct, the callback will be called - * and must return a struct object to use. This is useful for cases where you - * want to have self-referential structs for nested data structures to avoid a - * circular definition problem. - */ -function lazy(fn) { - let struct; - return new Struct({ - type: 'lazy', - schema: null, - *entries(value, ctx) { - struct ?? (struct = fn()); - yield* struct.entries(value, ctx); - }, - validator(value, ctx) { - struct ?? (struct = fn()); - return struct.validator(value, ctx); - }, - coercer(value, ctx) { - struct ?? (struct = fn()); - return struct.coercer(value, ctx); - }, - refiner(value, ctx) { - struct ?? (struct = fn()); - return struct.refiner(value, ctx); - }, - }); -} -/** - * Create a new struct based on an existing object struct, but excluding - * specific properties. - * - * Like TypeScript's `Omit` utility. - */ -function omit(struct, keys) { - const { schema } = struct; - const subschema = { ...schema }; - for (const key of keys) { - delete subschema[key]; - } - switch (struct.type) { - case 'type': - return type(subschema); - default: - return object(subschema); - } -} -/** - * Create a new struct based on an existing object struct, but with all of its - * properties allowed to be `undefined`. - * - * Like TypeScript's `Partial` utility. - */ -function partial(struct) { - const isStruct = struct instanceof Struct; - const schema = isStruct ? { ...struct.schema } : { ...struct }; - for (const key in schema) { - schema[key] = optional(schema[key]); - } - if (isStruct && struct.type === 'type') { - return type(schema); - } - return object(schema); -} -/** - * Create a new struct based on an existing object struct, but only including - * specific properties. - * - * Like TypeScript's `Pick` utility. - */ -function pick(struct, keys) { - const { schema } = struct; - const subschema = {}; - for (const key of keys) { - subschema[key] = schema[key]; - } - switch (struct.type) { - case 'type': - return type(subschema); - default: - return object(subschema); - } -} -/** - * Define a new struct type with a custom validation function. - * - * @deprecated This function has been renamed to `define`. - */ -function struct(name, validator) { - console.warn('superstruct@0.11 - The `struct` helper has been renamed to `define`.'); - return define(name, validator); -} - -/** - * Ensure that any value passes validation. - */ -function any() { - return define('any', () => true); -} -function array(Element) { - return new Struct({ - type: 'array', - schema: Element, - *entries(value) { - if (Element && Array.isArray(value)) { - for (const [i, v] of value.entries()) { - yield [i, v, Element]; - } - } - }, - coercer(value) { - return Array.isArray(value) ? value.slice() : value; - }, - validator(value) { - return (Array.isArray(value) || - `Expected an array value, but received: ${print(value)}`); - }, - }); -} -/** - * Ensure that a value is a bigint. - */ -function bigint() { - return define('bigint', (value) => { - return typeof value === 'bigint'; - }); -} -/** - * Ensure that a value is a boolean. - */ -function boolean() { - return define('boolean', (value) => { - return typeof value === 'boolean'; - }); -} -/** - * Ensure that a value is a valid `Date`. - * - * Note: this also ensures that the value is *not* an invalid `Date` object, - * which can occur when parsing a date fails but still returns a `Date`. - */ -function date() { - return define('date', (value) => { - return ((value instanceof Date && !isNaN(value.getTime())) || - `Expected a valid \`Date\` object, but received: ${print(value)}`); - }); -} -function enums(values) { - const schema = {}; - const description = values.map((v) => print(v)).join(); - for (const key of values) { - schema[key] = key; - } - return new Struct({ - type: 'enums', - schema, - validator(value) { - return (values.includes(value) || - `Expected one of \`${description}\`, but received: ${print(value)}`); - }, - }); -} -/** - * Ensure that a value is a function. - */ -function func() { - return define('func', (value) => { - return (typeof value === 'function' || - `Expected a function, but received: ${print(value)}`); - }); -} -/** - * Ensure that a value is an instance of a specific class. - */ -function instance(Class) { - return define('instance', (value) => { - return (value instanceof Class || - `Expected a \`${Class.name}\` instance, but received: ${print(value)}`); - }); -} -/** - * Ensure that a value is an integer. - */ -function integer() { - return define('integer', (value) => { - return ((typeof value === 'number' && !isNaN(value) && Number.isInteger(value)) || - `Expected an integer, but received: ${print(value)}`); - }); -} -/** - * Ensure that a value matches all of a set of types. - */ -function intersection(Structs) { - return new Struct({ - type: 'intersection', - schema: null, - *entries(value, ctx) { - for (const S of Structs) { - yield* S.entries(value, ctx); - } - }, - *validator(value, ctx) { - for (const S of Structs) { - yield* S.validator(value, ctx); - } - }, - *refiner(value, ctx) { - for (const S of Structs) { - yield* S.refiner(value, ctx); - } - }, - }); -} -function literal(constant) { - const description = print(constant); - const t = typeof constant; - return new Struct({ - type: 'literal', - schema: t === 'string' || t === 'number' || t === 'boolean' ? constant : null, - validator(value) { - return (value === constant || - `Expected the literal \`${description}\`, but received: ${print(value)}`); - }, - }); -} -function map(Key, Value) { - return new Struct({ - type: 'map', - schema: null, - *entries(value) { - if (Key && Value && value instanceof Map) { - for (const [k, v] of value.entries()) { - yield [k, k, Key]; - yield [k, v, Value]; - } - } - }, - coercer(value) { - return value instanceof Map ? new Map(value) : value; - }, - validator(value) { - return (value instanceof Map || - `Expected a \`Map\` object, but received: ${print(value)}`); - }, - }); -} -/** - * Ensure that no value ever passes validation. - */ -function never() { - return define('never', () => false); -} -/** - * Augment an existing struct to allow `null` values. - */ -function nullable(struct) { - return new Struct({ - ...struct, - validator: (value, ctx) => value === null || struct.validator(value, ctx), - refiner: (value, ctx) => value === null || struct.refiner(value, ctx), - }); -} -/** - * Ensure that a value is a number. - */ -function number() { - return define('number', (value) => { - return ((typeof value === 'number' && !isNaN(value)) || - `Expected a number, but received: ${print(value)}`); - }); -} -function object(schema) { - const knowns = schema ? Object.keys(schema) : []; - const Never = never(); - return new Struct({ - type: 'object', - schema: schema ? schema : null, - *entries(value) { - if (schema && isObject(value)) { - const unknowns = new Set(Object.keys(value)); - for (const key of knowns) { - unknowns.delete(key); - yield [key, value[key], schema[key]]; - } - for (const key of unknowns) { - yield [key, value[key], Never]; - } - } - }, - validator(value) { - return (isObject(value) || `Expected an object, but received: ${print(value)}`); - }, - coercer(value) { - return isObject(value) ? { ...value } : value; - }, - }); -} -/** - * Augment a struct to allow `undefined` values. - */ -function optional(struct) { - return new Struct({ - ...struct, - validator: (value, ctx) => value === undefined || struct.validator(value, ctx), - refiner: (value, ctx) => value === undefined || struct.refiner(value, ctx), - }); -} -/** - * Ensure that a value is an object with keys and values of specific types, but - * without ensuring any specific shape of properties. - * - * Like TypeScript's `Record` utility. - */ -function record(Key, Value) { - return new Struct({ - type: 'record', - schema: null, - *entries(value) { - if (isObject(value)) { - for (const k in value) { - const v = value[k]; - yield [k, k, Key]; - yield [k, v, Value]; - } - } - }, - validator(value) { - return (isObject(value) || `Expected an object, but received: ${print(value)}`); - }, - }); -} -/** - * Ensure that a value is a `RegExp`. - * - * Note: this does not test the value against the regular expression! For that - * you need to use the `pattern()` refinement. - */ -function regexp() { - return define('regexp', (value) => { - return value instanceof RegExp; - }); -} -function set(Element) { - return new Struct({ - type: 'set', - schema: null, - *entries(value) { - if (Element && value instanceof Set) { - for (const v of value) { - yield [v, v, Element]; - } - } - }, - coercer(value) { - return value instanceof Set ? new Set(value) : value; - }, - validator(value) { - return (value instanceof Set || - `Expected a \`Set\` object, but received: ${print(value)}`); - }, - }); -} -/** - * Ensure that a value is a string. - */ -function string() { - return define('string', (value) => { - return (typeof value === 'string' || - `Expected a string, but received: ${print(value)}`); - }); -} -/** - * Ensure that a value is a tuple of a specific length, and that each of its - * elements is of a specific type. - */ -function tuple(Structs) { - const Never = never(); - return new Struct({ - type: 'tuple', - schema: null, - *entries(value) { - if (Array.isArray(value)) { - const length = Math.max(Structs.length, value.length); - for (let i = 0; i < length; i++) { - yield [i, value[i], Structs[i] || Never]; - } - } - }, - validator(value) { - return (Array.isArray(value) || - `Expected an array, but received: ${print(value)}`); - }, - }); -} -/** - * Ensure that a value has a set of known properties of specific types. - * - * Note: Unrecognized properties are allowed and untouched. This is similar to - * how TypeScript's structural typing works. - */ -function type(schema) { - const keys = Object.keys(schema); - return new Struct({ - type: 'type', - schema, - *entries(value) { - if (isObject(value)) { - for (const k of keys) { - yield [k, value[k], schema[k]]; - } - } - }, - validator(value) { - return (isObject(value) || `Expected an object, but received: ${print(value)}`); - }, - coercer(value) { - return isObject(value) ? { ...value } : value; - }, - }); -} -/** - * Ensure that a value matches one of a set of types. - */ -function union(Structs) { - const description = Structs.map((s) => s.type).join(' | '); - return new Struct({ - type: 'union', - schema: null, - coercer(value) { - for (const S of Structs) { - const [error, coerced] = S.validate(value, { coerce: true }); - if (!error) { - return coerced; - } - } - return value; - }, - validator(value, ctx) { - const failures = []; - for (const S of Structs) { - const [...tuples] = run(value, S, ctx); - const [first] = tuples; - if (!first[0]) { - return []; - } - else { - for (const [failure] of tuples) { - if (failure) { - failures.push(failure); - } - } - } - } - return [ - `Expected the value to satisfy a union of \`${description}\`, but received: ${print(value)}`, - ...failures, - ]; - }, - }); -} -/** - * Ensure that any value passes validation, without widening its type to `any`. - */ -function unknown() { - return define('unknown', () => true); -} - -/** - * Augment a `Struct` to add an additional coercion step to its input. - * - * This allows you to transform input data before validating it, to increase the - * likelihood that it passes validation—for example for default values, parsing - * different formats, etc. - * - * Note: You must use `create(value, Struct)` on the value to have the coercion - * take effect! Using simply `assert()` or `is()` will not use coercion. - */ -function coerce(struct, condition, coercer) { - return new Struct({ - ...struct, - coercer: (value, ctx) => { - return is(value, condition) - ? struct.coercer(coercer(value, ctx), ctx) - : struct.coercer(value, ctx); - }, - }); -} -/** - * Augment a struct to replace `undefined` values with a default. - * - * Note: You must use `create(value, Struct)` on the value to have the coercion - * take effect! Using simply `assert()` or `is()` will not use coercion. - */ -function defaulted(struct, fallback, options = {}) { - return coerce(struct, unknown(), (x) => { - const f = typeof fallback === 'function' ? fallback() : fallback; - if (x === undefined) { - return f; - } - if (!options.strict && isPlainObject(x) && isPlainObject(f)) { - const ret = { ...x }; - let changed = false; - for (const key in f) { - if (ret[key] === undefined) { - ret[key] = f[key]; - changed = true; - } - } - if (changed) { - return ret; - } - } - return x; - }); -} -/** - * Augment a struct to trim string inputs. - * - * Note: You must use `create(value, Struct)` on the value to have the coercion - * take effect! Using simply `assert()` or `is()` will not use coercion. - */ -function trimmed(struct) { - return coerce(struct, string(), (x) => x.trim()); -} - -/** - * Ensure that a string, array, map, or set is empty. - */ -function empty(struct) { - return refine(struct, 'empty', (value) => { - const size = getSize(value); - return (size === 0 || - `Expected an empty ${struct.type} but received one with a size of \`${size}\``); - }); -} -function getSize(value) { - if (value instanceof Map || value instanceof Set) { - return value.size; - } - else { - return value.length; - } -} -/** - * Ensure that a number or date is below a threshold. - */ -function max(struct, threshold, options = {}) { - const { exclusive } = options; - return refine(struct, 'max', (value) => { - return exclusive - ? value < threshold - : value <= threshold || - `Expected a ${struct.type} less than ${exclusive ? '' : 'or equal to '}${threshold} but received \`${value}\``; - }); -} -/** - * Ensure that a number or date is above a threshold. - */ -function min(struct, threshold, options = {}) { - const { exclusive } = options; - return refine(struct, 'min', (value) => { - return exclusive - ? value > threshold - : value >= threshold || - `Expected a ${struct.type} greater than ${exclusive ? '' : 'or equal to '}${threshold} but received \`${value}\``; - }); -} -/** - * Ensure that a string, array, map or set is not empty. - */ -function nonempty(struct) { - return refine(struct, 'nonempty', (value) => { - const size = getSize(value); - return (size > 0 || `Expected a nonempty ${struct.type} but received an empty one`); - }); -} -/** - * Ensure that a string matches a regular expression. - */ -function pattern(struct, regexp) { - return refine(struct, 'pattern', (value) => { - return (regexp.test(value) || - `Expected a ${struct.type} matching \`/${regexp.source}/\` but received "${value}"`); - }); -} -/** - * Ensure that a string, array, number, date, map, or set has a size (or length, or time) between `min` and `max`. - */ -function size(struct, min, max = min) { - const expected = `Expected a ${struct.type}`; - const of = min === max ? `of \`${min}\`` : `between \`${min}\` and \`${max}\``; - return refine(struct, 'size', (value) => { - if (typeof value === 'number' || value instanceof Date) { - return ((min <= value && value <= max) || - `${expected} ${of} but received \`${value}\``); - } - else if (value instanceof Map || value instanceof Set) { - const { size } = value; - return ((min <= size && size <= max) || - `${expected} with a size ${of} but received one with a size of \`${size}\``); - } - else { - const { length } = value; - return ((min <= length && length <= max) || - `${expected} with a length ${of} but received one with a length of \`${length}\``); - } - }); -} -/** - * Augment a `Struct` to add an additional refinement to the validation. - * - * The refiner function is guaranteed to receive a value of the struct's type, - * because the struct's existing validation will already have passed. This - * allows you to layer additional validation on top of existing structs. - */ -function refine(struct, name, refiner) { - return new Struct({ - ...struct, - *refiner(value, ctx) { - yield* struct.refiner(value, ctx); - const result = refiner(value, ctx); - const failures = toFailures(result, ctx, struct, value); - for (const failure of failures) { - yield { ...failure, refinement: name }; - } - }, - }); -} - - -//# sourceMappingURL=index.mjs.map - - /***/ }), /***/ 63837: @@ -175581,7 +172726,7 @@ module.exports = /*#__PURE__*/JSON.parse('{"modp1":{"gen":"02","prime":"ffffffff /***/ ((module) => { "use strict"; -module.exports = {"rE":"6.5.5"}; +module.exports = {"rE":"6.5.7"}; /***/ }), @@ -175711,7 +172856,6 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ GET_REGISTERED: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.GET_REGISTERED), /* harmony export */ GET_STATISTIC: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.GET_STATISTIC), /* harmony export */ GET_WITHDRAWALS: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.GET_WITHDRAWALS), -/* harmony export */ GasPriceOracle__factory: () => (/* reexport safe */ _typechain__WEBPACK_IMPORTED_MODULE_3__.Hu), /* harmony export */ Invoice: () => (/* reexport safe */ _deposits__WEBPACK_IMPORTED_MODULE_5__.qO), /* harmony export */ MIN_STAKE_BALANCE: () => (/* reexport safe */ _relayerClient__WEBPACK_IMPORTED_MODULE_15__.pO), /* harmony export */ MerkleTreeService: () => (/* reexport safe */ _merkleTree__WEBPACK_IMPORTED_MODULE_8__.s), @@ -175765,7 +172909,6 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ getConfig: () => (/* reexport safe */ _networkConfig__WEBPACK_IMPORTED_MODULE_11__.zj), /* harmony export */ getDeposits: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.getDeposits), /* harmony export */ getEncryptedNotes: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.getEncryptedNotes), -/* harmony export */ getGasOraclePlugin: () => (/* reexport safe */ _providers__WEBPACK_IMPORTED_MODULE_14__.bD), /* harmony export */ getGovernanceEvents: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.getGovernanceEvents), /* harmony export */ getGraphEchoEvents: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.getGraphEchoEvents), /* harmony export */ getHttpAgent: () => (/* reexport safe */ _providers__WEBPACK_IMPORTED_MODULE_14__.WU), @@ -175812,7 +172955,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony reexport (unknown) */ __webpack_require__.d(__webpack_exports__, __WEBPACK_REEXPORT_OBJECT__); /* harmony import */ var _graphql__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(52049); /* harmony import */ var _schemas__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7613); -/* harmony import */ var _typechain__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(67276); +/* harmony import */ var _typechain__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(21278); /* harmony import */ var _batch__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(9723); /* harmony import */ var _deposits__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(7240); /* harmony import */ var _encryptedNotes__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(33298); diff --git a/dist/merkleTreeWorker.js b/dist/merkleTreeWorker.js index 835b909..2ebc08d 100644 --- a/dist/merkleTreeWorker.js +++ b/dist/merkleTreeWorker.js @@ -1,10 +1,7 @@ 'use strict'; -var threads = require('worker_threads'); -var crypto = require('crypto'); -var os = require('os'); -var URL = require('url'); -var VM = require('vm'); +var workerThreads = require('worker_threads'); +var ffjavascript = require('ffjavascript'); var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; @@ -18,18414 +15,473 @@ var FixedMerkleTree = {}; var simpleHash$1 = {}; -Object.defineProperty(simpleHash$1, "__esModule", { value: true }); -simpleHash$1.simpleHash = void 0; -/*** - * This is insecure hash function, just for example only - * @param data - * @param seed - * @param hashLength - */ -function simpleHash(data, seed, hashLength = 40) { - const str = data.join(''); - let i, l, hval = seed !== null && seed !== void 0 ? seed : 0x811c9dcc5; - for (i = 0, l = str.length; i < l; i++) { - hval ^= str.charCodeAt(i); - hval += (hval << 1) + (hval << 4) + (hval << 6) + (hval << 8) + (hval << 24); - } - const hash = (hval >>> 0).toString(16); - return BigInt('0x' + hash.padEnd(hashLength - (hash.length - 1), '0')).toString(10); -} -simpleHash$1.simpleHash = simpleHash; +Object.defineProperty(simpleHash$1, "__esModule", { value: true }); +simpleHash$1.simpleHash = void 0; +/*** + * This is insecure hash function, just for example only + * @param data + * @param seed + * @param hashLength + */ +function simpleHash(data, seed, hashLength = 40) { + const str = data.join(''); + let i, l, hval = seed !== null && seed !== void 0 ? seed : 0x811c9dcc5; + for (i = 0, l = str.length; i < l; i++) { + hval ^= str.charCodeAt(i); + hval += (hval << 1) + (hval << 4) + (hval << 6) + (hval << 8) + (hval << 24); + } + const hash = (hval >>> 0).toString(16); + return BigInt('0x' + hash.padEnd(hashLength - (hash.length - 1), '0')).toString(10); +} +simpleHash$1.simpleHash = simpleHash; simpleHash$1.default = (left, right) => simpleHash([left, right]); var BaseTree$1 = {}; -Object.defineProperty(BaseTree$1, "__esModule", { value: true }); -BaseTree$1.BaseTree = void 0; -class BaseTree { - get capacity() { - return 2 ** this.levels; - } - get layers() { - return this._layers.slice(); - } - get zeros() { - return this._zeros.slice(); - } - get elements() { - return this._layers[0].slice(); - } - get root() { - var _a; - return (_a = this._layers[this.levels][0]) !== null && _a !== void 0 ? _a : this._zeros[this.levels]; - } - /** - * Find an element in the tree - * @param elements elements of tree - * @param element An element to find - * @param comparator A function that checks leaf value equality - * @param fromIndex The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned - * @returns {number} Index if element is found, otherwise -1 - */ - static indexOf(elements, element, fromIndex, comparator) { - if (comparator) { - return elements.findIndex((el) => comparator(element, el)); - } - else { - return elements.indexOf(element, fromIndex); - } - } - /** - * Insert new element into the tree - * @param element Element to insert - */ - insert(element) { - if (this._layers[0].length >= this.capacity) { - throw new Error('Tree is full'); - } - this.update(this._layers[0].length, element); - } - /* - * Insert multiple elements into the tree. - * @param {Array} elements Elements to insert - */ - bulkInsert(elements) { - if (!elements.length) { - return; - } - if (this._layers[0].length + elements.length > this.capacity) { - throw new Error('Tree is full'); - } - // First we insert all elements except the last one - // updating only full subtree hashes (all layers where inserted element has odd index) - // the last element will update the full path to the root making the tree consistent again - for (let i = 0; i < elements.length - 1; i++) { - this._layers[0].push(elements[i]); - let level = 0; - let index = this._layers[0].length - 1; - while (index % 2 === 1) { - level++; - index >>= 1; - const left = this._layers[level - 1][index * 2]; - const right = this._layers[level - 1][index * 2 + 1]; - this._layers[level][index] = this._hashFn(left, right); - } - } - this.insert(elements[elements.length - 1]); - } - /** - * Change an element in the tree - * @param {number} index Index of element to change - * @param element Updated element value - */ - update(index, element) { - if (isNaN(Number(index)) || index < 0 || index > this._layers[0].length || index >= this.capacity) { - throw new Error('Insert index out of bounds: ' + index); - } - this._layers[0][index] = element; - this._processUpdate(index); - } - /** - * Get merkle path to a leaf - * @param {number} index Leaf index to generate path for - * @returns {{pathElements: Object[], pathIndex: number[]}} An object containing adjacent elements and left-right index - */ - path(index) { - if (isNaN(Number(index)) || index < 0 || index >= this._layers[0].length) { - throw new Error('Index out of bounds: ' + index); - } - let elIndex = +index; - const pathElements = []; - const pathIndices = []; - const pathPositions = []; - for (let level = 0; level < this.levels; level++) { - pathIndices[level] = elIndex % 2; - const leafIndex = elIndex ^ 1; - if (leafIndex < this._layers[level].length) { - pathElements[level] = this._layers[level][leafIndex]; - pathPositions[level] = leafIndex; - } - else { - pathElements[level] = this._zeros[level]; - pathPositions[level] = 0; - } - elIndex >>= 1; - } - return { - pathElements, - pathIndices, - pathPositions, - pathRoot: this.root, - }; - } - _buildZeros() { - this._zeros = [this.zeroElement]; - for (let i = 1; i <= this.levels; i++) { - this._zeros[i] = this._hashFn(this._zeros[i - 1], this._zeros[i - 1]); - } - } - _processNodes(nodes, layerIndex) { - const length = nodes.length; - let currentLength = Math.ceil(length / 2); - const currentLayer = new Array(currentLength); - currentLength--; - const starFrom = length - ((length % 2) ^ 1); - let j = 0; - for (let i = starFrom; i >= 0; i -= 2) { - if (nodes[i - 1] === undefined) - break; - const left = nodes[i - 1]; - const right = (i === starFrom && length % 2 === 1) ? this._zeros[layerIndex - 1] : nodes[i]; - currentLayer[currentLength - j] = this._hashFn(left, right); - j++; - } - return currentLayer; - } - _processUpdate(index) { - for (let level = 1; level <= this.levels; level++) { - index >>= 1; - const left = this._layers[level - 1][index * 2]; - const right = index * 2 + 1 < this._layers[level - 1].length - ? this._layers[level - 1][index * 2 + 1] - : this._zeros[level - 1]; - this._layers[level][index] = this._hashFn(left, right); - } - } -} +Object.defineProperty(BaseTree$1, "__esModule", { value: true }); +BaseTree$1.BaseTree = void 0; +class BaseTree { + get capacity() { + return 2 ** this.levels; + } + get layers() { + return this._layers.slice(); + } + get zeros() { + return this._zeros.slice(); + } + get elements() { + return this._layers[0].slice(); + } + get root() { + var _a; + return (_a = this._layers[this.levels][0]) !== null && _a !== void 0 ? _a : this._zeros[this.levels]; + } + /** + * Find an element in the tree + * @param elements elements of tree + * @param element An element to find + * @param comparator A function that checks leaf value equality + * @param fromIndex The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned + * @returns {number} Index if element is found, otherwise -1 + */ + static indexOf(elements, element, fromIndex, comparator) { + if (comparator) { + return elements.findIndex((el) => comparator(element, el)); + } + else { + return elements.indexOf(element, fromIndex); + } + } + /** + * Insert new element into the tree + * @param element Element to insert + */ + insert(element) { + if (this._layers[0].length >= this.capacity) { + throw new Error('Tree is full'); + } + this.update(this._layers[0].length, element); + } + /* + * Insert multiple elements into the tree. + * @param {Array} elements Elements to insert + */ + bulkInsert(elements) { + if (!elements.length) { + return; + } + if (this._layers[0].length + elements.length > this.capacity) { + throw new Error('Tree is full'); + } + // First we insert all elements except the last one + // updating only full subtree hashes (all layers where inserted element has odd index) + // the last element will update the full path to the root making the tree consistent again + for (let i = 0; i < elements.length - 1; i++) { + this._layers[0].push(elements[i]); + let level = 0; + let index = this._layers[0].length - 1; + while (index % 2 === 1) { + level++; + index >>= 1; + const left = this._layers[level - 1][index * 2]; + const right = this._layers[level - 1][index * 2 + 1]; + this._layers[level][index] = this._hashFn(left, right); + } + } + this.insert(elements[elements.length - 1]); + } + /** + * Change an element in the tree + * @param {number} index Index of element to change + * @param element Updated element value + */ + update(index, element) { + if (isNaN(Number(index)) || index < 0 || index > this._layers[0].length || index >= this.capacity) { + throw new Error('Insert index out of bounds: ' + index); + } + this._layers[0][index] = element; + this._processUpdate(index); + } + /** + * Get merkle path to a leaf + * @param {number} index Leaf index to generate path for + * @returns {{pathElements: Object[], pathIndex: number[]}} An object containing adjacent elements and left-right index + */ + path(index) { + if (isNaN(Number(index)) || index < 0 || index >= this._layers[0].length) { + throw new Error('Index out of bounds: ' + index); + } + let elIndex = +index; + const pathElements = []; + const pathIndices = []; + const pathPositions = []; + for (let level = 0; level < this.levels; level++) { + pathIndices[level] = elIndex % 2; + const leafIndex = elIndex ^ 1; + if (leafIndex < this._layers[level].length) { + pathElements[level] = this._layers[level][leafIndex]; + pathPositions[level] = leafIndex; + } + else { + pathElements[level] = this._zeros[level]; + pathPositions[level] = 0; + } + elIndex >>= 1; + } + return { + pathElements, + pathIndices, + pathPositions, + pathRoot: this.root, + }; + } + _buildZeros() { + this._zeros = [this.zeroElement]; + for (let i = 1; i <= this.levels; i++) { + this._zeros[i] = this._hashFn(this._zeros[i - 1], this._zeros[i - 1]); + } + } + _processNodes(nodes, layerIndex) { + const length = nodes.length; + let currentLength = Math.ceil(length / 2); + const currentLayer = new Array(currentLength); + currentLength--; + const starFrom = length - ((length % 2) ^ 1); + let j = 0; + for (let i = starFrom; i >= 0; i -= 2) { + if (nodes[i - 1] === undefined) + break; + const left = nodes[i - 1]; + const right = (i === starFrom && length % 2 === 1) ? this._zeros[layerIndex - 1] : nodes[i]; + currentLayer[currentLength - j] = this._hashFn(left, right); + j++; + } + return currentLayer; + } + _processUpdate(index) { + for (let level = 1; level <= this.levels; level++) { + index >>= 1; + const left = this._layers[level - 1][index * 2]; + const right = index * 2 + 1 < this._layers[level - 1].length + ? this._layers[level - 1][index * 2 + 1] + : this._zeros[level - 1]; + this._layers[level][index] = this._hashFn(left, right); + } + } +} BaseTree$1.BaseTree = BaseTree; -var __importDefault$1 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(FixedMerkleTree, "__esModule", { value: true }); -const simpleHash_1$1 = __importDefault$1(simpleHash$1); -const BaseTree_1$1 = BaseTree$1; -class MerkleTree extends BaseTree_1$1.BaseTree { - constructor(levels, elements = [], { hashFunction = simpleHash_1$1.default, zeroElement = 0, } = {}) { - super(); - this.levels = levels; - if (elements.length > this.capacity) { - throw new Error('Tree is full'); - } - this._hashFn = hashFunction; - this.zeroElement = zeroElement; - this._layers = []; - const leaves = elements.slice(); - this._layers = [leaves]; - this._buildZeros(); - this._buildHashes(); - } - _buildHashes() { - for (let layerIndex = 1; layerIndex <= this.levels; layerIndex++) { - const nodes = this._layers[layerIndex - 1]; - this._layers[layerIndex] = this._processNodes(nodes, layerIndex); - } - } - /** - * Insert multiple elements into the tree. - * @param {Array} elements Elements to insert - */ - bulkInsert(elements) { - if (!elements.length) { - return; - } - if (this._layers[0].length + elements.length > this.capacity) { - throw new Error('Tree is full'); - } - // First we insert all elements except the last one - // updating only full subtree hashes (all layers where inserted element has odd index) - // the last element will update the full path to the root making the tree consistent again - for (let i = 0; i < elements.length - 1; i++) { - this._layers[0].push(elements[i]); - let level = 0; - let index = this._layers[0].length - 1; - while (index % 2 === 1) { - level++; - index >>= 1; - this._layers[level][index] = this._hashFn(this._layers[level - 1][index * 2], this._layers[level - 1][index * 2 + 1]); - } - } - this.insert(elements[elements.length - 1]); - } - indexOf(element, comparator) { - return BaseTree_1$1.BaseTree.indexOf(this._layers[0], element, 0, comparator); - } - proof(element) { - const index = this.indexOf(element); - return this.path(index); - } - getTreeEdge(edgeIndex) { - const edgeElement = this._layers[0][edgeIndex]; - if (edgeElement === undefined) { - throw new Error('Element not found'); - } - const edgePath = this.path(edgeIndex); - return { edgePath, edgeElement, edgeIndex, edgeElementsCount: this._layers[0].length }; - } - /** - * 🪓 - * @param count - */ - getTreeSlices(count = 4) { - const length = this._layers[0].length; - let size = Math.ceil(length / count); - if (size % 2) - size++; - const slices = []; - for (let i = 0; i < length; i += size) { - const edgeLeft = i; - const edgeRight = i + size; - slices.push({ edge: this.getTreeEdge(edgeLeft), elements: this.elements.slice(edgeLeft, edgeRight) }); - } - return slices; - } - /** - * Serialize entire tree state including intermediate layers into a plain object - * Deserializing it back will not require to recompute any hashes - * Elements are not converted to a plain type, this is responsibility of the caller - */ - serialize() { - return { - levels: this.levels, - _zeros: this._zeros, - _layers: this._layers, - }; - } - /** - * Deserialize data into a MerkleTree instance - * Make sure to provide the same hashFunction as was used in the source tree, - * otherwise the tree state will be invalid - */ - static deserialize(data, hashFunction) { - const instance = Object.assign(Object.create(this.prototype), data); - instance._hashFn = hashFunction || simpleHash_1$1.default; - instance.zeroElement = instance._zeros[0]; - return instance; - } - toString() { - return JSON.stringify(this.serialize()); - } -} +var __importDefault$1 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(FixedMerkleTree, "__esModule", { value: true }); +const simpleHash_1$1 = __importDefault$1(simpleHash$1); +const BaseTree_1$1 = BaseTree$1; +class MerkleTree extends BaseTree_1$1.BaseTree { + constructor(levels, elements = [], { hashFunction = simpleHash_1$1.default, zeroElement = 0, } = {}) { + super(); + this.levels = levels; + if (elements.length > this.capacity) { + throw new Error('Tree is full'); + } + this._hashFn = hashFunction; + this.zeroElement = zeroElement; + this._layers = []; + const leaves = elements.slice(); + this._layers = [leaves]; + this._buildZeros(); + this._buildHashes(); + } + _buildHashes() { + for (let layerIndex = 1; layerIndex <= this.levels; layerIndex++) { + const nodes = this._layers[layerIndex - 1]; + this._layers[layerIndex] = this._processNodes(nodes, layerIndex); + } + } + /** + * Insert multiple elements into the tree. + * @param {Array} elements Elements to insert + */ + bulkInsert(elements) { + if (!elements.length) { + return; + } + if (this._layers[0].length + elements.length > this.capacity) { + throw new Error('Tree is full'); + } + // First we insert all elements except the last one + // updating only full subtree hashes (all layers where inserted element has odd index) + // the last element will update the full path to the root making the tree consistent again + for (let i = 0; i < elements.length - 1; i++) { + this._layers[0].push(elements[i]); + let level = 0; + let index = this._layers[0].length - 1; + while (index % 2 === 1) { + level++; + index >>= 1; + this._layers[level][index] = this._hashFn(this._layers[level - 1][index * 2], this._layers[level - 1][index * 2 + 1]); + } + } + this.insert(elements[elements.length - 1]); + } + indexOf(element, comparator) { + return BaseTree_1$1.BaseTree.indexOf(this._layers[0], element, 0, comparator); + } + proof(element) { + const index = this.indexOf(element); + return this.path(index); + } + getTreeEdge(edgeIndex) { + const edgeElement = this._layers[0][edgeIndex]; + if (edgeElement === undefined) { + throw new Error('Element not found'); + } + const edgePath = this.path(edgeIndex); + return { edgePath, edgeElement, edgeIndex, edgeElementsCount: this._layers[0].length }; + } + /** + * 🪓 + * @param count + */ + getTreeSlices(count = 4) { + const length = this._layers[0].length; + let size = Math.ceil(length / count); + if (size % 2) + size++; + const slices = []; + for (let i = 0; i < length; i += size) { + const edgeLeft = i; + const edgeRight = i + size; + slices.push({ edge: this.getTreeEdge(edgeLeft), elements: this.elements.slice(edgeLeft, edgeRight) }); + } + return slices; + } + /** + * Serialize entire tree state including intermediate layers into a plain object + * Deserializing it back will not require to recompute any hashes + * Elements are not converted to a plain type, this is responsibility of the caller + */ + serialize() { + return { + levels: this.levels, + _zeros: this._zeros, + _layers: this._layers, + }; + } + /** + * Deserialize data into a MerkleTree instance + * Make sure to provide the same hashFunction as was used in the source tree, + * otherwise the tree state will be invalid + */ + static deserialize(data, hashFunction) { + const instance = Object.assign(Object.create(this.prototype), data); + instance._hashFn = hashFunction || simpleHash_1$1.default; + instance.zeroElement = instance._zeros[0]; + return instance; + } + toString() { + return JSON.stringify(this.serialize()); + } +} FixedMerkleTree.default = MerkleTree; var PartialMerkleTree$1 = {}; -var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(PartialMerkleTree$1, "__esModule", { value: true }); -PartialMerkleTree$1.PartialMerkleTree = void 0; -const simpleHash_1 = __importDefault(simpleHash$1); -const BaseTree_1 = BaseTree$1; -class PartialMerkleTree extends BaseTree_1.BaseTree { - constructor(levels, { edgePath, edgeElement, edgeIndex, edgeElementsCount, }, leaves, { hashFunction, zeroElement } = {}) { - super(); - if (edgeIndex + leaves.length !== edgeElementsCount) - throw new Error('Invalid number of elements'); - this._edgeLeafProof = edgePath; - this._initialRoot = edgePath.pathRoot; - this.zeroElement = zeroElement !== null && zeroElement !== void 0 ? zeroElement : 0; - this._edgeLeaf = { data: edgeElement, index: edgeIndex }; - this._leavesAfterEdge = leaves; - this.levels = levels; - this._hashFn = hashFunction || simpleHash_1.default; - this._createProofMap(); - this._buildTree(); - } - get edgeIndex() { - return this._edgeLeaf.index; - } - get edgeElement() { - return this._edgeLeaf.data; - } - get edgeLeafProof() { - return this._edgeLeafProof; - } - _createProofMap() { - this._proofMap = this.edgeLeafProof.pathPositions.reduce((p, c, i) => { - p.set(i, [c, this.edgeLeafProof.pathElements[i]]); - return p; - }, new Map()); - this._proofMap.set(this.levels, [0, this.edgeLeafProof.pathRoot]); - } - _buildTree() { - const edgeLeafIndex = this._edgeLeaf.index; - this._leaves = Array(edgeLeafIndex).concat(this._leavesAfterEdge); - if (this._proofMap.has(0)) { - const [proofPos, proofEl] = this._proofMap.get(0); - this._leaves[proofPos] = proofEl; - } - this._layers = [this._leaves]; - this._buildZeros(); - this._buildHashes(); - } - _buildHashes() { - for (let layerIndex = 1; layerIndex <= this.levels; layerIndex++) { - const nodes = this._layers[layerIndex - 1]; - const currentLayer = this._processNodes(nodes, layerIndex); - if (this._proofMap.has(layerIndex)) { - const [proofPos, proofEl] = this._proofMap.get(layerIndex); - if (!currentLayer[proofPos]) - currentLayer[proofPos] = proofEl; - } - this._layers[layerIndex] = currentLayer; - } - } - /** - * Change an element in the tree - * @param {number} index Index of element to change - * @param element Updated element value - */ - update(index, element) { - if (isNaN(Number(index)) || index < 0 || index > this._layers[0].length || index >= this.capacity) { - throw new Error('Insert index out of bounds: ' + index); - } - if (index < this._edgeLeaf.index) { - throw new Error(`Index ${index} is below the edge: ${this._edgeLeaf.index}`); - } - this._layers[0][index] = element; - this._processUpdate(index); - } - path(index) { - var _a; - if (isNaN(Number(index)) || index < 0 || index >= this._layers[0].length) { - throw new Error('Index out of bounds: ' + index); - } - if (index < this._edgeLeaf.index) { - throw new Error(`Index ${index} is below the edge: ${this._edgeLeaf.index}`); - } - let elIndex = Number(index); - const pathElements = []; - const pathIndices = []; - const pathPositions = []; - for (let level = 0; level < this.levels; level++) { - pathIndices[level] = elIndex % 2; - const leafIndex = elIndex ^ 1; - if (leafIndex < this._layers[level].length) { - pathElements[level] = this._layers[level][leafIndex]; - pathPositions[level] = leafIndex; - } - else { - pathElements[level] = this._zeros[level]; - pathPositions[level] = 0; - } - const [proofPos, proofEl] = this._proofMap.get(level); - pathElements[level] = (_a = pathElements[level]) !== null && _a !== void 0 ? _a : (proofPos === leafIndex ? proofEl : this._zeros[level]); - elIndex >>= 1; - } - return { - pathElements, - pathIndices, - pathPositions, - pathRoot: this.root, - }; - } - indexOf(element, comparator) { - return BaseTree_1.BaseTree.indexOf(this._layers[0], element, this.edgeIndex, comparator); - } - proof(element) { - const index = this.indexOf(element); - return this.path(index); - } - /** - * Shifts edge of tree to left - * @param edge new TreeEdge below current edge - * @param elements leaves between old and new edge - */ - shiftEdge(edge, elements) { - if (this._edgeLeaf.index <= edge.edgeIndex) { - throw new Error(`New edgeIndex should be smaller then ${this._edgeLeaf.index}`); - } - if (elements.length !== (this._edgeLeaf.index - edge.edgeIndex)) { - throw new Error(`Elements length should be ${this._edgeLeaf.index - edge.edgeIndex}`); - } - this._edgeLeafProof = edge.edgePath; - this._edgeLeaf = { index: edge.edgeIndex, data: edge.edgeElement }; - this._leavesAfterEdge = [...elements, ...this._leavesAfterEdge]; - this._createProofMap(); - this._buildTree(); - } - serialize() { - return { - _edgeLeafProof: this._edgeLeafProof, - _edgeLeaf: this._edgeLeaf, - _layers: this._layers, - _zeros: this._zeros, - levels: this.levels, - }; - } - static deserialize(data, hashFunction) { - const instance = Object.assign(Object.create(this.prototype), data); - instance._hashFn = hashFunction || simpleHash_1.default; - instance._initialRoot = data._edgeLeafProof.pathRoot; - instance.zeroElement = instance._zeros[0]; - instance._leavesAfterEdge = instance._layers[0].slice(data._edgeLeaf.index); - instance._createProofMap(); - return instance; - } - toString() { - return JSON.stringify(this.serialize()); - } -} +var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(PartialMerkleTree$1, "__esModule", { value: true }); +PartialMerkleTree$1.PartialMerkleTree = void 0; +const simpleHash_1 = __importDefault(simpleHash$1); +const BaseTree_1 = BaseTree$1; +class PartialMerkleTree extends BaseTree_1.BaseTree { + constructor(levels, { edgePath, edgeElement, edgeIndex, edgeElementsCount, }, leaves, { hashFunction, zeroElement } = {}) { + super(); + if (edgeIndex + leaves.length !== edgeElementsCount) + throw new Error('Invalid number of elements'); + this._edgeLeafProof = edgePath; + this._initialRoot = edgePath.pathRoot; + this.zeroElement = zeroElement !== null && zeroElement !== void 0 ? zeroElement : 0; + this._edgeLeaf = { data: edgeElement, index: edgeIndex }; + this._leavesAfterEdge = leaves; + this.levels = levels; + this._hashFn = hashFunction || simpleHash_1.default; + this._createProofMap(); + this._buildTree(); + } + get edgeIndex() { + return this._edgeLeaf.index; + } + get edgeElement() { + return this._edgeLeaf.data; + } + get edgeLeafProof() { + return this._edgeLeafProof; + } + _createProofMap() { + this._proofMap = this.edgeLeafProof.pathPositions.reduce((p, c, i) => { + p.set(i, [c, this.edgeLeafProof.pathElements[i]]); + return p; + }, new Map()); + this._proofMap.set(this.levels, [0, this.edgeLeafProof.pathRoot]); + } + _buildTree() { + const edgeLeafIndex = this._edgeLeaf.index; + this._leaves = Array(edgeLeafIndex).concat(this._leavesAfterEdge); + if (this._proofMap.has(0)) { + const [proofPos, proofEl] = this._proofMap.get(0); + this._leaves[proofPos] = proofEl; + } + this._layers = [this._leaves]; + this._buildZeros(); + this._buildHashes(); + } + _buildHashes() { + for (let layerIndex = 1; layerIndex <= this.levels; layerIndex++) { + const nodes = this._layers[layerIndex - 1]; + const currentLayer = this._processNodes(nodes, layerIndex); + if (this._proofMap.has(layerIndex)) { + const [proofPos, proofEl] = this._proofMap.get(layerIndex); + if (!currentLayer[proofPos]) + currentLayer[proofPos] = proofEl; + } + this._layers[layerIndex] = currentLayer; + } + } + /** + * Change an element in the tree + * @param {number} index Index of element to change + * @param element Updated element value + */ + update(index, element) { + if (isNaN(Number(index)) || index < 0 || index > this._layers[0].length || index >= this.capacity) { + throw new Error('Insert index out of bounds: ' + index); + } + if (index < this._edgeLeaf.index) { + throw new Error(`Index ${index} is below the edge: ${this._edgeLeaf.index}`); + } + this._layers[0][index] = element; + this._processUpdate(index); + } + path(index) { + var _a; + if (isNaN(Number(index)) || index < 0 || index >= this._layers[0].length) { + throw new Error('Index out of bounds: ' + index); + } + if (index < this._edgeLeaf.index) { + throw new Error(`Index ${index} is below the edge: ${this._edgeLeaf.index}`); + } + let elIndex = Number(index); + const pathElements = []; + const pathIndices = []; + const pathPositions = []; + for (let level = 0; level < this.levels; level++) { + pathIndices[level] = elIndex % 2; + const leafIndex = elIndex ^ 1; + if (leafIndex < this._layers[level].length) { + pathElements[level] = this._layers[level][leafIndex]; + pathPositions[level] = leafIndex; + } + else { + pathElements[level] = this._zeros[level]; + pathPositions[level] = 0; + } + const [proofPos, proofEl] = this._proofMap.get(level); + pathElements[level] = (_a = pathElements[level]) !== null && _a !== void 0 ? _a : (proofPos === leafIndex ? proofEl : this._zeros[level]); + elIndex >>= 1; + } + return { + pathElements, + pathIndices, + pathPositions, + pathRoot: this.root, + }; + } + indexOf(element, comparator) { + return BaseTree_1.BaseTree.indexOf(this._layers[0], element, this.edgeIndex, comparator); + } + proof(element) { + const index = this.indexOf(element); + return this.path(index); + } + /** + * Shifts edge of tree to left + * @param edge new TreeEdge below current edge + * @param elements leaves between old and new edge + */ + shiftEdge(edge, elements) { + if (this._edgeLeaf.index <= edge.edgeIndex) { + throw new Error(`New edgeIndex should be smaller then ${this._edgeLeaf.index}`); + } + if (elements.length !== (this._edgeLeaf.index - edge.edgeIndex)) { + throw new Error(`Elements length should be ${this._edgeLeaf.index - edge.edgeIndex}`); + } + this._edgeLeafProof = edge.edgePath; + this._edgeLeaf = { index: edge.edgeIndex, data: edge.edgeElement }; + this._leavesAfterEdge = [...elements, ...this._leavesAfterEdge]; + this._createProofMap(); + this._buildTree(); + } + serialize() { + return { + _edgeLeafProof: this._edgeLeafProof, + _edgeLeaf: this._edgeLeaf, + _layers: this._layers, + _zeros: this._zeros, + levels: this.levels, + }; + } + static deserialize(data, hashFunction) { + const instance = Object.assign(Object.create(this.prototype), data); + instance._hashFn = hashFunction || simpleHash_1.default; + instance._initialRoot = data._edgeLeafProof.pathRoot; + instance.zeroElement = instance._zeros[0]; + instance._leavesAfterEdge = instance._layers[0].slice(data._edgeLeaf.index); + instance._createProofMap(); + return instance; + } + toString() { + return JSON.stringify(this.serialize()); + } +} PartialMerkleTree$1.PartialMerkleTree = PartialMerkleTree; (function (exports) { - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MerkleTree = exports.simpleHash = exports.PartialMerkleTree = void 0; - const FixedMerkleTree_1 = __importDefault(FixedMerkleTree); - Object.defineProperty(exports, "MerkleTree", { enumerable: true, get: function () { return FixedMerkleTree_1.default; } }); - var PartialMerkleTree_1 = PartialMerkleTree$1; - Object.defineProperty(exports, "PartialMerkleTree", { enumerable: true, get: function () { return PartialMerkleTree_1.PartialMerkleTree; } }); - var simpleHash_1 = simpleHash$1; - Object.defineProperty(exports, "simpleHash", { enumerable: true, get: function () { return simpleHash_1.simpleHash; } }); + var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MerkleTree = exports.simpleHash = exports.PartialMerkleTree = void 0; + const FixedMerkleTree_1 = __importDefault(FixedMerkleTree); + Object.defineProperty(exports, "MerkleTree", { enumerable: true, get: function () { return FixedMerkleTree_1.default; } }); + var PartialMerkleTree_1 = PartialMerkleTree$1; + Object.defineProperty(exports, "PartialMerkleTree", { enumerable: true, get: function () { return PartialMerkleTree_1.PartialMerkleTree; } }); + var simpleHash_1 = simpleHash$1; + Object.defineProperty(exports, "simpleHash", { enumerable: true, get: function () { return simpleHash_1.simpleHash; } }); exports.default = FixedMerkleTree_1.default; } (lib)); -/* global BigInt */ -const hexLen = [ 0, 1, 2, 2, 3, 3, 3, 3, 4 ,4 ,4 ,4 ,4 ,4 ,4 ,4]; - -function fromString$2(s, radix) { - if ((!radix)||(radix==10)) { - return BigInt(s); - } else if (radix==16) { - if (s.slice(0,2) == "0x") { - return BigInt(s); - } else { - return BigInt("0x"+s); - } - } -} - -const e$2 = fromString$2; - -function fromArray$2(a, radix) { - let acc =BigInt(0); - radix = BigInt(radix); - for (let i=0; i> BigInt(n); -} - -const shl$2 = shiftLeft$2; -const shr$2 = shiftRight$2; - -function isOdd$2(a) { - return (BigInt(a) & BigInt(1)) == BigInt(1); -} - - -function naf$2(n) { - let E = BigInt(n); - const res = []; - while (E) { - if (E & BigInt(1)) { - const z = 2 - Number(E % BigInt(4)); - res.push( z ); - E = E - BigInt(z); - } else { - res.push( 0 ); - } - E = E >> BigInt(1); - } - return res; -} - - -function bits$2(n) { - let E = BigInt(n); - const res = []; - while (E) { - if (E & BigInt(1)) { - res.push(1); - } else { - res.push( 0 ); - } - E = E >> BigInt(1); - } - return res; -} - -function toNumber$3(s) { - if (s>BigInt(Number.MAX_SAFE_INTEGER )) { - throw new Error("Number too big"); - } - return Number(s); -} - -function toArray$2(s, radix) { - const res = []; - let rem = BigInt(s); - radix = BigInt(radix); - while (rem) { - res.unshift( Number(rem % radix)); - rem = rem / radix; - } - return res; -} - - -function add$2(a, b) { - return BigInt(a) + BigInt(b); -} - -function sub$2(a, b) { - return BigInt(a) - BigInt(b); -} - -function neg$2(a) { - return -BigInt(a); -} - -function mul$2(a, b) { - return BigInt(a) * BigInt(b); -} - -function square$2(a) { - return BigInt(a) * BigInt(a); -} - -function pow$2(a, b) { - return BigInt(a) ** BigInt(b); -} - -function exp$2(a, b) { - return BigInt(a) ** BigInt(b); -} - -function abs$2(a) { - return BigInt(a) >= 0 ? BigInt(a) : -BigInt(a); -} - -function div$2(a, b) { - return BigInt(a) / BigInt(b); -} - -function mod$2(a, b) { - return BigInt(a) % BigInt(b); -} - -function eq$2(a, b) { - return BigInt(a) == BigInt(b); -} - -function neq$2(a, b) { - return BigInt(a) != BigInt(b); -} - -function lt$2(a, b) { - return BigInt(a) < BigInt(b); -} - -function gt$2(a, b) { - return BigInt(a) > BigInt(b); -} - -function leq$2(a, b) { - return BigInt(a) <= BigInt(b); -} - -function geq$2(a, b) { - return BigInt(a) >= BigInt(b); -} - -function band$2(a, b) { - return BigInt(a) & BigInt(b); -} - -function bor$2(a, b) { - return BigInt(a) | BigInt(b); -} - -function bxor$2(a, b) { - return BigInt(a) ^ BigInt(b); -} - -function land$2(a, b) { - return BigInt(a) && BigInt(b); -} - -function lor$2(a, b) { - return BigInt(a) || BigInt(b); -} - -function lnot$2(a) { - return !BigInt(a); -} - -var Scalar_native = /*#__PURE__*/Object.freeze({ - __proto__: null, - abs: abs$2, - add: add$2, - band: band$2, - bitLength: bitLength$2, - bits: bits$2, - bor: bor$2, - bxor: bxor$2, - div: div$2, - e: e$2, - eq: eq$2, - exp: exp$2, - fromArray: fromArray$2, - fromString: fromString$2, - geq: geq$2, - gt: gt$2, - isNegative: isNegative$2, - isOdd: isOdd$2, - isZero: isZero$2, - land: land$2, - leq: leq$2, - lnot: lnot$2, - lor: lor$2, - lt: lt$2, - mod: mod$2, - mul: mul$2, - naf: naf$2, - neg: neg$2, - neq: neq$2, - pow: pow$2, - shiftLeft: shiftLeft$2, - shiftRight: shiftRight$2, - shl: shl$2, - shr: shr$2, - square: square$2, - sub: sub$2, - toArray: toArray$2, - toNumber: toNumber$3 -}); - -var BigInteger = {exports: {}}; - -(function (module) { - var bigInt = (function (undefined$1) { - - var BASE = 1e7, - LOG_BASE = 7, - MAX_INT = 9007199254740992, - MAX_INT_ARR = smallToArray(MAX_INT), - DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"; - - var supportsNativeBigInt = typeof BigInt === "function"; - - function Integer(v, radix, alphabet, caseSensitive) { - if (typeof v === "undefined") return Integer[0]; - if (typeof radix !== "undefined") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive); - return parseValue(v); - } - - function BigInteger(value, sign) { - this.value = value; - this.sign = sign; - this.isSmall = false; - } - BigInteger.prototype = Object.create(Integer.prototype); - - function SmallInteger(value) { - this.value = value; - this.sign = value < 0; - this.isSmall = true; - } - SmallInteger.prototype = Object.create(Integer.prototype); - - function NativeBigInt(value) { - this.value = value; - } - NativeBigInt.prototype = Object.create(Integer.prototype); - - function isPrecise(n) { - return -MAX_INT < n && n < MAX_INT; - } - - function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes - if (n < 1e7) - return [n]; - if (n < 1e14) - return [n % 1e7, Math.floor(n / 1e7)]; - return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)]; - } - - function arrayToSmall(arr) { // If BASE changes this function may need to change - trim(arr); - var length = arr.length; - if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) { - switch (length) { - case 0: return 0; - case 1: return arr[0]; - case 2: return arr[0] + arr[1] * BASE; - default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE; - } - } - return arr; - } - - function trim(v) { - var i = v.length; - while (v[--i] === 0); - v.length = i + 1; - } - - function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger - var x = new Array(length); - var i = -1; - while (++i < length) { - x[i] = 0; - } - return x; - } - - function truncate(n) { - if (n > 0) return Math.floor(n); - return Math.ceil(n); - } - - function add(a, b) { // assumes a and b are arrays with a.length >= b.length - var l_a = a.length, - l_b = b.length, - r = new Array(l_a), - carry = 0, - base = BASE, - sum, i; - for (i = 0; i < l_b; i++) { - sum = a[i] + b[i] + carry; - carry = sum >= base ? 1 : 0; - r[i] = sum - carry * base; - } - while (i < l_a) { - sum = a[i] + carry; - carry = sum === base ? 1 : 0; - r[i++] = sum - carry * base; - } - if (carry > 0) r.push(carry); - return r; - } - - function addAny(a, b) { - if (a.length >= b.length) return add(a, b); - return add(b, a); - } - - function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT - var l = a.length, - r = new Array(l), - base = BASE, - sum, i; - for (i = 0; i < l; i++) { - sum = a[i] - base + carry; - carry = Math.floor(sum / base); - r[i] = sum - carry * base; - carry += 1; - } - while (carry > 0) { - r[i++] = carry % base; - carry = Math.floor(carry / base); - } - return r; - } - - BigInteger.prototype.add = function (v) { - var n = parseValue(v); - if (this.sign !== n.sign) { - return this.subtract(n.negate()); - } - var a = this.value, b = n.value; - if (n.isSmall) { - return new BigInteger(addSmall(a, Math.abs(b)), this.sign); - } - return new BigInteger(addAny(a, b), this.sign); - }; - BigInteger.prototype.plus = BigInteger.prototype.add; - - SmallInteger.prototype.add = function (v) { - var n = parseValue(v); - var a = this.value; - if (a < 0 !== n.sign) { - return this.subtract(n.negate()); - } - var b = n.value; - if (n.isSmall) { - if (isPrecise(a + b)) return new SmallInteger(a + b); - b = smallToArray(Math.abs(b)); - } - return new BigInteger(addSmall(b, Math.abs(a)), a < 0); - }; - SmallInteger.prototype.plus = SmallInteger.prototype.add; - - NativeBigInt.prototype.add = function (v) { - return new NativeBigInt(this.value + parseValue(v).value); - }; - NativeBigInt.prototype.plus = NativeBigInt.prototype.add; - - function subtract(a, b) { // assumes a and b are arrays with a >= b - var a_l = a.length, - b_l = b.length, - r = new Array(a_l), - borrow = 0, - base = BASE, - i, difference; - for (i = 0; i < b_l; i++) { - difference = a[i] - borrow - b[i]; - if (difference < 0) { - difference += base; - borrow = 1; - } else borrow = 0; - r[i] = difference; - } - for (i = b_l; i < a_l; i++) { - difference = a[i] - borrow; - if (difference < 0) difference += base; - else { - r[i++] = difference; - break; - } - r[i] = difference; - } - for (; i < a_l; i++) { - r[i] = a[i]; - } - trim(r); - return r; - } - - function subtractAny(a, b, sign) { - var value; - if (compareAbs(a, b) >= 0) { - value = subtract(a, b); - } else { - value = subtract(b, a); - sign = !sign; - } - value = arrayToSmall(value); - if (typeof value === "number") { - if (sign) value = -value; - return new SmallInteger(value); - } - return new BigInteger(value, sign); - } - - function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT - var l = a.length, - r = new Array(l), - carry = -b, - base = BASE, - i, difference; - for (i = 0; i < l; i++) { - difference = a[i] + carry; - carry = Math.floor(difference / base); - difference %= base; - r[i] = difference < 0 ? difference + base : difference; - } - r = arrayToSmall(r); - if (typeof r === "number") { - if (sign) r = -r; - return new SmallInteger(r); - } return new BigInteger(r, sign); - } - - BigInteger.prototype.subtract = function (v) { - var n = parseValue(v); - if (this.sign !== n.sign) { - return this.add(n.negate()); - } - var a = this.value, b = n.value; - if (n.isSmall) - return subtractSmall(a, Math.abs(b), this.sign); - return subtractAny(a, b, this.sign); - }; - BigInteger.prototype.minus = BigInteger.prototype.subtract; - - SmallInteger.prototype.subtract = function (v) { - var n = parseValue(v); - var a = this.value; - if (a < 0 !== n.sign) { - return this.add(n.negate()); - } - var b = n.value; - if (n.isSmall) { - return new SmallInteger(a - b); - } - return subtractSmall(b, Math.abs(a), a >= 0); - }; - SmallInteger.prototype.minus = SmallInteger.prototype.subtract; - - NativeBigInt.prototype.subtract = function (v) { - return new NativeBigInt(this.value - parseValue(v).value); - }; - NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract; - - BigInteger.prototype.negate = function () { - return new BigInteger(this.value, !this.sign); - }; - SmallInteger.prototype.negate = function () { - var sign = this.sign; - var small = new SmallInteger(-this.value); - small.sign = !sign; - return small; - }; - NativeBigInt.prototype.negate = function () { - return new NativeBigInt(-this.value); - }; - - BigInteger.prototype.abs = function () { - return new BigInteger(this.value, false); - }; - SmallInteger.prototype.abs = function () { - return new SmallInteger(Math.abs(this.value)); - }; - NativeBigInt.prototype.abs = function () { - return new NativeBigInt(this.value >= 0 ? this.value : -this.value); - }; - - - function multiplyLong(a, b) { - var a_l = a.length, - b_l = b.length, - l = a_l + b_l, - r = createArray(l), - base = BASE, - product, carry, i, a_i, b_j; - for (i = 0; i < a_l; ++i) { - a_i = a[i]; - for (var j = 0; j < b_l; ++j) { - b_j = b[j]; - product = a_i * b_j + r[i + j]; - carry = Math.floor(product / base); - r[i + j] = product - carry * base; - r[i + j + 1] += carry; - } - } - trim(r); - return r; - } - - function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE - var l = a.length, - r = new Array(l), - base = BASE, - carry = 0, - product, i; - for (i = 0; i < l; i++) { - product = a[i] * b + carry; - carry = Math.floor(product / base); - r[i] = product - carry * base; - } - while (carry > 0) { - r[i++] = carry % base; - carry = Math.floor(carry / base); - } - return r; - } - - function shiftLeft(x, n) { - var r = []; - while (n-- > 0) r.push(0); - return r.concat(x); - } - - function multiplyKaratsuba(x, y) { - var n = Math.max(x.length, y.length); - - if (n <= 30) return multiplyLong(x, y); - n = Math.ceil(n / 2); - - var b = x.slice(n), - a = x.slice(0, n), - d = y.slice(n), - c = y.slice(0, n); - - var ac = multiplyKaratsuba(a, c), - bd = multiplyKaratsuba(b, d), - abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d)); - - var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n)); - trim(product); - return product; - } - - // The following function is derived from a surface fit of a graph plotting the performance difference - // between long multiplication and karatsuba multiplication versus the lengths of the two arrays. - function useKaratsuba(l1, l2) { - return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0; - } - - BigInteger.prototype.multiply = function (v) { - var n = parseValue(v), - a = this.value, b = n.value, - sign = this.sign !== n.sign, - abs; - if (n.isSmall) { - if (b === 0) return Integer[0]; - if (b === 1) return this; - if (b === -1) return this.negate(); - abs = Math.abs(b); - if (abs < BASE) { - return new BigInteger(multiplySmall(a, abs), sign); - } - b = smallToArray(abs); - } - if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes - return new BigInteger(multiplyKaratsuba(a, b), sign); - return new BigInteger(multiplyLong(a, b), sign); - }; - - BigInteger.prototype.times = BigInteger.prototype.multiply; - - function multiplySmallAndArray(a, b, sign) { // a >= 0 - if (a < BASE) { - return new BigInteger(multiplySmall(b, a), sign); - } - return new BigInteger(multiplyLong(b, smallToArray(a)), sign); - } - SmallInteger.prototype._multiplyBySmall = function (a) { - if (isPrecise(a.value * this.value)) { - return new SmallInteger(a.value * this.value); - } - return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign); - }; - BigInteger.prototype._multiplyBySmall = function (a) { - if (a.value === 0) return Integer[0]; - if (a.value === 1) return this; - if (a.value === -1) return this.negate(); - return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign); - }; - SmallInteger.prototype.multiply = function (v) { - return parseValue(v)._multiplyBySmall(this); - }; - SmallInteger.prototype.times = SmallInteger.prototype.multiply; - - NativeBigInt.prototype.multiply = function (v) { - return new NativeBigInt(this.value * parseValue(v).value); - }; - NativeBigInt.prototype.times = NativeBigInt.prototype.multiply; - - function square(a) { - //console.assert(2 * BASE * BASE < MAX_INT); - var l = a.length, - r = createArray(l + l), - base = BASE, - product, carry, i, a_i, a_j; - for (i = 0; i < l; i++) { - a_i = a[i]; - carry = 0 - a_i * a_i; - for (var j = i; j < l; j++) { - a_j = a[j]; - product = 2 * (a_i * a_j) + r[i + j] + carry; - carry = Math.floor(product / base); - r[i + j] = product - carry * base; - } - r[i + l] = carry; - } - trim(r); - return r; - } - - BigInteger.prototype.square = function () { - return new BigInteger(square(this.value), false); - }; - - SmallInteger.prototype.square = function () { - var value = this.value * this.value; - if (isPrecise(value)) return new SmallInteger(value); - return new BigInteger(square(smallToArray(Math.abs(this.value))), false); - }; - - NativeBigInt.prototype.square = function (v) { - return new NativeBigInt(this.value * this.value); - }; - - function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes. - var a_l = a.length, - b_l = b.length, - base = BASE, - result = createArray(b.length), - divisorMostSignificantDigit = b[b_l - 1], - // normalization - lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)), - remainder = multiplySmall(a, lambda), - divisor = multiplySmall(b, lambda), - quotientDigit, shift, carry, borrow, i, l, q; - if (remainder.length <= a_l) remainder.push(0); - divisor.push(0); - divisorMostSignificantDigit = divisor[b_l - 1]; - for (shift = a_l - b_l; shift >= 0; shift--) { - quotientDigit = base - 1; - if (remainder[shift + b_l] !== divisorMostSignificantDigit) { - quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit); - } - // quotientDigit <= base - 1 - carry = 0; - borrow = 0; - l = divisor.length; - for (i = 0; i < l; i++) { - carry += quotientDigit * divisor[i]; - q = Math.floor(carry / base); - borrow += remainder[shift + i] - (carry - q * base); - carry = q; - if (borrow < 0) { - remainder[shift + i] = borrow + base; - borrow = -1; - } else { - remainder[shift + i] = borrow; - borrow = 0; - } - } - while (borrow !== 0) { - quotientDigit -= 1; - carry = 0; - for (i = 0; i < l; i++) { - carry += remainder[shift + i] - base + divisor[i]; - if (carry < 0) { - remainder[shift + i] = carry + base; - carry = 0; - } else { - remainder[shift + i] = carry; - carry = 1; - } - } - borrow += carry; - } - result[shift] = quotientDigit; - } - // denormalization - remainder = divModSmall(remainder, lambda)[0]; - return [arrayToSmall(result), arrayToSmall(remainder)]; - } - - function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/ - // Performs faster than divMod1 on larger input sizes. - var a_l = a.length, - b_l = b.length, - result = [], - part = [], - base = BASE, - guess, xlen, highx, highy, check; - while (a_l) { - part.unshift(a[--a_l]); - trim(part); - if (compareAbs(part, b) < 0) { - result.push(0); - continue; - } - xlen = part.length; - highx = part[xlen - 1] * base + part[xlen - 2]; - highy = b[b_l - 1] * base + b[b_l - 2]; - if (xlen > b_l) { - highx = (highx + 1) * base; - } - guess = Math.ceil(highx / highy); - do { - check = multiplySmall(b, guess); - if (compareAbs(check, part) <= 0) break; - guess--; - } while (guess); - result.push(guess); - part = subtract(part, check); - } - result.reverse(); - return [arrayToSmall(result), arrayToSmall(part)]; - } - - function divModSmall(value, lambda) { - var length = value.length, - quotient = createArray(length), - base = BASE, - i, q, remainder, divisor; - remainder = 0; - for (i = length - 1; i >= 0; --i) { - divisor = remainder * base + value[i]; - q = truncate(divisor / lambda); - remainder = divisor - q * lambda; - quotient[i] = q | 0; - } - return [quotient, remainder | 0]; - } - - function divModAny(self, v) { - var value, n = parseValue(v); - if (supportsNativeBigInt) { - return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)]; - } - var a = self.value, b = n.value; - var quotient; - if (b === 0) throw new Error("Cannot divide by zero"); - if (self.isSmall) { - if (n.isSmall) { - return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)]; - } - return [Integer[0], self]; - } - if (n.isSmall) { - if (b === 1) return [self, Integer[0]]; - if (b == -1) return [self.negate(), Integer[0]]; - var abs = Math.abs(b); - if (abs < BASE) { - value = divModSmall(a, abs); - quotient = arrayToSmall(value[0]); - var remainder = value[1]; - if (self.sign) remainder = -remainder; - if (typeof quotient === "number") { - if (self.sign !== n.sign) quotient = -quotient; - return [new SmallInteger(quotient), new SmallInteger(remainder)]; - } - return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)]; - } - b = smallToArray(abs); - } - var comparison = compareAbs(a, b); - if (comparison === -1) return [Integer[0], self]; - if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]]; - - // divMod1 is faster on smaller input sizes - if (a.length + b.length <= 200) - value = divMod1(a, b); - else value = divMod2(a, b); - - quotient = value[0]; - var qSign = self.sign !== n.sign, - mod = value[1], - mSign = self.sign; - if (typeof quotient === "number") { - if (qSign) quotient = -quotient; - quotient = new SmallInteger(quotient); - } else quotient = new BigInteger(quotient, qSign); - if (typeof mod === "number") { - if (mSign) mod = -mod; - mod = new SmallInteger(mod); - } else mod = new BigInteger(mod, mSign); - return [quotient, mod]; - } - - BigInteger.prototype.divmod = function (v) { - var result = divModAny(this, v); - return { - quotient: result[0], - remainder: result[1] - }; - }; - NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod; - - - BigInteger.prototype.divide = function (v) { - return divModAny(this, v)[0]; - }; - NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) { - return new NativeBigInt(this.value / parseValue(v).value); - }; - SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide; - - BigInteger.prototype.mod = function (v) { - return divModAny(this, v)[1]; - }; - NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) { - return new NativeBigInt(this.value % parseValue(v).value); - }; - SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod; - - BigInteger.prototype.pow = function (v) { - var n = parseValue(v), - a = this.value, - b = n.value, - value, x, y; - if (b === 0) return Integer[1]; - if (a === 0) return Integer[0]; - if (a === 1) return Integer[1]; - if (a === -1) return n.isEven() ? Integer[1] : Integer[-1]; - if (n.sign) { - return Integer[0]; - } - if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large."); - if (this.isSmall) { - if (isPrecise(value = Math.pow(a, b))) - return new SmallInteger(truncate(value)); - } - x = this; - y = Integer[1]; - while (true) { - if (b & 1 === 1) { - y = y.times(x); - --b; - } - if (b === 0) break; - b /= 2; - x = x.square(); - } - return y; - }; - SmallInteger.prototype.pow = BigInteger.prototype.pow; - - NativeBigInt.prototype.pow = function (v) { - var n = parseValue(v); - var a = this.value, b = n.value; - var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2); - if (b === _0) return Integer[1]; - if (a === _0) return Integer[0]; - if (a === _1) return Integer[1]; - if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1]; - if (n.isNegative()) return new NativeBigInt(_0); - var x = this; - var y = Integer[1]; - while (true) { - if ((b & _1) === _1) { - y = y.times(x); - --b; - } - if (b === _0) break; - b /= _2; - x = x.square(); - } - return y; - }; - - BigInteger.prototype.modPow = function (exp, mod) { - exp = parseValue(exp); - mod = parseValue(mod); - if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0"); - var r = Integer[1], - base = this.mod(mod); - if (exp.isNegative()) { - exp = exp.multiply(Integer[-1]); - base = base.modInv(mod); - } - while (exp.isPositive()) { - if (base.isZero()) return Integer[0]; - if (exp.isOdd()) r = r.multiply(base).mod(mod); - exp = exp.divide(2); - base = base.square().mod(mod); - } - return r; - }; - NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow; - - function compareAbs(a, b) { - if (a.length !== b.length) { - return a.length > b.length ? 1 : -1; - } - for (var i = a.length - 1; i >= 0; i--) { - if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1; - } - return 0; - } - - BigInteger.prototype.compareAbs = function (v) { - var n = parseValue(v), - a = this.value, - b = n.value; - if (n.isSmall) return 1; - return compareAbs(a, b); - }; - SmallInteger.prototype.compareAbs = function (v) { - var n = parseValue(v), - a = Math.abs(this.value), - b = n.value; - if (n.isSmall) { - b = Math.abs(b); - return a === b ? 0 : a > b ? 1 : -1; - } - return -1; - }; - NativeBigInt.prototype.compareAbs = function (v) { - var a = this.value; - var b = parseValue(v).value; - a = a >= 0 ? a : -a; - b = b >= 0 ? b : -b; - return a === b ? 0 : a > b ? 1 : -1; - }; - - BigInteger.prototype.compare = function (v) { - // See discussion about comparison with Infinity: - // https://github.com/peterolson/BigInteger.js/issues/61 - if (v === Infinity) { - return -1; - } - if (v === -Infinity) { - return 1; - } - - var n = parseValue(v), - a = this.value, - b = n.value; - if (this.sign !== n.sign) { - return n.sign ? 1 : -1; - } - if (n.isSmall) { - return this.sign ? -1 : 1; - } - return compareAbs(a, b) * (this.sign ? -1 : 1); - }; - BigInteger.prototype.compareTo = BigInteger.prototype.compare; - - SmallInteger.prototype.compare = function (v) { - if (v === Infinity) { - return -1; - } - if (v === -Infinity) { - return 1; - } - - var n = parseValue(v), - a = this.value, - b = n.value; - if (n.isSmall) { - return a == b ? 0 : a > b ? 1 : -1; - } - if (a < 0 !== n.sign) { - return a < 0 ? -1 : 1; - } - return a < 0 ? 1 : -1; - }; - SmallInteger.prototype.compareTo = SmallInteger.prototype.compare; - - NativeBigInt.prototype.compare = function (v) { - if (v === Infinity) { - return -1; - } - if (v === -Infinity) { - return 1; - } - var a = this.value; - var b = parseValue(v).value; - return a === b ? 0 : a > b ? 1 : -1; - }; - NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare; - - BigInteger.prototype.equals = function (v) { - return this.compare(v) === 0; - }; - NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals; - - BigInteger.prototype.notEquals = function (v) { - return this.compare(v) !== 0; - }; - NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals; - - BigInteger.prototype.greater = function (v) { - return this.compare(v) > 0; - }; - NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater; - - BigInteger.prototype.lesser = function (v) { - return this.compare(v) < 0; - }; - NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser; - - BigInteger.prototype.greaterOrEquals = function (v) { - return this.compare(v) >= 0; - }; - NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals; - - BigInteger.prototype.lesserOrEquals = function (v) { - return this.compare(v) <= 0; - }; - NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals; - - BigInteger.prototype.isEven = function () { - return (this.value[0] & 1) === 0; - }; - SmallInteger.prototype.isEven = function () { - return (this.value & 1) === 0; - }; - NativeBigInt.prototype.isEven = function () { - return (this.value & BigInt(1)) === BigInt(0); - }; - - BigInteger.prototype.isOdd = function () { - return (this.value[0] & 1) === 1; - }; - SmallInteger.prototype.isOdd = function () { - return (this.value & 1) === 1; - }; - NativeBigInt.prototype.isOdd = function () { - return (this.value & BigInt(1)) === BigInt(1); - }; - - BigInteger.prototype.isPositive = function () { - return !this.sign; - }; - SmallInteger.prototype.isPositive = function () { - return this.value > 0; - }; - NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive; - - BigInteger.prototype.isNegative = function () { - return this.sign; - }; - SmallInteger.prototype.isNegative = function () { - return this.value < 0; - }; - NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative; - - BigInteger.prototype.isUnit = function () { - return false; - }; - SmallInteger.prototype.isUnit = function () { - return Math.abs(this.value) === 1; - }; - NativeBigInt.prototype.isUnit = function () { - return this.abs().value === BigInt(1); - }; - - BigInteger.prototype.isZero = function () { - return false; - }; - SmallInteger.prototype.isZero = function () { - return this.value === 0; - }; - NativeBigInt.prototype.isZero = function () { - return this.value === BigInt(0); - }; - - BigInteger.prototype.isDivisibleBy = function (v) { - var n = parseValue(v); - if (n.isZero()) return false; - if (n.isUnit()) return true; - if (n.compareAbs(2) === 0) return this.isEven(); - return this.mod(n).isZero(); - }; - NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy; - - function isBasicPrime(v) { - var n = v.abs(); - if (n.isUnit()) return false; - if (n.equals(2) || n.equals(3) || n.equals(5)) return true; - if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false; - if (n.lesser(49)) return true; - // we don't know if it's prime: let the other functions figure it out - } - - function millerRabinTest(n, a) { - var nPrev = n.prev(), - b = nPrev, - r = 0, - d, i, x; - while (b.isEven()) b = b.divide(2), r++; - next: for (i = 0; i < a.length; i++) { - if (n.lesser(a[i])) continue; - x = bigInt(a[i]).modPow(b, n); - if (x.isUnit() || x.equals(nPrev)) continue; - for (d = r - 1; d != 0; d--) { - x = x.square().mod(n); - if (x.isUnit()) return false; - if (x.equals(nPrev)) continue next; - } - return false; - } - return true; - } - - // Set "strict" to true to force GRH-supported lower bound of 2*log(N)^2 - BigInteger.prototype.isPrime = function (strict) { - var isPrime = isBasicPrime(this); - if (isPrime !== undefined$1) return isPrime; - var n = this.abs(); - var bits = n.bitLength(); - if (bits <= 64) - return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]); - var logN = Math.log(2) * bits.toJSNumber(); - var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN); - for (var a = [], i = 0; i < t; i++) { - a.push(bigInt(i + 2)); - } - return millerRabinTest(n, a); - }; - NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime; - - BigInteger.prototype.isProbablePrime = function (iterations, rng) { - var isPrime = isBasicPrime(this); - if (isPrime !== undefined$1) return isPrime; - var n = this.abs(); - var t = iterations === undefined$1 ? 5 : iterations; - for (var a = [], i = 0; i < t; i++) { - a.push(bigInt.randBetween(2, n.minus(2), rng)); - } - return millerRabinTest(n, a); - }; - NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime; - - BigInteger.prototype.modInv = function (n) { - var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR; - while (!newR.isZero()) { - q = r.divide(newR); - lastT = t; - lastR = r; - t = newT; - r = newR; - newT = lastT.subtract(q.multiply(newT)); - newR = lastR.subtract(q.multiply(newR)); - } - if (!r.isUnit()) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime"); - if (t.compare(0) === -1) { - t = t.add(n); - } - if (this.isNegative()) { - return t.negate(); - } - return t; - }; - - NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv; - - BigInteger.prototype.next = function () { - var value = this.value; - if (this.sign) { - return subtractSmall(value, 1, this.sign); - } - return new BigInteger(addSmall(value, 1), this.sign); - }; - SmallInteger.prototype.next = function () { - var value = this.value; - if (value + 1 < MAX_INT) return new SmallInteger(value + 1); - return new BigInteger(MAX_INT_ARR, false); - }; - NativeBigInt.prototype.next = function () { - return new NativeBigInt(this.value + BigInt(1)); - }; - - BigInteger.prototype.prev = function () { - var value = this.value; - if (this.sign) { - return new BigInteger(addSmall(value, 1), true); - } - return subtractSmall(value, 1, this.sign); - }; - SmallInteger.prototype.prev = function () { - var value = this.value; - if (value - 1 > -MAX_INT) return new SmallInteger(value - 1); - return new BigInteger(MAX_INT_ARR, true); - }; - NativeBigInt.prototype.prev = function () { - return new NativeBigInt(this.value - BigInt(1)); - }; - - var powersOfTwo = [1]; - while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]); - var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1]; - - function shift_isSmall(n) { - return Math.abs(n) <= BASE; - } - - BigInteger.prototype.shiftLeft = function (v) { - var n = parseValue(v).toJSNumber(); - if (!shift_isSmall(n)) { - throw new Error(String(n) + " is too large for shifting."); - } - if (n < 0) return this.shiftRight(-n); - var result = this; - if (result.isZero()) return result; - while (n >= powers2Length) { - result = result.multiply(highestPower2); - n -= powers2Length - 1; - } - return result.multiply(powersOfTwo[n]); - }; - NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft; - - BigInteger.prototype.shiftRight = function (v) { - var remQuo; - var n = parseValue(v).toJSNumber(); - if (!shift_isSmall(n)) { - throw new Error(String(n) + " is too large for shifting."); - } - if (n < 0) return this.shiftLeft(-n); - var result = this; - while (n >= powers2Length) { - if (result.isZero() || (result.isNegative() && result.isUnit())) return result; - remQuo = divModAny(result, highestPower2); - result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; - n -= powers2Length - 1; - } - remQuo = divModAny(result, powersOfTwo[n]); - return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; - }; - NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight; - - function bitwise(x, y, fn) { - y = parseValue(y); - var xSign = x.isNegative(), ySign = y.isNegative(); - var xRem = xSign ? x.not() : x, - yRem = ySign ? y.not() : y; - var xDigit = 0, yDigit = 0; - var xDivMod = null, yDivMod = null; - var result = []; - while (!xRem.isZero() || !yRem.isZero()) { - xDivMod = divModAny(xRem, highestPower2); - xDigit = xDivMod[1].toJSNumber(); - if (xSign) { - xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers - } - - yDivMod = divModAny(yRem, highestPower2); - yDigit = yDivMod[1].toJSNumber(); - if (ySign) { - yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers - } - - xRem = xDivMod[0]; - yRem = yDivMod[0]; - result.push(fn(xDigit, yDigit)); - } - var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0); - for (var i = result.length - 1; i >= 0; i -= 1) { - sum = sum.multiply(highestPower2).add(bigInt(result[i])); - } - return sum; - } - - BigInteger.prototype.not = function () { - return this.negate().prev(); - }; - NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not; - - BigInteger.prototype.and = function (n) { - return bitwise(this, n, function (a, b) { return a & b; }); - }; - NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and; - - BigInteger.prototype.or = function (n) { - return bitwise(this, n, function (a, b) { return a | b; }); - }; - NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or; - - BigInteger.prototype.xor = function (n) { - return bitwise(this, n, function (a, b) { return a ^ b; }); - }; - NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor; - - var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I; - function roughLOB(n) { // get lowestOneBit (rough) - // SmallInteger: return Min(lowestOneBit(n), 1 << 30) - // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7] - var v = n.value, - x = typeof v === "number" ? v | LOBMASK_I : - typeof v === "bigint" ? v | BigInt(LOBMASK_I) : - v[0] + v[1] * BASE | LOBMASK_BI; - return x & -x; - } - - function integerLogarithm(value, base) { - if (base.compareTo(value) <= 0) { - var tmp = integerLogarithm(value, base.square(base)); - var p = tmp.p; - var e = tmp.e; - var t = p.multiply(base); - return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 }; - } - return { p: bigInt(1), e: 0 }; - } - - BigInteger.prototype.bitLength = function () { - var n = this; - if (n.compareTo(bigInt(0)) < 0) { - n = n.negate().subtract(bigInt(1)); - } - if (n.compareTo(bigInt(0)) === 0) { - return bigInt(0); - } - return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1)); - }; - NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength; - - function max(a, b) { - a = parseValue(a); - b = parseValue(b); - return a.greater(b) ? a : b; - } - function min(a, b) { - a = parseValue(a); - b = parseValue(b); - return a.lesser(b) ? a : b; - } - function gcd(a, b) { - a = parseValue(a).abs(); - b = parseValue(b).abs(); - if (a.equals(b)) return a; - if (a.isZero()) return b; - if (b.isZero()) return a; - var c = Integer[1], d, t; - while (a.isEven() && b.isEven()) { - d = min(roughLOB(a), roughLOB(b)); - a = a.divide(d); - b = b.divide(d); - c = c.multiply(d); - } - while (a.isEven()) { - a = a.divide(roughLOB(a)); - } - do { - while (b.isEven()) { - b = b.divide(roughLOB(b)); - } - if (a.greater(b)) { - t = b; b = a; a = t; - } - b = b.subtract(a); - } while (!b.isZero()); - return c.isUnit() ? a : a.multiply(c); - } - function lcm(a, b) { - a = parseValue(a).abs(); - b = parseValue(b).abs(); - return a.divide(gcd(a, b)).multiply(b); - } - function randBetween(a, b, rng) { - a = parseValue(a); - b = parseValue(b); - var usedRNG = rng || Math.random; - var low = min(a, b), high = max(a, b); - var range = high.subtract(low).add(1); - if (range.isSmall) return low.add(Math.floor(usedRNG() * range)); - var digits = toBase(range, BASE).value; - var result = [], restricted = true; - for (var i = 0; i < digits.length; i++) { - var top = restricted ? digits[i] + (i + 1 < digits.length ? digits[i + 1] / BASE : 0) : BASE; - var digit = truncate(usedRNG() * top); - result.push(digit); - if (digit < digits[i]) restricted = false; - } - return low.add(Integer.fromArray(result, BASE, false)); - } - - var parseBase = function (text, base, alphabet, caseSensitive) { - alphabet = alphabet || DEFAULT_ALPHABET; - text = String(text); - if (!caseSensitive) { - text = text.toLowerCase(); - alphabet = alphabet.toLowerCase(); - } - var length = text.length; - var i; - var absBase = Math.abs(base); - var alphabetValues = {}; - for (i = 0; i < alphabet.length; i++) { - alphabetValues[alphabet[i]] = i; - } - for (i = 0; i < length; i++) { - var c = text[i]; - if (c === "-") continue; - if (c in alphabetValues) { - if (alphabetValues[c] >= absBase) { - if (c === "1" && absBase === 1) continue; - throw new Error(c + " is not a valid digit in base " + base + "."); - } - } - } - base = parseValue(base); - var digits = []; - var isNegative = text[0] === "-"; - for (i = isNegative ? 1 : 0; i < text.length; i++) { - var c = text[i]; - if (c in alphabetValues) digits.push(parseValue(alphabetValues[c])); - else if (c === "<") { - var start = i; - do { i++; } while (text[i] !== ">" && i < text.length); - digits.push(parseValue(text.slice(start + 1, i))); - } - else throw new Error(c + " is not a valid character"); - } - return parseBaseFromArray(digits, base, isNegative); - }; - - function parseBaseFromArray(digits, base, isNegative) { - var val = Integer[0], pow = Integer[1], i; - for (i = digits.length - 1; i >= 0; i--) { - val = val.add(digits[i].times(pow)); - pow = pow.times(base); - } - return isNegative ? val.negate() : val; - } - - function stringify(digit, alphabet) { - alphabet = alphabet || DEFAULT_ALPHABET; - if (digit < alphabet.length) { - return alphabet[digit]; - } - return "<" + digit + ">"; - } - - function toBase(n, base) { - base = bigInt(base); - if (base.isZero()) { - if (n.isZero()) return { value: [0], isNegative: false }; - throw new Error("Cannot convert nonzero numbers to base 0."); - } - if (base.equals(-1)) { - if (n.isZero()) return { value: [0], isNegative: false }; - if (n.isNegative()) - return { - value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber())) - .map(Array.prototype.valueOf, [1, 0]) - ), - isNegative: false - }; - - var arr = Array.apply(null, Array(n.toJSNumber() - 1)) - .map(Array.prototype.valueOf, [0, 1]); - arr.unshift([1]); - return { - value: [].concat.apply([], arr), - isNegative: false - }; - } - - var neg = false; - if (n.isNegative() && base.isPositive()) { - neg = true; - n = n.abs(); - } - if (base.isUnit()) { - if (n.isZero()) return { value: [0], isNegative: false }; - - return { - value: Array.apply(null, Array(n.toJSNumber())) - .map(Number.prototype.valueOf, 1), - isNegative: neg - }; - } - var out = []; - var left = n, divmod; - while (left.isNegative() || left.compareAbs(base) >= 0) { - divmod = left.divmod(base); - left = divmod.quotient; - var digit = divmod.remainder; - if (digit.isNegative()) { - digit = base.minus(digit).abs(); - left = left.next(); - } - out.push(digit.toJSNumber()); - } - out.push(left.toJSNumber()); - return { value: out.reverse(), isNegative: neg }; - } - - function toBaseString(n, base, alphabet) { - var arr = toBase(n, base); - return (arr.isNegative ? "-" : "") + arr.value.map(function (x) { - return stringify(x, alphabet); - }).join(''); - } - - BigInteger.prototype.toArray = function (radix) { - return toBase(this, radix); - }; - - SmallInteger.prototype.toArray = function (radix) { - return toBase(this, radix); - }; - - NativeBigInt.prototype.toArray = function (radix) { - return toBase(this, radix); - }; - - BigInteger.prototype.toString = function (radix, alphabet) { - if (radix === undefined$1) radix = 10; - if (radix !== 10 || alphabet) return toBaseString(this, radix, alphabet); - var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit; - while (--l >= 0) { - digit = String(v[l]); - str += zeros.slice(digit.length) + digit; - } - var sign = this.sign ? "-" : ""; - return sign + str; - }; - - SmallInteger.prototype.toString = function (radix, alphabet) { - if (radix === undefined$1) radix = 10; - if (radix != 10 || alphabet) return toBaseString(this, radix, alphabet); - return String(this.value); - }; - - NativeBigInt.prototype.toString = SmallInteger.prototype.toString; - - NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); }; - - BigInteger.prototype.valueOf = function () { - return parseInt(this.toString(), 10); - }; - BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf; - - SmallInteger.prototype.valueOf = function () { - return this.value; - }; - SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf; - NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () { - return parseInt(this.toString(), 10); - }; - - function parseStringValue(v) { - if (isPrecise(+v)) { - var x = +v; - if (x === truncate(x)) - return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x); - throw new Error("Invalid integer: " + v); - } - var sign = v[0] === "-"; - if (sign) v = v.slice(1); - var split = v.split(/e/i); - if (split.length > 2) throw new Error("Invalid integer: " + split.join("e")); - if (split.length === 2) { - var exp = split[1]; - if (exp[0] === "+") exp = exp.slice(1); - exp = +exp; - if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent."); - var text = split[0]; - var decimalPlace = text.indexOf("."); - if (decimalPlace >= 0) { - exp -= text.length - decimalPlace - 1; - text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1); - } - if (exp < 0) throw new Error("Cannot include negative exponent part for integers"); - text += (new Array(exp + 1)).join("0"); - v = text; - } - var isValid = /^([0-9][0-9]*)$/.test(v); - if (!isValid) throw new Error("Invalid integer: " + v); - if (supportsNativeBigInt) { - return new NativeBigInt(BigInt(sign ? "-" + v : v)); - } - var r = [], max = v.length, l = LOG_BASE, min = max - l; - while (max > 0) { - r.push(+v.slice(min, max)); - min -= l; - if (min < 0) min = 0; - max -= l; - } - trim(r); - return new BigInteger(r, sign); - } - - function parseNumberValue(v) { - if (supportsNativeBigInt) { - return new NativeBigInt(BigInt(v)); - } - if (isPrecise(v)) { - if (v !== truncate(v)) throw new Error(v + " is not an integer."); - return new SmallInteger(v); - } - return parseStringValue(v.toString()); - } - - function parseValue(v) { - if (typeof v === "number") { - return parseNumberValue(v); - } - if (typeof v === "string") { - return parseStringValue(v); - } - if (typeof v === "bigint") { - return new NativeBigInt(v); - } - return v; - } - // Pre-define numbers in range [-999,999] - for (var i = 0; i < 1000; i++) { - Integer[i] = parseValue(i); - if (i > 0) Integer[-i] = parseValue(-i); - } - // Backwards compatibility - Integer.one = Integer[1]; - Integer.zero = Integer[0]; - Integer.minusOne = Integer[-1]; - Integer.max = max; - Integer.min = min; - Integer.gcd = gcd; - Integer.lcm = lcm; - Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; }; - Integer.randBetween = randBetween; - - Integer.fromArray = function (digits, base, isNegative) { - return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative); - }; - - return Integer; - })(); - - // Node.js check - if (module.hasOwnProperty("exports")) { - module.exports = bigInt; - } -} (BigInteger)); - -var BigIntegerExports = BigInteger.exports; -var bigInt$8 = /*@__PURE__*/getDefaultExportFromCjs(BigIntegerExports); - -function fromString$1(s, radix) { - if (typeof s == "string") { - if (s.slice(0,2) == "0x") { - return bigInt$8(s.slice(2), 16); - } else { - return bigInt$8(s,radix); - } - } else { - return bigInt$8(s, radix); - } -} - -const e$1 = fromString$1; - -function fromArray$1(a, radix) { - return bigInt$8.fromArray(a, radix); -} - -function bitLength$1(a) { - return bigInt$8(a).bitLength(); -} - -function isNegative$1(a) { - return bigInt$8(a).isNegative(); -} - -function isZero$1(a) { - return bigInt$8(a).isZero(); -} - -function shiftLeft$1(a, n) { - return bigInt$8(a).shiftLeft(n); -} - -function shiftRight$1(a, n) { - return bigInt$8(a).shiftRight(n); -} - -const shl$1 = shiftLeft$1; -const shr$1 = shiftRight$1; - -function isOdd$1(a) { - return bigInt$8(a).isOdd(); -} - - -function naf$1(n) { - let E = bigInt$8(n); - const res = []; - while (E.gt(bigInt$8.zero)) { - if (E.isOdd()) { - const z = 2 - E.mod(4).toJSNumber(); - res.push( z ); - E = E.minus(z); - } else { - res.push( 0 ); - } - E = E.shiftRight(1); - } - return res; -} - -function bits$1(n) { - let E = bigInt$8(n); - const res = []; - while (E.gt(bigInt$8.zero)) { - if (E.isOdd()) { - res.push(1); - } else { - res.push( 0 ); - } - E = E.shiftRight(1); - } - return res; -} - -function toNumber$2(s) { - if (!s.lt(bigInt$8("9007199254740992", 10))) { - throw new Error("Number too big"); - } - return s.toJSNumber(); -} - -function toArray$1(s, radix) { - return bigInt$8(s).toArray(radix); -} - -function add$1(a, b) { - return bigInt$8(a).add(bigInt$8(b)); -} - -function sub$1(a, b) { - return bigInt$8(a).minus(bigInt$8(b)); -} - -function neg$1(a) { - return bigInt$8.zero.minus(bigInt$8(a)); -} - -function mul$1(a, b) { - return bigInt$8(a).times(bigInt$8(b)); -} - -function square$1(a) { - return bigInt$8(a).square(); -} - -function pow$1(a, b) { - return bigInt$8(a).pow(bigInt$8(b)); -} - -function exp$1(a, b) { - return bigInt$8(a).pow(bigInt$8(b)); -} - -function abs$1(a) { - return bigInt$8(a).abs(); -} - -function div$1(a, b) { - return bigInt$8(a).divide(bigInt$8(b)); -} - -function mod$1(a, b) { - return bigInt$8(a).mod(bigInt$8(b)); -} - -function eq$1(a, b) { - return bigInt$8(a).eq(bigInt$8(b)); -} - -function neq$1(a, b) { - return bigInt$8(a).neq(bigInt$8(b)); -} - -function lt$1(a, b) { - return bigInt$8(a).lt(bigInt$8(b)); -} - -function gt$1(a, b) { - return bigInt$8(a).gt(bigInt$8(b)); -} - -function leq$1(a, b) { - return bigInt$8(a).leq(bigInt$8(b)); -} - -function geq$1(a, b) { - return bigInt$8(a).geq(bigInt$8(b)); -} - -function band$1(a, b) { - return bigInt$8(a).and(bigInt$8(b)); -} - -function bor$1(a, b) { - return bigInt$8(a).or(bigInt$8(b)); -} - -function bxor$1(a, b) { - return bigInt$8(a).xor(bigInt$8(b)); -} - -function land$1(a, b) { - return (!bigInt$8(a).isZero()) && (!bigInt$8(b).isZero()); -} - -function lor$1(a, b) { - return (!bigInt$8(a).isZero()) || (!bigInt$8(b).isZero()); -} - -function lnot$1(a) { - return bigInt$8(a).isZero(); -} - -var Scalar_bigint = /*#__PURE__*/Object.freeze({ - __proto__: null, - abs: abs$1, - add: add$1, - band: band$1, - bitLength: bitLength$1, - bits: bits$1, - bor: bor$1, - bxor: bxor$1, - div: div$1, - e: e$1, - eq: eq$1, - exp: exp$1, - fromArray: fromArray$1, - fromString: fromString$1, - geq: geq$1, - gt: gt$1, - isNegative: isNegative$1, - isOdd: isOdd$1, - isZero: isZero$1, - land: land$1, - leq: leq$1, - lnot: lnot$1, - lor: lor$1, - lt: lt$1, - mod: mod$1, - mul: mul$1, - naf: naf$1, - neg: neg$1, - neq: neq$1, - pow: pow$1, - shiftLeft: shiftLeft$1, - shiftRight: shiftRight$1, - shl: shl$1, - shr: shr$1, - square: square$1, - sub: sub$1, - toArray: toArray$1, - toNumber: toNumber$2 -}); - -const supportsNativeBigInt$1 = typeof BigInt === "function"; - -let Scalar$1 = {}; -if (supportsNativeBigInt$1) { - Object.assign(Scalar$1, Scalar_native); -} else { - Object.assign(Scalar$1, Scalar_bigint); -} - - -// Returns a buffer with Little Endian Representation -Scalar$1.toRprLE = function rprBE(buff, o, e, n8) { - const s = "0000000" + e.toString(16); - const v = new Uint32Array(buff.buffer, o, n8/4); - const l = (((s.length-7)*4 - 1) >> 5)+1; // Number of 32bit words; - for (let i=0; i> 5)+1; // Number of 32bit words; - for (let i=0; i a[a.length-i-1] = ch.toString(16).padStart(8,"0") ); - return Scalar$1.fromString(a.join(""), 16); -}; - -// Pases a buffer with Big Endian Representation -Scalar$1.fromRprBE = function rprLEM(buff, o, n8) { - n8 = n8 || buff.byteLength; - o = o || 0; - const v = new DataView(buff.buffer, buff.byteOffset + o, n8); - const a = new Array(n8/4); - for (let i=0; i>> 0; - st[d] = (st[d] ^ st[a]) >>> 0; - st[d] = ((st[d] << 16) | ((st[d]>>>16) & 0xFFFF)) >>> 0; - - st[c] = (st[c] + st[d]) >>> 0; - st[b] = (st[b] ^ st[c]) >>> 0; - st[b] = ((st[b] << 12) | ((st[b]>>>20) & 0xFFF)) >>> 0; - - st[a] = (st[a] + st[b]) >>> 0; - st[d] = (st[d] ^ st[a]) >>> 0; - st[d] = ((st[d] << 8) | ((st[d]>>>24) & 0xFF)) >>> 0; - - st[c] = (st[c] + st[d]) >>> 0; - st[b] = (st[b] ^ st[c]) >>> 0; - st[b] = ((st[b] << 7) | ((st[b]>>>25) & 0x7F)) >>> 0; -} - -function doubleRound(st) { - quarterRound(st, 0, 4, 8,12); - quarterRound(st, 1, 5, 9,13); - quarterRound(st, 2, 6,10,14); - quarterRound(st, 3, 7,11,15); - - quarterRound(st, 0, 5,10,15); - quarterRound(st, 1, 6,11,12); - quarterRound(st, 2, 7, 8,13); - quarterRound(st, 3, 4, 9,14); -} - -class ChaCha { - - constructor(seed) { - seed = seed || [0,0,0,0,0,0,0,0]; - this.state = [ - 0x61707865, - 0x3320646E, - 0x79622D32, - 0x6B206574, - seed[0], - seed[1], - seed[2], - seed[3], - seed[4], - seed[5], - seed[6], - seed[7], - 0, - 0, - 0, - 0 - ]; - this.idx = 16; - this.buff = new Array(16); - } - - nextU32() { - if (this.idx == 16) this.update(); - return this.buff[this.idx++]; - } - - nextU64() { - return add(mul(this.nextU32(), 0x100000000), this.nextU32()); - } - - nextBool() { - return (this.nextU32() & 1) == 1; - } - - update() { - // Copy the state - for (let i=0; i<16; i++) this.buff[i] = this.state[i]; - - // Apply the rounds - for (let i=0; i<10; i++) doubleRound(this.buff); - - // Add to the initial - for (let i=0; i<16; i++) this.buff[i] = (this.buff[i] + this.state[i]) >>> 0; - - this.idx = 0; - - this.state[12] = (this.state[12] + 1) >>> 0; - if (this.state[12] != 0) return; - this.state[13] = (this.state[13] + 1) >>> 0; - if (this.state[13] != 0) return; - this.state[14] = (this.state[14] + 1) >>> 0; - if (this.state[14] != 0) return; - this.state[15] = (this.state[15] + 1) >>> 0; - } -} - -function getRandomBytes(n) { - let array = new Uint8Array(n); - if (process.browser) { // Browser - if (typeof globalThis.crypto !== "undefined") { // Supported - globalThis.crypto.getRandomValues(array); - } else { // fallback - for (let i=0; i>>0; - } - } - } - else { // NodeJS - crypto.randomFillSync(array); - } - return array; -} - -function getRandomSeed() { - const arr = getRandomBytes(32); - const arrV = new Uint32Array(arr.buffer); - const seed = []; - for (let i=0; i<8; i++) { - seed.push(arrV[i]); - } - return seed; -} - -let threadRng = null; - -function getThreadRng() { - if (threadRng) return threadRng; - threadRng = new ChaCha(getRandomSeed()); - return threadRng; -} - -var utils$b = {}; - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -const bigInt$7 = BigIntegerExports; - -utils$b.bigInt2BytesLE = function bigInt2BytesLE(_a, len) { - const b = Array(len); - let v = bigInt$7(_a); - for (let i=0; i. -*/ - -const utils$a = utils$b; - -var build_int = function buildInt(module, n64, _prefix) { - - const prefix = _prefix || "int"; - if (module.modules[prefix]) return prefix; // already builded - module.modules[prefix] = {}; - - const n32 = n64*2; - const n8 = n64*8; - - module.alloc(n8, utils$a.bigInt2BytesLE(1, n8)); - - function buildCopy() { - const f = module.addFunction(prefix+"_copy"); - f.addParam("px", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - for (let i=0; i>1) )&&(i>1, k>>1) - ) - ) - ); - - f.addCode( - c.setLocal(c1, - c.i64_add( - c.getLocal(c1), - c.i64_shr_u( - c.getLocal(c0), - c.i64_const(32) - ) - ) - ) - ); - } - - // Add the old carry - - if (k>0) { - f.addCode( - c.setLocal(c0, - c.i64_add( - c.i64_and( - c.getLocal(c0), - c.i64_const(0xFFFFFFFF) - ), - c.i64_and( - c.getLocal(c0_old), - c.i64_const(0xFFFFFFFF) - ), - ) - ) - ); - - f.addCode( - c.setLocal(c1, - c.i64_add( - c.i64_add( - c.getLocal(c1), - c.i64_shr_u( - c.getLocal(c0), - c.i64_const(32) - ) - ), - c.getLocal(c1_old) - ) - ) - ); - } - - f.addCode( - c.i64_store32( - c.getLocal("r"), - k*4, - c.getLocal(c0) - ) - ); - - f.addCode( - c.setLocal( - c0_old, - c.getLocal(c1) - ), - c.setLocal( - c1_old, - c.i64_shr_u( - c.getLocal(c0_old), - c.i64_const(32) - ) - ) - ); - - } - f.addCode( - c.i64_store32( - c.getLocal("r"), - n32*4*2-4, - c.getLocal(c0_old) - ) - ); - - } - - - function buildSquareOld() { - const f = module.addFunction(prefix+"_squareOld"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); - } - - function _buildMul1() { - const f = module.addFunction(prefix+"__mul1"); - f.addParam("px", "i32"); - f.addParam("y", "i64"); - f.addParam("pr", "i32"); - f.addLocal("c", "i64"); - - const c = f.getCodeBuilder(); - - f.addCode(c.setLocal( - "c", - c.i64_mul( - c.i64_load32_u(c.getLocal("px"), 0, 0), - c.getLocal("y") - ) - )); - - f.addCode(c.i64_store32( - c.getLocal("pr"), - 0, - 0, - c.getLocal("c"), - )); - - for (let i=1; i3)&&(Y[eY]==0) ey--; - f.addCode(c.block(c.loop( - c.br_if( - 1, - c.i32_or( - c.i32_load8_u( - c.i32_add(Y , c.getLocal("eY")), - 0, - 0 - ), - c.i32_eq( - c.getLocal("eY"), - c.i32_const(3) - ) - ) - ), - c.setLocal("eY", c.i32_sub(c.getLocal("eY"), c.i32_const(1))), - c.br(0) - ))); - - f.addCode( - c.setLocal( - "sy", - c.i64_add( - c.i64_load32_u( - c.i32_sub( - c.i32_add( Y, c.getLocal("eY")), - c.i32_const(3) - ), - 0, - 0 - ), - c.i64_const(1) - ) - ) - ); - - // Force a divide by 0 if quotien is 0 - f.addCode( - c.if( - c.i64_eq( - c.getLocal("sy"), - c.i64_const(1) - ), - c.drop(c.i64_div_u(c.i64_const(0), c.i64_const(0))) - ) - ); - - f.addCode(c.block(c.loop( - - // while (eX>7)&&(Y[eX]==0) ex--; - c.block(c.loop( - c.br_if( - 1, - c.i32_or( - c.i32_load8_u( - c.i32_add(R , c.getLocal("eX")), - 0, - 0 - ), - c.i32_eq( - c.getLocal("eX"), - c.i32_const(7) - ) - ) - ), - c.setLocal("eX", c.i32_sub(c.getLocal("eX"), c.i32_const(1))), - c.br(0) - )), - - c.setLocal( - "sx", - c.i64_load( - c.i32_sub( - c.i32_add( R, c.getLocal("eX")), - c.i32_const(7) - ), - 0, - 0 - ) - ), - - c.setLocal( - "sx", - c.i64_div_u( - c.getLocal("sx"), - c.getLocal("sy") - ) - ), - c.setLocal( - "ec", - c.i32_sub( - c.i32_sub( - c.getLocal("eX"), - c.getLocal("eY") - ), - c.i32_const(4) - ) - ), - - // While greater than 32 bits or ec is neg, shr and inc exp - c.block(c.loop( - c.br_if( - 1, - c.i32_and( - c.i64_eqz( - c.i64_and( - c.getLocal("sx"), - c.i64_const("0xFFFFFFFF00000000") - ) - ), - c.i32_ge_s( - c.getLocal("ec"), - c.i32_const(0) - ) - ) - ), - - c.setLocal( - "sx", - c.i64_shr_u( - c.getLocal("sx"), - c.i64_const(8) - ) - ), - - c.setLocal( - "ec", - c.i32_add( - c.getLocal("ec"), - c.i32_const(1) - ) - ), - c.br(0) - )), - - c.if( - c.i64_eqz(c.getLocal("sx")), - [ - ...c.br_if( - 2, - c.i32_eqz(c.call(prefix + "_gte", R, Y)) - ), - ...c.setLocal("sx", c.i64_const(1)), - ...c.setLocal("ec", c.i32_const(0)) - ] - ), - - c.call(prefix + "__mul1", Y, c.getLocal("sx"), R2), - c.drop(c.call( - prefix + "_sub", - R, - c.i32_sub(R2, c.getLocal("ec")), - R - )), - c.call( - prefix + "__add1", - c.i32_add(C, c.getLocal("ec")), - c.getLocal("sx") - ), - c.br(0) - ))); - } - - function buildInverseMod() { - - const f = module.addFunction(prefix+"_inverseMod"); - f.addParam("px", "i32"); - f.addParam("pm", "i32"); - f.addParam("pr", "i32"); - f.addLocal("t", "i32"); - f.addLocal("newt", "i32"); - f.addLocal("r", "i32"); - f.addLocal("qq", "i32"); - f.addLocal("qr", "i32"); - f.addLocal("newr", "i32"); - f.addLocal("swp", "i32"); - f.addLocal("x", "i32"); - f.addLocal("signt", "i32"); - f.addLocal("signnewt", "i32"); - f.addLocal("signx", "i32"); - - const c = f.getCodeBuilder(); - - const aux1 = c.i32_const(module.alloc(n8)); - const aux2 = c.i32_const(module.alloc(n8)); - const aux3 = c.i32_const(module.alloc(n8)); - const aux4 = c.i32_const(module.alloc(n8)); - const aux5 = c.i32_const(module.alloc(n8)); - const aux6 = c.i32_const(module.alloc(n8)); - const mulBuff = c.i32_const(module.alloc(n8*2)); - const aux7 = c.i32_const(module.alloc(n8)); - - f.addCode( - c.setLocal("t", aux1), - c.call(prefix + "_zero", aux1), - c.setLocal("signt", c.i32_const(0)), - ); - - f.addCode( - c.setLocal("r", aux2), - c.call(prefix + "_copy", c.getLocal("pm"), aux2) - ); - - f.addCode( - c.setLocal("newt", aux3), - c.call(prefix + "_one", aux3), - c.setLocal("signnewt", c.i32_const(0)), - ); - - f.addCode( - c.setLocal("newr", aux4), - c.call(prefix + "_copy", c.getLocal("px"), aux4) - ); - - - - - f.addCode(c.setLocal("qq", aux5)); - f.addCode(c.setLocal("qr", aux6)); - f.addCode(c.setLocal("x", aux7)); - - f.addCode(c.block(c.loop( - c.br_if( - 1, - c.call(prefix + "_isZero", c.getLocal("newr") ) - ), - c.call(prefix + "_div", c.getLocal("r"), c.getLocal("newr"), c.getLocal("qq"), c.getLocal("qr")), - - c.call(prefix + "_mul", c.getLocal("qq"), c.getLocal("newt"), mulBuff), - - c.if( - c.getLocal("signt"), - c.if( - c.getLocal("signnewt"), - c.if ( - c.call(prefix + "_gte", mulBuff, c.getLocal("t")), - [ - ...c.drop(c.call(prefix + "_sub", mulBuff, c.getLocal("t"), c.getLocal("x"))), - ...c.setLocal("signx", c.i32_const(0)) - ], - [ - ...c.drop(c.call(prefix + "_sub", c.getLocal("t"), mulBuff, c.getLocal("x"))), - ...c.setLocal("signx", c.i32_const(1)) - ], - ), - [ - ...c.drop(c.call(prefix + "_add", mulBuff, c.getLocal("t"), c.getLocal("x"))), - ...c.setLocal("signx", c.i32_const(1)) - ] - ), - c.if( - c.getLocal("signnewt"), - [ - ...c.drop(c.call(prefix + "_add", mulBuff, c.getLocal("t"), c.getLocal("x"))), - ...c.setLocal("signx", c.i32_const(0)) - ], - c.if ( - c.call(prefix + "_gte", c.getLocal("t"), mulBuff), - [ - ...c.drop(c.call(prefix + "_sub", c.getLocal("t"), mulBuff, c.getLocal("x"))), - ...c.setLocal("signx", c.i32_const(0)) - ], - [ - ...c.drop(c.call(prefix + "_sub", mulBuff, c.getLocal("t"), c.getLocal("x"))), - ...c.setLocal("signx", c.i32_const(1)) - ] - ) - ) - ), - - c.setLocal("swp", c.getLocal("t")), - c.setLocal("t", c.getLocal("newt")), - c.setLocal("newt", c.getLocal("x")), - c.setLocal("x", c.getLocal("swp")), - - c.setLocal("signt", c.getLocal("signnewt")), - c.setLocal("signnewt", c.getLocal("signx")), - - c.setLocal("swp", c.getLocal("r")), - c.setLocal("r", c.getLocal("newr")), - c.setLocal("newr", c.getLocal("qr")), - c.setLocal("qr", c.getLocal("swp")), - - c.br(0) - ))); - - f.addCode(c.if( - c.getLocal("signt"), - c.drop(c.call(prefix + "_sub", c.getLocal("pm"), c.getLocal("t"), c.getLocal("pr"))), - c.call(prefix + "_copy", c.getLocal("t"), c.getLocal("pr")) - )); - } - - - buildCopy(); - buildZero(); - buildIsZero(); - buildOne(); - buildEq(); - buildGte(); - buildAdd(); - buildSub(); - buildMul(); - buildSquare(); - buildSquareOld(); - buildDiv(); - buildInverseMod(); - module.exportFunction(prefix+"_copy"); - module.exportFunction(prefix+"_zero"); - module.exportFunction(prefix+"_one"); - module.exportFunction(prefix+"_isZero"); - module.exportFunction(prefix+"_eq"); - module.exportFunction(prefix+"_gte"); - module.exportFunction(prefix+"_add"); - module.exportFunction(prefix+"_sub"); - module.exportFunction(prefix+"_mul"); - module.exportFunction(prefix+"_square"); - module.exportFunction(prefix+"_squareOld"); - module.exportFunction(prefix+"_div"); - module.exportFunction(prefix+"_inverseMod"); - - return prefix; -}; - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -var build_timesscalar = function buildTimesScalar(module, fnName, elementLen, opAB, opAA, opCopy, opInit) { - - const f = module.addFunction(fnName); - f.addParam("base", "i32"); - f.addParam("scalar", "i32"); - f.addParam("scalarLength", "i32"); - f.addParam("r", "i32"); - f.addLocal("i", "i32"); - f.addLocal("b", "i32"); - - const c = f.getCodeBuilder(); - - const aux = c.i32_const(module.alloc(elementLen)); - - f.addCode( - c.if( - c.i32_eqz(c.getLocal("scalarLength")), - [ - ...c.call(opInit, c.getLocal("r")), - ...c.ret([]) - ] - ) - ); - f.addCode(c.call(opCopy, c.getLocal("base"), aux)); - f.addCode(c.call(opInit, c.getLocal("r"))); - f.addCode(c.setLocal("i", c.getLocal("scalarLength"))); - f.addCode(c.block(c.loop( - c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - - c.setLocal( - "b", - c.i32_load8_u( - c.i32_add( - c.getLocal("scalar"), - c.getLocal("i") - ) - ) - ), - ...innerLoop(), - c.br_if(1, c.i32_eqz ( c.getLocal("i") )), - c.br(0) - ))); - - - function innerLoop() { - const code = []; - for (let i=0; i<8; i++) { - code.push( - ...c.call(opAA, c.getLocal("r"), c.getLocal("r")), - ...c.if( - c.i32_ge_u( c.getLocal("b"), c.i32_const(0x80 >> i)), - [ - ...c.setLocal( - "b", - c.i32_sub( - c.getLocal("b"), - c.i32_const(0x80 >> i) - ) - ), - ...c.call(opAB, c.getLocal("r"),aux, c.getLocal("r")) - ] - ) - ); - } - return code; - } - -}; - -var build_batchinverse = buildBatchInverse$3; - -function buildBatchInverse$3(module, prefix) { - - - const n8 = module.modules[prefix].n64*8; - - const f = module.addFunction(prefix+"_batchInverse"); - f.addParam("pIn", "i32"); - f.addParam("inStep", "i32"); - f.addParam("n", "i32"); - f.addParam("pOut", "i32"); - f.addParam("outStep", "i32"); - f.addLocal("itAux", "i32"); - f.addLocal("itIn", "i32"); - f.addLocal("itOut","i32"); - f.addLocal("i","i32"); - - const c = f.getCodeBuilder(); - - const AUX = c.i32_const(module.alloc(n8)); - - - // Alloc Working space for accumulated umltiplications - f.addCode( - c.setLocal("itAux", c.i32_load( c.i32_const(0) )), - c.i32_store( - c.i32_const(0), - c.i32_add( - c.getLocal("itAux"), - c.i32_mul( - c.i32_add( - c.getLocal("n"), - c.i32_const(1) - ), - c.i32_const(n8) - ) - ) - ) - ); - - f.addCode( - - // aux[0] = a; - c.call(prefix+"_one", c.getLocal("itAux")), - // for (i=0;i. -*/ - -const bigInt$6 = BigIntegerExports; -const buildInt = build_int; -const utils$9 = utils$b; -const buildExp$2 = build_timesscalar; -const buildBatchInverse$2 = build_batchinverse; -const buildBatchConvertion$1 = build_batchconvertion; -const buildBatchOp = build_batchop; - -var build_f1m = function buildF1m(module, _q, _prefix, _intPrefix) { - const q = bigInt$6(_q); - const n64 = Math.floor((q.minus(1).bitLength() - 1)/64) +1; - const n32 = n64*2; - const n8 = n64*8; - - const prefix = _prefix || "f1m"; - if (module.modules[prefix]) return prefix; // already builded - - const intPrefix = buildInt(module, n64, _intPrefix); - const pq = module.alloc(n8, utils$9.bigInt2BytesLE(q, n8)); - - module.alloc(utils$9.bigInt2BytesLE(bigInt$6.one.shiftLeft(n64*64).mod(q), n8)); - const pR2 = module.alloc(utils$9.bigInt2BytesLE(bigInt$6.one.shiftLeft(n64*64).square().mod(q), n8)); - const pOne = module.alloc(utils$9.bigInt2BytesLE(bigInt$6.one.shiftLeft(n64*64).mod(q), n8)); - const pZero = module.alloc(utils$9.bigInt2BytesLE(bigInt$6.zero, n8)); - const _minusOne = q.minus(bigInt$6.one); - const _e = _minusOne.shiftRight(1); // e = (p-1)/2 - const pe = module.alloc(n8, utils$9.bigInt2BytesLE(_e, n8)); - - const _ePlusOne = _e.add(bigInt$6.one); // e = (p-1)/2 - const pePlusOne = module.alloc(n8, utils$9.bigInt2BytesLE(_ePlusOne, n8)); - - module.modules[prefix] = { - pq: pq, - pR2: pR2, - n64: n64, - q: q, - pOne: pOne, - pZero: pZero, - pePlusOne: pePlusOne - }; - - function buildOne() { - const f = module.addFunction(prefix+"_one"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode(c.call(intPrefix + "_copy", c.i32_const(pOne), c.getLocal("pr"))); - } - - function buildAdd() { - const f = module.addFunction(prefix+"_add"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.if( - c.call(intPrefix+"_add", c.getLocal("x"), c.getLocal("y"), c.getLocal("r")), - c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), - c.if( - c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), - c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), - ) - ) - ); - } - - function buildSub() { - const f = module.addFunction(prefix+"_sub"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.if( - c.call(intPrefix+"_sub", c.getLocal("x"), c.getLocal("y"), c.getLocal("r")), - c.drop(c.call(intPrefix+"_add", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))) - ) - ); - } - - function buildNeg() { - const f = module.addFunction(prefix+"_neg"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call(prefix + "_sub", c.i32_const(pZero), c.getLocal("x"), c.getLocal("r")) - ); - } - - - function buildIsNegative() { - const f = module.addFunction(prefix+"_isNegative"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const AUX = c.i32_const(module.alloc(n8)); - - f.addCode( - c.call(prefix + "_fromMontgomery", c.getLocal("x"), AUX), - c.call(intPrefix + "_gte", AUX, c.i32_const(pePlusOne) ) - ); - } - - -/* - function buildIsNegative() { - const f = module.addFunction(prefix+"_isNegative"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const AUX = c.i32_const(module.alloc(n8)); - - f.addCode( - c.call(prefix + "_fromMontgomery", c.getLocal("x"), AUX), - c.i32_and( - c.i32_load(AUX), - c.i32_const(1) - ) - ); - } -*/ - - function buildSign() { - const f = module.addFunction(prefix+"_sign"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const AUX = c.i32_const(module.alloc(n8)); - - f.addCode( - c.if ( - c.call(intPrefix + "_isZero", c.getLocal("x")), - c.ret(c.i32_const(0)) - ), - c.call(prefix + "_fromMontgomery", c.getLocal("x"), AUX), - c.if( - c.call(intPrefix + "_gte", AUX, c.i32_const(pePlusOne)), - c.ret(c.i32_const(-1)) - ), - c.ret(c.i32_const(1)) - ); - } - - - function buildMReduct() { - const carries = module.alloc(n32*n32*8); - - const f = module.addFunction(prefix+"_mReduct"); - f.addParam("t", "i32"); - f.addParam("r", "i32"); - f.addLocal("np32", "i64"); - f.addLocal("c", "i64"); - f.addLocal("m", "i64"); - - const c = f.getCodeBuilder(); - - const np32 = bigInt$6("100000000",16).minus( q.modInv(bigInt$6("100000000",16))).toJSNumber(); - - f.addCode(c.setLocal("np32", c.i64_const(np32))); - - for (let i=0; i=n32) { - f.addCode( - c.i64_store32( - c.getLocal("r"), - (k-n32)*4, - c.getLocal(c0) - ) - ); - } - [c0, c1] = [c1, c0]; - f.addCode( - c.setLocal(c1, - c.i64_shr_u( - c.getLocal(c0), - c.i64_const(32) - ) - ) - ); - } - f.addCode( - c.i64_store32( - c.getLocal("r"), - n32*4-4, - c.getLocal(c0) - ) - ); - - f.addCode( - c.if( - c.i32_wrap_i64(c.getLocal(c1)), - c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), - c.if( - c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), - c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), - ) - ) - ); - } - - - function buildSquare() { - - const f = module.addFunction(prefix+"_square"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - f.addLocal("c0", "i64"); - f.addLocal("c1", "i64"); - f.addLocal("c0_old", "i64"); - f.addLocal("c1_old", "i64"); - f.addLocal("np32", "i64"); - - - for (let i=0;i>1) )&&(i>1, k>>1) - ) - ) - ); - - f.addCode( - c.setLocal(c1, - c.i64_add( - c.getLocal(c1), - c.i64_shr_u( - c.getLocal(c0), - c.i64_const(32) - ) - ) - ) - ); - } - - // Add the old carry - - if (k>0) { - f.addCode( - c.setLocal(c0, - c.i64_add( - c.i64_and( - c.getLocal(c0), - c.i64_const(0xFFFFFFFF) - ), - c.i64_and( - c.getLocal(c0_old), - c.i64_const(0xFFFFFFFF) - ), - ) - ) - ); - - f.addCode( - c.setLocal(c1, - c.i64_add( - c.i64_add( - c.getLocal(c1), - c.i64_shr_u( - c.getLocal(c0), - c.i64_const(32) - ) - ), - c.getLocal(c1_old) - ) - ) - ); - } - - - for (let i=Math.max(1, k-n32+1); (i<=k)&&(i=n32) { - f.addCode( - c.i64_store32( - c.getLocal("r"), - (k-n32)*4, - c.getLocal(c0) - ) - ); - } - f.addCode( - c.setLocal( - c0_old, - c.getLocal(c1) - ), - c.setLocal( - c1_old, - c.i64_shr_u( - c.getLocal(c0_old), - c.i64_const(32) - ) - ) - ); - } - f.addCode( - c.i64_store32( - c.getLocal("r"), - n32*4-4, - c.getLocal(c0_old) - ) - ); - - f.addCode( - c.if( - c.i32_wrap_i64(c.getLocal(c1_old)), - c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), - c.if( - c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), - c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), - ) - ) - ); - } - - - function buildSquareOld() { - const f = module.addFunction(prefix+"_squareOld"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); - } - - function buildToMontgomery() { - const f = module.addFunction(prefix+"_toMontgomery"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - f.addCode(c.call(prefix+"_mul", c.getLocal("x"), c.i32_const(pR2), c.getLocal("r"))); - } - - function buildFromMontgomery() { - - const pAux2 = module.alloc(n8*2); - - const f = module.addFunction(prefix+"_fromMontgomery"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - f.addCode(c.call(intPrefix + "_copy", c.getLocal("x"), c.i32_const(pAux2) )); - f.addCode(c.call(intPrefix + "_zero", c.i32_const(pAux2 + n8) )); - f.addCode(c.call(prefix+"_mReduct", c.i32_const(pAux2), c.getLocal("r"))); - } - - function buildInverse() { - - const f = module.addFunction(prefix+ "_inverse"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - f.addCode(c.call(prefix + "_fromMontgomery", c.getLocal("x"), c.getLocal("r"))); - f.addCode(c.call(intPrefix + "_inverseMod", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))); - f.addCode(c.call(prefix + "_toMontgomery", c.getLocal("r"), c.getLocal("r"))); - } - - // Calculate various valuse needed for sqrt - - - let _nqr = bigInt$6(2); - if (q.isPrime()) { - while (!_nqr.modPow(_e, q).equals(_minusOne)) _nqr = _nqr.add(bigInt$6.one); - } - - module.alloc(utils$9.bigInt2BytesLE(_nqr.shiftLeft(n64*64).mod(q), n8)); - - let s2 = 0; - let _t = _minusOne; - - while ((!_t.isOdd())&&(!_t.isZero())) { - s2++; - _t = _t.shiftRight(1); - } - const pt = module.alloc(n8, utils$9.bigInt2BytesLE(_t, n8)); - - const _nqrToT = _nqr.modPow(_t, q); - const pNqrToT = module.alloc(utils$9.bigInt2BytesLE(_nqrToT.shiftLeft(n64*64).mod(q), n8)); - - const _tPlusOneOver2 = _t.add(1).shiftRight(1); - const ptPlusOneOver2 = module.alloc(n8, utils$9.bigInt2BytesLE(_tPlusOneOver2, n8)); - - function buildSqrt() { - - const f = module.addFunction(prefix+ "_sqrt"); - f.addParam("n", "i32"); - f.addParam("r", "i32"); - f.addLocal("m", "i32"); - f.addLocal("i", "i32"); - f.addLocal("j", "i32"); - - const c = f.getCodeBuilder(); - - const ONE = c.i32_const(pOne); - const C = c.i32_const(module.alloc(n8)); - const T = c.i32_const(module.alloc(n8)); - const R = c.i32_const(module.alloc(n8)); - const SQ = c.i32_const(module.alloc(n8)); - const B = c.i32_const(module.alloc(n8)); - - f.addCode( - - // If (n==0) return 0 - c.if( - c.call(prefix + "_isZero", c.getLocal("n")), - c.ret( - c.call(prefix + "_zero", c.getLocal("r")) - ) - ), - - c.setLocal("m", c.i32_const(s2)), - c.call(prefix + "_copy", c.i32_const(pNqrToT), C), - c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(pt), c.i32_const(n8), T), - c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(ptPlusOneOver2), c.i32_const(n8), R), - - c.block(c.loop( - c.br_if(1, c.call(prefix + "_eq", T, ONE)), - - c.call(prefix + "_square", T, SQ), - c.setLocal("i", c.i32_const(1)), - c.block(c.loop( - c.br_if(1, c.call(prefix + "_eq", SQ, ONE)), - c.call(prefix + "_square", SQ, SQ), - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )), - - c.call(prefix + "_copy", C, B), - c.setLocal("j", c.i32_sub(c.i32_sub( c.getLocal("m"), c.getLocal("i")), c.i32_const(1)) ), - c.block(c.loop( - c.br_if(1, c.i32_eqz(c.getLocal("j"))), - c.call(prefix + "_square", B, B), - c.setLocal("j", c.i32_sub(c.getLocal("j"), c.i32_const(1))), - c.br(0) - )), - - c.setLocal("m", c.getLocal("i")), - c.call(prefix + "_square", B, C), - c.call(prefix + "_mul", T, C, T), - c.call(prefix + "_mul", R, B, R), - - c.br(0) - )), - - c.if( - c.call(prefix + "_isNegative", R), - c.call(prefix + "_neg", R, c.getLocal("r")), - c.call(prefix + "_copy", R, c.getLocal("r")), - ) - ); - } - - function buildIsSquare() { - const f = module.addFunction(prefix+"_isSquare"); - f.addParam("n", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const ONE = c.i32_const(pOne); - const AUX = c.i32_const(module.alloc(n8)); - - f.addCode( - c.if( - c.call(prefix + "_isZero", c.getLocal("n")), - c.ret(c.i32_const(1)) - ), - c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(pe), c.i32_const(n8), AUX), - c.call(prefix + "_eq", AUX, ONE) - ); - } - - - function buildLoad() { - const f = module.addFunction(prefix+"_load"); - f.addParam("scalar", "i32"); - f.addParam("scalarLen", "i32"); - f.addParam("r", "i32"); - f.addLocal("p", "i32"); - f.addLocal("l", "i32"); - f.addLocal("i", "i32"); - f.addLocal("j", "i32"); - const c = f.getCodeBuilder(); - - const R = c.i32_const(module.alloc(n8)); - const pAux = module.alloc(n8); - const AUX = c.i32_const(pAux); - - f.addCode( - c.call(intPrefix + "_zero", c.getLocal("r")), - c.setLocal("i", c.i32_const(n8)), - c.setLocal("p", c.getLocal("scalar")), - c.block(c.loop( - c.br_if(1, c.i32_gt_u(c.getLocal("i"), c.getLocal("scalarLen"))), - - c.if( - c.i32_eq(c.getLocal("i"), c.i32_const(n8)), - c.call(prefix + "_one", R), - c.call(prefix + "_mul", R, c.i32_const(pR2), R) - ), - c.call(prefix + "_mul", c.getLocal("p"), R, AUX), - c.call(prefix + "_add", c.getLocal("r"), AUX, c.getLocal("r")), - - c.setLocal("p", c.i32_add(c.getLocal("p"), c.i32_const(n8))), - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(n8))), - c.br(0) - )), - - c.setLocal("l", c.i32_rem_u( c.getLocal("scalarLen"), c.i32_const(n8))), - c.if(c.i32_eqz(c.getLocal("l")), c.ret([])), - c.call(intPrefix + "_zero", AUX), - c.setLocal("j", c.i32_const(0)), - c.block(c.loop( - c.br_if(1, c.i32_eq(c.getLocal("j"), c.getLocal("l"))), - - c.i32_store8( - c.getLocal("j"), - pAux, - c.i32_load8_u(c.getLocal("p")), - ), - c.setLocal("p", c.i32_add(c.getLocal("p"), c.i32_const(1))), - c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), - c.br(0) - )), - - c.if( - c.i32_eq(c.getLocal("i"), c.i32_const(n8)), - c.call(prefix + "_one", R), - c.call(prefix + "_mul", R, c.i32_const(pR2), R) - ), - c.call(prefix + "_mul", AUX, R, AUX), - c.call(prefix + "_add", c.getLocal("r"), AUX, c.getLocal("r")), - ); - } - - function buildTimesScalar() { - const f = module.addFunction(prefix+"_timesScalar"); - f.addParam("x", "i32"); - f.addParam("scalar", "i32"); - f.addParam("scalarLen", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const AUX = c.i32_const(module.alloc(n8)); - - f.addCode( - c.call(prefix + "_load", c.getLocal("scalar"), c.getLocal("scalarLen"), AUX), - c.call(prefix + "_toMontgomery", AUX, AUX), - c.call(prefix + "_mul", c.getLocal("x"), AUX, c.getLocal("r")), - ); - } - - function buildIsOne() { - const f = module.addFunction(prefix+"_isOne"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - f.addCode( - c.ret(c.call(intPrefix + "_eq", c.getLocal("x"), c.i32_const(pOne))) - ); - } - - - module.exportFunction(intPrefix + "_copy", prefix+"_copy"); - module.exportFunction(intPrefix + "_zero", prefix+"_zero"); - module.exportFunction(intPrefix + "_isZero", prefix+"_isZero"); - module.exportFunction(intPrefix + "_eq", prefix+"_eq"); - - buildIsOne(); - buildAdd(); - buildSub(); - buildNeg(); - buildMReduct(); - buildMul(); - buildSquare(); - buildSquareOld(); - buildToMontgomery(); - buildFromMontgomery(); - buildIsNegative(); - buildSign(); - buildInverse(); - buildOne(); - buildLoad(); - buildTimesScalar(); - buildBatchInverse$2(module, prefix); - buildBatchConvertion$1(module, prefix + "_batchToMontgomery", prefix + "_toMontgomery", n8, n8); - buildBatchConvertion$1(module, prefix + "_batchFromMontgomery", prefix + "_fromMontgomery", n8, n8); - buildBatchConvertion$1(module, prefix + "_batchNeg", prefix + "_neg", n8, n8); - buildBatchOp(module, prefix + "_batchAdd", prefix + "_add", n8, n8); - buildBatchOp(module, prefix + "_batchSub", prefix + "_sub", n8, n8); - buildBatchOp(module, prefix + "_batchMul", prefix + "_mul", n8, n8); - - module.exportFunction(prefix + "_add"); - module.exportFunction(prefix + "_sub"); - module.exportFunction(prefix + "_neg"); - module.exportFunction(prefix + "_isNegative"); - module.exportFunction(prefix + "_isOne"); - module.exportFunction(prefix + "_sign"); - module.exportFunction(prefix + "_mReduct"); - module.exportFunction(prefix + "_mul"); - module.exportFunction(prefix + "_square"); - module.exportFunction(prefix + "_squareOld"); - module.exportFunction(prefix + "_fromMontgomery"); - module.exportFunction(prefix + "_toMontgomery"); - module.exportFunction(prefix + "_inverse"); - module.exportFunction(prefix + "_one"); - module.exportFunction(prefix + "_load"); - module.exportFunction(prefix + "_timesScalar"); - buildExp$2( - module, - prefix + "_exp", - n8, - prefix + "_mul", - prefix + "_square", - intPrefix + "_copy", - prefix + "_one", - ); - module.exportFunction(prefix + "_exp"); - module.exportFunction(prefix + "_batchInverse"); - if (q.isPrime()) { - buildSqrt(); - buildIsSquare(); - module.exportFunction(prefix + "_sqrt"); - module.exportFunction(prefix + "_isSquare"); - } - module.exportFunction(prefix + "_batchToMontgomery"); - module.exportFunction(prefix + "_batchFromMontgomery"); - // console.log(module.functionIdxByName); - - return prefix; -}; - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -const bigInt$5 = BigIntegerExports; - -const buildF1m$2 =build_f1m; - -var build_f1 = function buildF1(module, _q, _prefix, _f1mPrefix, _intPrefix) { - - const q = bigInt$5(_q); - const n64 = Math.floor((q.minus(1).bitLength() - 1)/64) +1; - const n8 = n64*8; - - const prefix = _prefix || "f1"; - if (module.modules[prefix]) return prefix; // already builded - module.modules[prefix] = { - n64: n64 - }; - - const intPrefix = _intPrefix || "int"; - const f1mPrefix = buildF1m$2(module, q, _f1mPrefix, intPrefix); - - - const pR2 = module.modules[f1mPrefix].pR2; - const pq = module.modules[f1mPrefix].pq; - const pePlusOne = module.modules[f1mPrefix].pePlusOne; - - function buildMul() { - const pAux1 = module.alloc(n8); - - const f = module.addFunction(prefix+ "_mul"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - f.addCode(c.call(f1mPrefix + "_mul", c.getLocal("x"), c.getLocal("y"), c.i32_const(pAux1))); - f.addCode(c.call(f1mPrefix + "_mul", c.i32_const(pAux1), c.i32_const(pR2), c.getLocal("r"))); - } - - function buildSquare() { - const f = module.addFunction(prefix+"_square"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); - } - - - function buildInverse() { - - const f = module.addFunction(prefix+ "_inverse"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - f.addCode(c.call(intPrefix + "_inverseMod", c.getLocal("x"), c.i32_const(pq), c.getLocal("r"))); - } - - function buildIsNegative() { - const f = module.addFunction(prefix+"_isNegative"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call(intPrefix + "_gte", c.getLocal("x"), c.i32_const(pePlusOne) ) - ); - } - - - buildMul(); - buildSquare(); - buildInverse(); - buildIsNegative(); - module.exportFunction(f1mPrefix + "_add", prefix + "_add"); - module.exportFunction(f1mPrefix + "_sub", prefix + "_sub"); - module.exportFunction(f1mPrefix + "_neg", prefix + "_neg"); - module.exportFunction(prefix + "_mul"); - module.exportFunction(prefix + "_square"); - module.exportFunction(prefix + "_inverse"); - module.exportFunction(prefix + "_isNegative"); - module.exportFunction(f1mPrefix + "_copy", prefix+"_copy"); - module.exportFunction(f1mPrefix + "_zero", prefix+"_zero"); - module.exportFunction(f1mPrefix + "_one", prefix+"_one"); - module.exportFunction(f1mPrefix + "_isZero", prefix+"_isZero"); - module.exportFunction(f1mPrefix + "_eq", prefix+"_eq"); - - return prefix; -}; - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -const buildExp$1 = build_timesscalar; -const buildBatchInverse$1 = build_batchinverse; -const bigInt$4 = BigIntegerExports; -const utils$8 = utils$b; - -var build_f2m = function buildF2m(module, mulNonResidueFn, prefix, f1mPrefix) { - - if (module.modules[prefix]) return prefix; // already builded - - const f1n8 = module.modules[f1mPrefix].n64*8; - const q = module.modules[f1mPrefix].q; - - module.modules[prefix] = { - n64: module.modules[f1mPrefix].n64*2 - }; - - function buildAdd() { - const f = module.addFunction(prefix+"_add"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const y0 = c.getLocal("y"); - const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_add", x0, y0, r0), - c.call(f1mPrefix+"_add", x1, y1, r1), - ); - } - - function buildTimesScalar() { - const f = module.addFunction(prefix+"_timesScalar"); - f.addParam("x", "i32"); - f.addParam("scalar", "i32"); - f.addParam("scalarLen", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_timesScalar", x0, c.getLocal("scalar"), c.getLocal("scalarLen"), r0), - c.call(f1mPrefix+"_timesScalar", x1, c.getLocal("scalar"), c.getLocal("scalarLen"), r1), - ); - } - - function buildSub() { - const f = module.addFunction(prefix+"_sub"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const y0 = c.getLocal("y"); - const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_sub", x0, y0, r0), - c.call(f1mPrefix+"_sub", x1, y1, r1), - ); - } - - function buildNeg() { - const f = module.addFunction(prefix+"_neg"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_neg", x0, r0), - c.call(f1mPrefix+"_neg", x1, r1), - ); - } - - function buildConjugate() { - const f = module.addFunction(prefix+"_conjugate"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_copy", x0, r0), - c.call(f1mPrefix+"_neg", x1, r1), - ); - } - - - function buildIsNegative() { - const f = module.addFunction(prefix+"_isNegative"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - - f.addCode( - c.if( - c.call(f1mPrefix+"_isZero", x1), - c.ret(c.call(f1mPrefix+"_isNegative", x0)) - ), - c.ret(c.call(f1mPrefix+"_isNegative", x1)) - ); - } - - function buildMul() { - const f = module.addFunction(prefix+"_mul"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const y0 = c.getLocal("y"); - const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - const A = c.i32_const(module.alloc(f1n8)); - const B = c.i32_const(module.alloc(f1n8)); - const C = c.i32_const(module.alloc(f1n8)); - const D = c.i32_const(module.alloc(f1n8)); - - - f.addCode( - c.call(f1mPrefix + "_mul", x0, y0, A), // A = x0*y0 - c.call(f1mPrefix + "_mul", x1, y1, B), // B = x1*y1 - - c.call(f1mPrefix + "_add", x0, x1, C), // C = x0 + x1 - c.call(f1mPrefix + "_add", y0, y1, D), // D = y0 + y1 - c.call(f1mPrefix + "_mul", C, D, C), // C = (x0 + x1)*(y0 + y1) = x0*y0+x0*y1+x1*y0+x1*y1 - - // c.call(f1mPrefix + "_mul", B, c.i32_const(pNonResidue), r0), // r0 = nr*(x1*y1) - c.call(mulNonResidueFn, B, r0), // r0 = nr*(x1*y1) - c.call(f1mPrefix + "_add", A, r0, r0), // r0 = x0*y0 + nr*(x1*y1) - c.call(f1mPrefix + "_add", A, B, r1), // r1 = x0*y0+x1*y1 - c.call(f1mPrefix + "_sub", C, r1, r1) // r1 = x0*y0+x0*y1+x1*y0+x1*y1 - x0*y0+x1*y1 = x0*y1+x1*y0 - ); - - } - - function buildMul1() { - const f = module.addFunction(prefix+"_mul1"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const y = c.getLocal("y"); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - - f.addCode( - c.call(f1mPrefix + "_mul", x0, y, r0), // A = x0*y - c.call(f1mPrefix + "_mul", x1, y, r1), // B = x1*y - ); - } - - function buildSquare() { - const f = module.addFunction(prefix+"_square"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - const AB = c.i32_const(module.alloc(f1n8)); - const APB = c.i32_const(module.alloc(f1n8)); - const APNB = c.i32_const(module.alloc(f1n8)); - const ABPNAB = c.i32_const(module.alloc(f1n8)); - - - f.addCode( - // AB = x0*y1 - c.call(f1mPrefix + "_mul", x0, x1, AB), - - // APB = x0+y1 - c.call(f1mPrefix + "_add", x0, x1, APB), - - // APBN0 = x0 + nr*x1 - c.call(mulNonResidueFn, x1, APNB), - c.call(f1mPrefix + "_add", x0, APNB, APNB), - - // ABPNAB = ab + nr*ab - c.call(mulNonResidueFn, AB, ABPNAB), - c.call(f1mPrefix + "_add", ABPNAB, AB, ABPNAB), - - // r0 = APB * APNB - ABPNAB - c.call(f1mPrefix + "_mul", APB, APNB, r0), - c.call(f1mPrefix + "_sub", r0, ABPNAB, r0), - - // r1 = AB + AB - c.call(f1mPrefix + "_add", AB, AB, r1), - ); - - } - - - function buildToMontgomery() { - const f = module.addFunction(prefix+"_toMontgomery"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_toMontgomery", x0, r0), - c.call(f1mPrefix+"_toMontgomery", x1, r1) - ); - } - - function buildFromMontgomery() { - const f = module.addFunction(prefix+"_fromMontgomery"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_fromMontgomery", x0, r0), - c.call(f1mPrefix+"_fromMontgomery", x1, r1) - ); - } - - function buildCopy() { - const f = module.addFunction(prefix+"_copy"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_copy", x0, r0), - c.call(f1mPrefix+"_copy", x1, r1) - ); - } - - function buildZero() { - const f = module.addFunction(prefix+"_zero"); - f.addParam("x", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_zero", x0), - c.call(f1mPrefix+"_zero", x1) - ); - } - - function buildOne() { - const f = module.addFunction(prefix+"_one"); - f.addParam("x", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_one", x0), - c.call(f1mPrefix+"_zero", x1) - ); - } - - function buildEq() { - const f = module.addFunction(prefix+"_eq"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const y0 = c.getLocal("y"); - const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); - - f.addCode( - c.i32_and( - c.call(f1mPrefix+"_eq", x0, y0), - c.call(f1mPrefix+"_eq", x1, y1) - ) - ); - } - - function buildIsZero() { - const f = module.addFunction(prefix+"_isZero"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - - f.addCode( - c.i32_and( - c.call(f1mPrefix+"_isZero", x0), - c.call(f1mPrefix+"_isZero", x1) - ) - ); - } - - function buildInverse() { - const f = module.addFunction(prefix+"_inverse"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - const t0 = c.i32_const(module.alloc(f1n8)); - const t1 = c.i32_const(module.alloc(f1n8)); - const t2 = c.i32_const(module.alloc(f1n8)); - const t3 = c.i32_const(module.alloc(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_square", x0, t0), - c.call(f1mPrefix+"_square", x1, t1), - // c.call(f1mPrefix+"_mul", t1, c.i32_const(pNonResidue), t2), - c.call(mulNonResidueFn, t1, t2), - - c.call(f1mPrefix+"_sub", t0, t2, t2), - c.call(f1mPrefix+"_inverse", t2, t3), - - c.call(f1mPrefix+"_mul", x0, t3, r0), - c.call(f1mPrefix+"_mul", x1, t3, r1), - c.call(f1mPrefix+"_neg", r1, r1), - ); - } - - - function buildSign() { - const f = module.addFunction(prefix+"_sign"); - f.addParam("x", "i32"); - f.addLocal("s", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - - f.addCode( - c.setLocal("s" , c.call( f1mPrefix + "_sign", x1)), - c.if( - c.getLocal("s"), - c.ret(c.getLocal("s")) - ), - c.ret(c.call( f1mPrefix + "_sign", x0)) - ); - } - - function buildIsOne() { - const f = module.addFunction(prefix+"_isOne"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - - f.addCode( - c.ret(c.i32_and( - c.call(f1mPrefix + "_isOne", x0), - c.call(f1mPrefix + "_isZero", x1), - )) - ); - } - - - // Check here: https://eprint.iacr.org/2012/685.pdf - // Alg 9adj - function buildSqrt() { - - const f = module.addFunction(prefix+"_sqrt"); - f.addParam("a", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - const e34 = c.i32_const(module.alloc(utils$8.bigInt2BytesLE(bigInt$4(q).minus(bigInt$4(3)).divide(4), f1n8 ))); - const e12 = c.i32_const(module.alloc(utils$8.bigInt2BytesLE(bigInt$4(q).minus(bigInt$4(1)).divide(2), f1n8 ))); - - const a = c.getLocal("a"); - const a1 = c.i32_const(module.alloc(f1n8*2)); - const alpha = c.i32_const(module.alloc(f1n8*2)); - const a0 = c.i32_const(module.alloc(f1n8*2)); - const pn1 = module.alloc(f1n8*2); - const n1 = c.i32_const(pn1); - const n1a = c.i32_const(pn1); - const n1b = c.i32_const(pn1+f1n8); - const x0 = c.i32_const(module.alloc(f1n8*2)); - const b = c.i32_const(module.alloc(f1n8*2)); - - f.addCode( - - c.call(prefix + "_one", n1), - c.call(prefix + "_neg", n1, n1), - - // const a1 = F.pow(a, F.sqrt_e34); - c.call(prefix + "_exp", a, e34, c.i32_const(f1n8), a1), - - // const a1 = F.pow(a, F.sqrt_e34); - c.call(prefix + "_square", a1, alpha), - c.call(prefix + "_mul", a, alpha, alpha), - - // const a0 = F.mul(F.frobenius(1, alfa), alfa); - c.call(prefix + "_conjugate", alpha, a0), - c.call(prefix + "_mul", a0, alpha, a0), - - // if (F.eq(a0, F.negone)) return null; - c.if(c.call(prefix + "_eq",a0,n1), c.unreachable() ), - - // const x0 = F.mul(a1, a); - c.call(prefix + "_mul", a1, a, x0), - - // if (F.eq(alfa, F.negone)) { - c.if( - c.call(prefix + "_eq", alpha, n1), - [ - // x = F.mul(x0, [F.F.zero, F.F.one]); - ...c.call(f1mPrefix + "_zero", n1a), - ...c.call(f1mPrefix + "_one", n1b), - ...c.call(prefix + "_mul", n1, x0, c.getLocal("pr")), - ], - [ - // const b = F.pow(F.add(F.one, alfa), F.sqrt_e12); - ...c.call(prefix + "_one", b), - ...c.call(prefix + "_add", b, alpha, b), - ...c.call(prefix + "_exp", b, e12, c.i32_const(f1n8), b), - - // x = F.mul(b, x0); - ...c.call(prefix + "_mul", b, x0, c.getLocal("pr")), - ] - ) - ); - - } - - - function buildIsSquare() { - - const f = module.addFunction(prefix+"_isSquare"); - f.addParam("a", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const e34 = c.i32_const(module.alloc(utils$8.bigInt2BytesLE(bigInt$4(q).minus(bigInt$4(3)).divide(4), f1n8 ))); - - const a = c.getLocal("a"); - const a1 = c.i32_const(module.alloc(f1n8*2)); - const alpha = c.i32_const(module.alloc(f1n8*2)); - const a0 = c.i32_const(module.alloc(f1n8*2)); - const pn1 = module.alloc(f1n8*2); - const n1 = c.i32_const(pn1); - - f.addCode( - - c.call(prefix + "_one", n1), - c.call(prefix + "_neg", n1, n1), - - // const a1 = F.pow(a, F.sqrt_e34); - c.call(prefix + "_exp", a, e34, c.i32_const(f1n8), a1), - - // const a1 = F.pow(a, F.sqrt_e34); - c.call(prefix + "_square", a1, alpha), - c.call(prefix + "_mul", a, alpha, alpha), - - // const a0 = F.mul(F.frobenius(1, alfa), alfa); - c.call(prefix + "_conjugate", alpha, a0), - c.call(prefix + "_mul", a0, alpha, a0), - - // if (F.eq(a0, F.negone)) return null; - c.if( - c.call( - prefix + "_eq", - a0, - n1 - ), - c.ret(c.i32_const(0)) - ), - c.ret(c.i32_const(1)) - ); - - } - - - buildIsZero(); - buildIsOne(); - buildZero(); - buildOne(); - buildCopy(); - buildMul(); - buildMul1(); - buildSquare(); - buildAdd(); - buildSub(); - buildNeg(); - buildConjugate(); - buildToMontgomery(); - buildFromMontgomery(); - buildEq(); - buildInverse(); - buildTimesScalar(); - buildSign(); - buildIsNegative(); - - module.exportFunction(prefix + "_isZero"); - module.exportFunction(prefix + "_isOne"); - module.exportFunction(prefix + "_zero"); - module.exportFunction(prefix + "_one"); - module.exportFunction(prefix + "_copy"); - module.exportFunction(prefix + "_mul"); - module.exportFunction(prefix + "_mul1"); - module.exportFunction(prefix + "_square"); - module.exportFunction(prefix + "_add"); - module.exportFunction(prefix + "_sub"); - module.exportFunction(prefix + "_neg"); - module.exportFunction(prefix + "_sign"); - module.exportFunction(prefix + "_conjugate"); - module.exportFunction(prefix + "_fromMontgomery"); - module.exportFunction(prefix + "_toMontgomery"); - module.exportFunction(prefix + "_eq"); - module.exportFunction(prefix + "_inverse"); - buildBatchInverse$1(module, prefix); - buildExp$1( - module, - prefix + "_exp", - f1n8*2, - prefix + "_mul", - prefix + "_square", - prefix + "_copy", - prefix + "_one", - ); - buildSqrt(); - buildIsSquare(); - - module.exportFunction(prefix + "_exp"); - module.exportFunction(prefix + "_timesScalar"); - module.exportFunction(prefix + "_batchInverse"); - module.exportFunction(prefix + "_sqrt"); - module.exportFunction(prefix + "_isSquare"); - module.exportFunction(prefix + "_isNegative"); - - - return prefix; -}; - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -const buildExp = build_timesscalar; -const buildBatchInverse = build_batchinverse; - -var build_f3m = function buildF3m(module, mulNonResidueFn, prefix, f1mPrefix) { - - if (module.modules[prefix]) return prefix; // already builded - - const f1n8 = module.modules[f1mPrefix].n64*8; - module.modules[prefix] = { - n64: module.modules[f1mPrefix].n64*3 - }; - - function buildAdd() { - const f = module.addFunction(prefix+"_add"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const y0 = c.getLocal("y"); - const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); - const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_add", x0, y0, r0), - c.call(f1mPrefix+"_add", x1, y1, r1), - c.call(f1mPrefix+"_add", x2, y2, r2), - ); - } - - function buildTimesScalar() { - const f = module.addFunction(prefix+"_timesScalar"); - f.addParam("x", "i32"); - f.addParam("scalar", "i32"); - f.addParam("scalarLen", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_timesScalar", x0, c.getLocal("scalar"), c.getLocal("scalarLen"), r0), - c.call(f1mPrefix+"_timesScalar", x1, c.getLocal("scalar"), c.getLocal("scalarLen"), r1), - c.call(f1mPrefix+"_timesScalar", x2, c.getLocal("scalar"), c.getLocal("scalarLen"), r2), - ); - } - - - function buildSub() { - const f = module.addFunction(prefix+"_sub"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const y0 = c.getLocal("y"); - const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); - const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_sub", x0, y0, r0), - c.call(f1mPrefix+"_sub", x1, y1, r1), - c.call(f1mPrefix+"_sub", x2, y2, r2), - ); - } - - function buildNeg() { - const f = module.addFunction(prefix+"_neg"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_neg", x0, r0), - c.call(f1mPrefix+"_neg", x1, r1), - c.call(f1mPrefix+"_neg", x2, r2), - ); - } - - function buildIsNegative() { - const f = module.addFunction(prefix+"_isNegative"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - - f.addCode( - c.if( - c.call(f1mPrefix+"_isZero", x2), - c.if( - c.call(f1mPrefix+"_isZero", x1), - c.ret(c.call(f1mPrefix+"_isNegative", x0)), - c.ret(c.call(f1mPrefix+"_isNegative", x1)) - ) - ), - c.ret(c.call(f1mPrefix+"_isNegative", x2)) - ); - } - - - function buildMul() { - const f = module.addFunction(prefix+"_mul"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const cd = f.getCodeBuilder(); - - const a = cd.getLocal("x"); - const b = cd.i32_add(cd.getLocal("x"), cd.i32_const(f1n8)); - const c = cd.i32_add(cd.getLocal("x"), cd.i32_const(2*f1n8)); - const A = cd.getLocal("y"); - const B = cd.i32_add(cd.getLocal("y"), cd.i32_const(f1n8)); - const C = cd.i32_add(cd.getLocal("y"), cd.i32_const(2*f1n8)); - const r0 = cd.getLocal("r"); - const r1 = cd.i32_add(cd.getLocal("r"), cd.i32_const(f1n8)); - const r2 = cd.i32_add(cd.getLocal("r"), cd.i32_const(2*f1n8)); - - const aA = cd.i32_const(module.alloc(f1n8)); - const bB = cd.i32_const(module.alloc(f1n8)); - const cC = cd.i32_const(module.alloc(f1n8)); - const a_b = cd.i32_const(module.alloc(f1n8)); - const A_B = cd.i32_const(module.alloc(f1n8)); - const a_c = cd.i32_const(module.alloc(f1n8)); - const A_C = cd.i32_const(module.alloc(f1n8)); - const b_c = cd.i32_const(module.alloc(f1n8)); - const B_C = cd.i32_const(module.alloc(f1n8)); - const aA_bB = cd.i32_const(module.alloc(f1n8)); - const aA_cC = cd.i32_const(module.alloc(f1n8)); - const bB_cC = cd.i32_const(module.alloc(f1n8)); - const AUX = cd.i32_const(module.alloc(f1n8)); - - - f.addCode( - cd.call(f1mPrefix + "_mul", a, A, aA), - cd.call(f1mPrefix + "_mul", b, B, bB), - cd.call(f1mPrefix + "_mul", c, C, cC), - - cd.call(f1mPrefix + "_add", a, b, a_b), - cd.call(f1mPrefix + "_add", A, B, A_B), - cd.call(f1mPrefix + "_add", a, c, a_c), - cd.call(f1mPrefix + "_add", A, C, A_C), - cd.call(f1mPrefix + "_add", b, c, b_c), - cd.call(f1mPrefix + "_add", B, C, B_C), - - cd.call(f1mPrefix + "_add", aA, bB, aA_bB), - cd.call(f1mPrefix + "_add", aA, cC, aA_cC), - cd.call(f1mPrefix + "_add", bB, cC, bB_cC), - - cd.call(f1mPrefix + "_mul", b_c, B_C, r0), - cd.call(f1mPrefix + "_sub", r0, bB_cC, r0), - cd.call(mulNonResidueFn, r0, r0), - cd.call(f1mPrefix + "_add", aA, r0, r0), - - cd.call(f1mPrefix + "_mul", a_b, A_B, r1), - cd.call(f1mPrefix + "_sub", r1, aA_bB, r1), - cd.call(mulNonResidueFn, cC, AUX), - cd.call(f1mPrefix + "_add", r1, AUX, r1), - - cd.call(f1mPrefix + "_mul", a_c, A_C, r2), - cd.call(f1mPrefix + "_sub", r2, aA_cC, r2), - cd.call(f1mPrefix + "_add", r2, bB, r2), - ); - - } - - function buildSquare() { - const f = module.addFunction(prefix+"_square"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const A = c.getLocal("x"); - const B = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const C = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - const s0 = c.i32_const(module.alloc(f1n8)); - const ab = c.i32_const(module.alloc(f1n8)); - const s1 = c.i32_const(module.alloc(f1n8)); - const s2 = c.i32_const(module.alloc(f1n8)); - const bc = c.i32_const(module.alloc(f1n8)); - const s3 = c.i32_const(module.alloc(f1n8)); - const s4 = c.i32_const(module.alloc(f1n8)); - - - f.addCode( - - c.call(f1mPrefix + "_square", A, s0), - c.call(f1mPrefix + "_mul", A, B, ab), - c.call(f1mPrefix + "_add", ab, ab, s1), - - c.call(f1mPrefix + "_sub", A, B, s2), - c.call(f1mPrefix + "_add", s2, C, s2), - c.call(f1mPrefix + "_square", s2, s2), - - c.call(f1mPrefix + "_mul", B, C, bc), - c.call(f1mPrefix + "_add", bc, bc, s3), - - c.call(f1mPrefix + "_square", C, s4), - - c.call(mulNonResidueFn, s3, r0), - c.call(f1mPrefix + "_add", s0, r0, r0), - - c.call(mulNonResidueFn, s4, r1), - c.call(f1mPrefix + "_add", s1, r1, r1), - - c.call(f1mPrefix + "_add", s0, s4, r2), - c.call(f1mPrefix + "_sub", s3, r2, r2), - c.call(f1mPrefix + "_add", s2, r2, r2), - c.call(f1mPrefix + "_add", s1, r2, r2), - ); - - } - - - function buildToMontgomery() { - const f = module.addFunction(prefix+"_toMontgomery"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_toMontgomery", x0, r0), - c.call(f1mPrefix+"_toMontgomery", x1, r1), - c.call(f1mPrefix+"_toMontgomery", x2, r2) - ); - } - - function buildFromMontgomery() { - const f = module.addFunction(prefix+"_fromMontgomery"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_fromMontgomery", x0, r0), - c.call(f1mPrefix+"_fromMontgomery", x1, r1), - c.call(f1mPrefix+"_fromMontgomery", x2, r2) - ); - } - - function buildCopy() { - const f = module.addFunction(prefix+"_copy"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_copy", x0, r0), - c.call(f1mPrefix+"_copy", x1, r1), - c.call(f1mPrefix+"_copy", x2, r2), - ); - } - - function buildZero() { - const f = module.addFunction(prefix+"_zero"); - f.addParam("x", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_zero", x0), - c.call(f1mPrefix+"_zero", x1), - c.call(f1mPrefix+"_zero", x2), - ); - } - - function buildOne() { - const f = module.addFunction(prefix+"_one"); - f.addParam("x", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_one", x0), - c.call(f1mPrefix+"_zero", x1), - c.call(f1mPrefix+"_zero", x2), - ); - } - - function buildEq() { - const f = module.addFunction(prefix+"_eq"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const y0 = c.getLocal("y"); - const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); - const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); - - f.addCode( - c.i32_and( - c.i32_and( - c.call(f1mPrefix+"_eq", x0, y0), - c.call(f1mPrefix+"_eq", x1, y1), - ), - c.call(f1mPrefix+"_eq", x2, y2) - ) - ); - } - - function buildIsZero() { - const f = module.addFunction(prefix+"_isZero"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - - f.addCode( - c.i32_and( - c.i32_and( - c.call(f1mPrefix+"_isZero", x0), - c.call(f1mPrefix+"_isZero", x1) - ), - c.call(f1mPrefix+"_isZero", x2) - ) - ); - } - - function buildInverse() { - const f = module.addFunction(prefix+"_inverse"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - const t0 = c.i32_const(module.alloc(f1n8)); - const t1 = c.i32_const(module.alloc(f1n8)); - const t2 = c.i32_const(module.alloc(f1n8)); - const t3 = c.i32_const(module.alloc(f1n8)); - const t4 = c.i32_const(module.alloc(f1n8)); - const t5 = c.i32_const(module.alloc(f1n8)); - const c0 = c.i32_const(module.alloc(f1n8)); - const c1 = c.i32_const(module.alloc(f1n8)); - const c2 = c.i32_const(module.alloc(f1n8)); - const t6 = c.i32_const(module.alloc(f1n8)); - const AUX = c.i32_const(module.alloc(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_square", x0, t0), - c.call(f1mPrefix+"_square", x1, t1), - c.call(f1mPrefix+"_square", x2, t2), - c.call(f1mPrefix+"_mul", x0, x1, t3), - c.call(f1mPrefix+"_mul", x0, x2, t4), - c.call(f1mPrefix+"_mul", x1, x2, t5), - - c.call(mulNonResidueFn, t5, c0), - c.call(f1mPrefix+"_sub", t0, c0, c0), - - c.call(mulNonResidueFn, t2, c1), - c.call(f1mPrefix+"_sub", c1, t3, c1), - - c.call(f1mPrefix+"_sub", t1, t4, c2), - - c.call(f1mPrefix+"_mul", x2, c1, t6), - c.call(f1mPrefix+"_mul", x1, c2, AUX), - c.call(f1mPrefix+"_add", t6, AUX, t6), - c.call(mulNonResidueFn, t6, t6), - c.call(f1mPrefix+"_mul", x0, c0, AUX), - c.call(f1mPrefix+"_add", AUX, t6, t6), - - c.call(f1mPrefix+"_inverse", t6, t6), - - c.call(f1mPrefix+"_mul", t6, c0, r0), - c.call(f1mPrefix+"_mul", t6, c1, r1), - c.call(f1mPrefix+"_mul", t6, c2, r2) - ); - } - - - function buildSign() { - const f = module.addFunction(prefix+"_sign"); - f.addParam("x", "i32"); - f.addLocal("s", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - - f.addCode( - c.setLocal("s" , c.call( f1mPrefix + "_sign", x2)), - c.if( - c.getLocal("s"), - c.ret(c.getLocal("s")) - ), - c.setLocal("s" , c.call( f1mPrefix + "_sign", x1)), - c.if( - c.getLocal("s"), - c.ret(c.getLocal("s")) - ), - c.ret(c.call( f1mPrefix + "_sign", x0)) - ); - } - - function buildIsOne() { - const f = module.addFunction(prefix+"_isOne"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8*2)); - - f.addCode( - c.ret( - c.i32_and( - c.i32_and( - c.call(f1mPrefix + "_isOne", x0), - c.call(f1mPrefix + "_isZero", x1) - ), - c.call(f1mPrefix + "_isZero", x2) - ) - ) - ); - } - - buildIsZero(); - buildIsOne(); - buildZero(); - buildOne(); - buildCopy(); - buildMul(); - buildSquare(); - buildAdd(); - buildSub(); - buildNeg(); - buildSign(); - buildToMontgomery(); - buildFromMontgomery(); - buildEq(); - buildInverse(); - buildTimesScalar(); - buildIsNegative(); - - module.exportFunction(prefix + "_isZero"); - module.exportFunction(prefix + "_isOne"); - module.exportFunction(prefix + "_zero"); - module.exportFunction(prefix + "_one"); - module.exportFunction(prefix + "_copy"); - module.exportFunction(prefix + "_mul"); - module.exportFunction(prefix + "_square"); - module.exportFunction(prefix + "_add"); - module.exportFunction(prefix + "_sub"); - module.exportFunction(prefix + "_neg"); - module.exportFunction(prefix + "_sign"); - module.exportFunction(prefix + "_fromMontgomery"); - module.exportFunction(prefix + "_toMontgomery"); - module.exportFunction(prefix + "_eq"); - module.exportFunction(prefix + "_inverse"); - buildBatchInverse(module, prefix); - buildExp( - module, - prefix + "_exp", - f1n8*3, - prefix + "_mul", - prefix + "_square", - prefix + "_copy", - prefix + "_one" - ); - module.exportFunction(prefix + "_exp"); - module.exportFunction(prefix + "_timesScalar"); - module.exportFunction(prefix + "_batchInverse"); - module.exportFunction(prefix + "_isNegative"); - - return prefix; -}; - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -var build_timesscalarnaf = function buildTimesScalarNAF(module, fnName, elementLen, opAB, opAA, opAmB, opCopy, opInit) { - - const f = module.addFunction(fnName); - f.addParam("base", "i32"); - f.addParam("scalar", "i32"); - f.addParam("scalarLength", "i32"); - f.addParam("r", "i32"); - f.addLocal("old0", "i32"); - f.addLocal("nbits", "i32"); - f.addLocal("i", "i32"); - f.addLocal("last", "i32"); - f.addLocal("cur", "i32"); - f.addLocal("carry", "i32"); - f.addLocal("p", "i32"); - - const c = f.getCodeBuilder(); - - const aux = c.i32_const(module.alloc(elementLen)); - - function getBit(IDX) { - return c.i32_and( - c.i32_shr_u( - c.i32_load( - c.i32_add( - c.getLocal("scalar"), - c.i32_and( - c.i32_shr_u( - IDX, - c.i32_const(3) - ), - c.i32_const(0xFFFFFFFC) - ) - ) - ), - c.i32_and( - IDX, - c.i32_const(0x1F) - ) - ), - c.i32_const(1) - ); - } - - function pushBit(b) { - return [ - ...c.i32_store8( - c.getLocal("p"), - c.i32_const(b) - ), - ...c.setLocal( - "p", - c.i32_add( - c.getLocal("p"), - c.i32_const(1) - ) - ) - ]; - } - - f.addCode( - c.if( - c.i32_eqz(c.getLocal("scalarLength")), - [ - ...c.call(opInit, c.getLocal("r")), - ...c.ret([]) - ] - ), - c.setLocal("nbits", c.i32_shl(c.getLocal("scalarLength"), c.i32_const(3))), - c.setLocal("old0", c.i32_load(c.i32_const(0))), - c.setLocal("p", c.getLocal("old0")), - c.i32_store( - c.i32_const(0), - c.i32_and( - c.i32_add( - c.i32_add( - c.getLocal("old0"), - c.i32_const(32) - ), - c.getLocal("nbits") - ), - c.i32_const(0xFFFFFFF8) - ) - ), - c.setLocal("i", c.i32_const(1)), - - c.setLocal("last",getBit(c.i32_const(0))), - c.setLocal("carry",c.i32_const(0)), - - c.block(c.loop( - c.br_if(1, c.i32_eq( c.getLocal("i"), c.getLocal("nbits"))), - - c.setLocal("cur", getBit(c.getLocal("i"))), - c.if( c.getLocal("last"), - c.if( c.getLocal("cur"), - c.if(c.getLocal("carry"), - [ - ...c.setLocal("last", c.i32_const(0)), - ...c.setLocal("carry", c.i32_const(1)), - ...pushBit(1) - ] - , - [ - ...c.setLocal("last", c.i32_const(0)), - ...c.setLocal("carry", c.i32_const(1)), - ...pushBit(255) - ], - ), - c.if(c.getLocal("carry"), - [ - ...c.setLocal("last", c.i32_const(0)), - ...c.setLocal("carry", c.i32_const(1)), - ...pushBit(255) - ] - , - [ - ...c.setLocal("last", c.i32_const(0)), - ...c.setLocal("carry", c.i32_const(0)), - ...pushBit(1) - ], - ), - ), - c.if( c.getLocal("cur"), - c.if(c.getLocal("carry"), - [ - ...c.setLocal("last", c.i32_const(0)), - ...c.setLocal("carry", c.i32_const(1)), - ...pushBit(0) - ] - , - [ - ...c.setLocal("last", c.i32_const(1)), - ...c.setLocal("carry", c.i32_const(0)), - ...pushBit(0) - ], - ), - c.if(c.getLocal("carry"), - [ - ...c.setLocal("last", c.i32_const(1)), - ...c.setLocal("carry", c.i32_const(0)), - ...pushBit(0) - ] - , - [ - ...c.setLocal("last", c.i32_const(0)), - ...c.setLocal("carry", c.i32_const(0)), - ...pushBit(0) - ], - ), - ) - ), - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )), - - c.if( c.getLocal("last"), - c.if(c.getLocal("carry"), - [ - ...pushBit(255), - ...pushBit(0), - ...pushBit(1) - ] - , - [ - ...pushBit(1) - ], - ), - c.if(c.getLocal("carry"), - [ - ...pushBit(0), - ...pushBit(1) - ] - ), - ), - - c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), - - // p already points to the last bit - - c.call(opCopy, c.getLocal("base"), aux), - - c.call(opInit, c.getLocal("r")), - - c.block(c.loop( - - - c.call(opAA, c.getLocal("r"), c.getLocal("r")), - - - c.setLocal("cur", - c.i32_load8_u( - c.getLocal("p") - ) - ), - - c.if( - c.getLocal("cur"), - c.if( - c.i32_eq(c.getLocal("cur"), c.i32_const(1)), - c.call(opAB, c.getLocal("r"), aux, c.getLocal("r")), - c.call(opAmB, c.getLocal("r"), aux, c.getLocal("r")), - ) - ), - - c.br_if(1, c.i32_eq( c.getLocal("old0"), c.getLocal("p"))), - c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), - c.br(0) - - )), - - c.i32_store( c.i32_const(0), c.getLocal("old0")) - - ); - -}; - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -var build_multiexp = function buildMultiexp(module, prefix, fnName, opAdd, n8b) { - - const n64g = module.modules[prefix].n64; - const n8g = n64g*8; - - function buildGetChunk() { - const f = module.addFunction(fnName + "_getChunk"); - f.addParam("pScalar", "i32"); - f.addParam("scalarSize", "i32"); // Number of bytes of the scalar - f.addParam("startBit", "i32"); // Bit to start extract - f.addParam("chunkSize", "i32"); // Chunk size in bits - f.addLocal("bitsToEnd", "i32"); - f.addLocal("mask", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.setLocal("bitsToEnd", - c.i32_sub( - c.i32_mul( - c.getLocal("scalarSize"), - c.i32_const(8) - ), - c.getLocal("startBit") - ) - ), - c.if( - c.i32_gt_s( - c.getLocal("chunkSize"), - c.getLocal("bitsToEnd") - ), - c.setLocal( - "mask", - c.i32_sub( - c.i32_shl( - c.i32_const(1), - c.getLocal("bitsToEnd") - ), - c.i32_const(1) - ) - ), - c.setLocal( - "mask", - c.i32_sub( - c.i32_shl( - c.i32_const(1), - c.getLocal("chunkSize") - ), - c.i32_const(1) - ) - ) - ), - c.i32_and( - c.i32_shr_u( - c.i32_load( - c.i32_add( - c.getLocal("pScalar"), - c.i32_shr_u( - c.getLocal("startBit"), - c.i32_const(3) - ) - ), - 0, // offset - 0 // align to byte. - ), - c.i32_and( - c.getLocal("startBit"), - c.i32_const(0x7) - ) - ), - c.getLocal("mask") - ) - ); - } - - function buildMutiexpChunk() { - const f = module.addFunction(fnName + "_chunk"); - f.addParam("pBases", "i32"); - f.addParam("pScalars", "i32"); - f.addParam("scalarSize", "i32"); // Number of points - f.addParam("n", "i32"); // Number of points - f.addParam("startBit", "i32"); // bit where it starts the chunk - f.addParam("chunkSize", "i32"); // bit where it starts the chunk - f.addParam("pr", "i32"); - f.addLocal("nChunks", "i32"); - f.addLocal("itScalar", "i32"); - f.addLocal("endScalar", "i32"); - f.addLocal("itBase", "i32"); - f.addLocal("i", "i32"); - f.addLocal("j", "i32"); - f.addLocal("nTable", "i32"); - f.addLocal("pTable", "i32"); - f.addLocal("idx", "i32"); - f.addLocal("pIdxTable", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.if( - c.i32_eqz(c.getLocal("n")), - [ - ...c.call(prefix + "_zero", c.getLocal("pr")), - ...c.ret([]) - ] - ), - - // Allocate memory - - c.setLocal( - "nTable", - c.i32_shl( - c.i32_const(1), - c.getLocal("chunkSize") - ) - ), - c.setLocal("pTable", c.i32_load( c.i32_const(0) )), - c.i32_store( - c.i32_const(0), - c.i32_add( - c.getLocal("pTable"), - c.i32_mul( - c.getLocal("nTable"), - c.i32_const(n8g) - ) - ) - ), - - // Reset Table - c.setLocal("j", c.i32_const(0)), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("j"), - c.getLocal("nTable") - ) - ), - - c.call( - prefix + "_zero", - c.i32_add( - c.getLocal("pTable"), - c.i32_mul( - c.getLocal("j"), - c.i32_const(n8g) - ) - ) - ), - - c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), - c.br(0) - )), - - // Distribute elements - c.setLocal("itBase", c.getLocal("pBases")), - c.setLocal("itScalar", c.getLocal("pScalars")), - c.setLocal("endScalar", - c.i32_add( - c.getLocal("pScalars"), - c.i32_mul( - c.getLocal("n"), - c.getLocal("scalarSize") - ) - ) - ), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("itScalar"), - c.getLocal("endScalar") - ) - ), - - c.setLocal( - "idx", - c.call(fnName + "_getChunk", - c.getLocal("itScalar"), - c.getLocal("scalarSize"), - c.getLocal("startBit"), - c.getLocal("chunkSize") - ) - ), - - c.if( - c.getLocal("idx"), - [ - ...c.setLocal( - "pIdxTable", - c.i32_add( - c.getLocal("pTable"), - c.i32_mul( - c.i32_sub( - c.getLocal("idx"), - c.i32_const(1) - ), - c.i32_const(n8g) - ) - ) - ), - ...c.call( - opAdd, - c.getLocal("pIdxTable"), - c.getLocal("itBase"), - c.getLocal("pIdxTable"), - ) - ] - ), - - c.setLocal("itScalar", c.i32_add(c.getLocal("itScalar"), c.getLocal("scalarSize"))), - c.setLocal("itBase", c.i32_add(c.getLocal("itBase"), c.i32_const(n8b))), - c.br(0) - )), - - c.call(fnName + "_reduceTable", c.getLocal("pTable"), c.getLocal("chunkSize")), - c.call( - prefix + "_copy", - c.getLocal("pTable"), - c.getLocal("pr") - ), - - - c.i32_store( - c.i32_const(0), - c.getLocal("pTable") - ) - - ); - } - - function buildMultiexp() { - const f = module.addFunction(fnName); - f.addParam("pBases", "i32"); - f.addParam("pScalars", "i32"); - f.addParam("scalarSize", "i32"); // Number of points - f.addParam("n", "i32"); // Number of points - f.addParam("pr", "i32"); - f.addLocal("chunkSize", "i32"); - f.addLocal("nChunks", "i32"); - f.addLocal("itScalar", "i32"); - f.addLocal("endScalar", "i32"); - f.addLocal("itBase", "i32"); - f.addLocal("itBit", "i32"); - f.addLocal("i", "i32"); - f.addLocal("j", "i32"); - f.addLocal("nTable", "i32"); - f.addLocal("pTable", "i32"); - f.addLocal("idx", "i32"); - f.addLocal("pIdxTable", "i32"); - - const c = f.getCodeBuilder(); - - const aux = c.i32_const(module.alloc(n8g)); - - const pTSizes = module.alloc([ - 17, 17, 17, 17, 17, 17, 17, 17, - 17, 17, 16, 16, 15, 14, 13, 13, - 12, 11, 10, 9, 8, 7, 7, 6, - 5 , 4, 3, 2, 1, 1, 1, 1 - ]); - - f.addCode( - c.call(prefix + "_zero", c.getLocal("pr")), - c.if( - c.i32_eqz(c.getLocal("n")), - c.ret([]) - ), - c.setLocal("chunkSize", c.i32_load8_u( c.i32_clz(c.getLocal("n")), pTSizes )), - c.setLocal( - "nChunks", - c.i32_add( - c.i32_div_u( - c.i32_sub( - c.i32_shl( - c.getLocal("scalarSize"), - c.i32_const(3) - ), - c.i32_const(1) - ), - c.getLocal("chunkSize") - ), - c.i32_const(1) - ) - ), - - - // Allocate memory - - c.setLocal( - "itBit", - c.i32_mul( - c.i32_sub( - c.getLocal("nChunks"), - c.i32_const(1) - ), - c.getLocal("chunkSize") - ) - ), - c.block(c.loop( - c.br_if( - 1, - c.i32_lt_s( - c.getLocal("itBit"), - c.i32_const(0) - ) - ), - - // Double nChunk times - c.if( - c.i32_eqz(c.call(prefix + "_isZero", c.getLocal("pr"))), - [ - ...c.setLocal("j", c.i32_const(0)), - ...c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("j"), - c.getLocal("chunkSize") - ) - ), - - c.call(prefix + "_double", c.getLocal("pr"), c.getLocal("pr")), - - c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), - c.br(0) - )) - ] - ), - - c.call( - fnName + "_chunk", - c.getLocal("pBases"), - c.getLocal("pScalars"), - c.getLocal("scalarSize"), - c.getLocal("n"), - c.getLocal("itBit"), - c.getLocal("chunkSize"), - aux - ), - - c.call( - prefix + "_add", - c.getLocal("pr"), - aux, - c.getLocal("pr") - ), - c.setLocal("itBit", c.i32_sub(c.getLocal("itBit"), c.getLocal("chunkSize"))), - c.br(0) - )) - ); - } - - function buildReduceTable() { - const f = module.addFunction(fnName + "_reduceTable"); - f.addParam("pTable", "i32"); - f.addParam("p", "i32"); // Number of bits of the table - f.addLocal("half", "i32"); - f.addLocal("it1", "i32"); - f.addLocal("it2", "i32"); - f.addLocal("pAcc", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.if( - c.i32_eq(c.getLocal("p"), c.i32_const(1)), - c.ret([]) - ), - c.setLocal( - "half", - c.i32_shl( - c.i32_const(1), - c.i32_sub( - c.getLocal("p"), - c.i32_const(1) - ) - ) - ), - - c.setLocal("it1", c.getLocal("pTable")), - c.setLocal( - "it2", - c.i32_add( - c.getLocal("pTable"), - c.i32_mul( - c.getLocal("half"), - c.i32_const(n8g) - ) - ) - ), - c.setLocal("pAcc", - c.i32_sub( - c.getLocal("it2"), - c.i32_const(n8g) - ) - ), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("it1"), - c.getLocal("pAcc") - ) - ), - c.call( - prefix + "_add", - c.getLocal("it1"), - c.getLocal("it2"), - c.getLocal("it1") - ), - c.call( - prefix + "_add", - c.getLocal("pAcc"), - c.getLocal("it2"), - c.getLocal("pAcc") - ), - c.setLocal("it1", c.i32_add(c.getLocal("it1"), c.i32_const(n8g))), - c.setLocal("it2", c.i32_add(c.getLocal("it2"), c.i32_const(n8g))), - c.br(0) - )), - - c.call( - fnName + "_reduceTable", - c.getLocal("pTable"), - c.i32_sub( - c.getLocal("p"), - c.i32_const(1) - ) - ), - - c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), - c.block(c.loop( - c.br_if(1, c.i32_eqz(c.getLocal("p"))), - c.call(prefix + "_double", c.getLocal("pAcc"), c.getLocal("pAcc")), - c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), - c.br(0) - )), - - c.call(prefix + "_add", c.getLocal("pTable"), c.getLocal("pAcc"), c.getLocal("pTable")) - ); - } - - buildGetChunk(); - buildReduceTable(); - buildMutiexpChunk(); - buildMultiexp(); - - module.exportFunction(fnName); - module.exportFunction(fnName +"_chunk"); - - -}; - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -const buildTimesScalarNAF = build_timesscalarnaf; -//const buildTimesScalar = require("./build_timesscalar"); -const buildBatchConvertion = build_batchconvertion; -const buildMultiexp$1 = build_multiexp; - -var build_curve_jacobian_a0 = function buildCurve(module, prefix, prefixField, pB) { - - - const n64 = module.modules[prefixField].n64; - const n8 = n64*8; - - if (module.modules[prefix]) return prefix; // already builded - module.modules[prefix] = { - n64: n64*3 - }; - - function buildIsZero() { - const f = module.addFunction(prefix + "_isZero"); - f.addParam("p1", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - f.addCode(c.call( - prefixField + "_isZero", - c.i32_add( - c.getLocal("p1"), - c.i32_const(n8*2) - ) - )); - } - function buildIsZeroAffine() { - const f = module.addFunction(prefix + "_isZeroAffine"); - f.addParam("p1", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.i32_and( - c.call( - prefixField + "_isZero", - c.getLocal("p1") - ), - c.call( - prefixField + "_isZero", - c.i32_add( - c.getLocal("p1"), - c.i32_const(n8) - ) - ) - ) - ); - } - - function buildCopy() { - const f = module.addFunction(prefix + "_copy"); - f.addParam("ps", "i32"); - f.addParam("pd", "i32"); - - const c = f.getCodeBuilder(); - - for (let i=0; i. -*/ - -const bigInt$3 = BigIntegerExports; -const utils$7 = utils$b; - -var build_fft = function buildFFT(module, prefix, gPrefix, fPrefix, opGtimesF) { - - const n64f = module.modules[fPrefix].n64; - const n8f = n64f*8; - - const n64g = module.modules[gPrefix].n64; - const n8g = n64g*8; - - const q = module.modules[fPrefix].q; - - let rem = q.minus(bigInt$3(1)); - let maxBits = 0; - while (!rem.isOdd()) { - maxBits ++; - rem = rem.shiftRight(1); - } - - let nr = bigInt$3(2); - - while ( nr.modPow(q.shiftRight(1), q).equals(1) ) nr = nr.add(1); - - // console.log(nr); - - const w = new Array(maxBits+1); - w[maxBits] = nr.modPow(rem, q); - - let n=maxBits-1; - while (n>=0) { - w[n] = w[n+1].modPow(2, q); - n--; - } - - const bytes = []; - const R = bigInt$3(1).shiftLeft(n8f*8).mod(q); - - for (let i=0; i> i); - } - } - return r; - } - - const rtable = Array(256); - for (let i=0; i<256; i++) { - rtable[i] = rev(i); - } - - const REVTABLE = module.alloc(rtable); - - - function buildLog2() { - const f = module.addFunction(prefix+"__log2"); - f.addParam("n", "i32"); - f.setReturnType("i32"); - f.addLocal("bits", "i32"); - f.addLocal("aux", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.setLocal( - "aux", - c.i32_shr_u( - c.getLocal("n"), - c.i32_const(1) - ) - ) - ); - f.addCode(c.setLocal("bits", c.i32_const(0))); - - f.addCode(c.block(c.loop( - c.br_if( - 1, - c.i32_eqz(c.getLocal("aux")) - ), - - c.setLocal( - "aux", - c.i32_shr_u( - c.getLocal("aux"), - c.i32_const(1) - ) - ), - - c.setLocal( - "bits", - c.i32_add( - c.getLocal("bits"), - c.i32_const(1) - ) - ), - - c.br(0) - ))); - - f.addCode(c.if( - c.i32_ne( - c.getLocal("n"), - c.i32_shl( - c.i32_const(1), - c.getLocal("bits") - ) - ), - c.unreachable() - )); - - f.addCode(c.if( - c.i32_gt_u( - c.getLocal("bits"), - c.i32_const(maxBits) - ), - c.unreachable() - )); - - f.addCode(c.getLocal("bits")); - } - - function buildFFT() { - const f = module.addFunction(prefix+"_fft"); - f.addParam("px", "i32"); - f.addParam("n", "i32"); - - f.addLocal("bits", "i32"); - - const c = f.getCodeBuilder(); - - const One = c.i32_const(module.alloc(n8f)); - - f.addCode( - c.setLocal( - "bits", - c.call( - prefix + "__log2", - c.getLocal("n") - ) - ), - c.call(fPrefix + "_one", One), - c.call( - prefix+"_rawfft", - c.getLocal("px"), - c.getLocal("bits"), - c.i32_const(0), - One - ) - ); - - } - - function buildIFFT() { - const f = module.addFunction(prefix+"_ifft"); - f.addParam("px", "i32"); - f.addParam("n", "i32"); - f.addLocal("bits", "i32"); - f.addLocal("pInv2", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.setLocal( - "bits", - c.call( - prefix + "__log2", - c.getLocal("n") - ) - ), - c.setLocal( - "pInv2", - c.i32_add( - c.i32_const(INV2), - c.i32_mul( - c.getLocal("bits"), - c.i32_const(n8f) - ) - ) - ), - - c.call( - prefix+"_rawfft", - c.getLocal("px"), - c.getLocal("bits"), - c.i32_const(1), - c.getLocal("pInv2") - ), - ); - } - - function buildRawFFT() { - const f = module.addFunction(prefix+"_rawfft"); - f.addParam("px", "i32"); - f.addParam("bits", "i32"); // 2 power - f.addParam("reverse", "i32"); - f.addParam("mulFactor", "i32"); - - f.addLocal("s", "i32"); - f.addLocal("k", "i32"); - f.addLocal("j", "i32"); - f.addLocal("m", "i32"); - f.addLocal("mdiv2", "i32"); - f.addLocal("n", "i32"); - f.addLocal("pwm", "i32"); - f.addLocal("idx1", "i32"); - f.addLocal("idx2", "i32"); - - const c = f.getCodeBuilder(); - - const W = c.i32_const(module.alloc(n8f)); - const T = c.i32_const(module.alloc(n8g)); - const U = c.i32_const(module.alloc(n8g)); - - f.addCode( - c.call(prefix + "__reversePermutation", c.getLocal("px"), c.getLocal("bits")), - c.setLocal("n", c.i32_shl(c.i32_const(1), c.getLocal("bits"))), - c.setLocal("s", c.i32_const(1)), - c.block(c.loop( - c.br_if( - 1, - c.i32_gt_u( - c.getLocal("s"), - c.getLocal("bits") - ) - ), - c.setLocal("m", c.i32_shl(c.i32_const(1), c.getLocal("s"))), - c.setLocal("pwm", - c.i32_add( - c.i32_const(ROOTs), - c.i32_mul( - c.getLocal("s"), - c.i32_const(n8f) - ) - ) - ), - c.setLocal("k", c.i32_const(0)), - c.block(c.loop( - c.br_if( - 1, - c.i32_ge_u( - c.getLocal("k"), - c.getLocal("n") - ) - ), - - c.call(fPrefix + "_one", W), - - c.setLocal("mdiv2", c.i32_shr_u(c.getLocal("m"), c.i32_const(1)) ), - c.setLocal("j", c.i32_const(0)), - c.block(c.loop( - c.br_if( - 1, - c.i32_ge_u( - c.getLocal("j"), - c.getLocal("mdiv2") - ) - ), - - c.setLocal( - "idx1", - c.i32_add( - c.getLocal("px"), - c.i32_mul( - c.i32_add( - c.getLocal("k"), - c.getLocal("j") - ), - c.i32_const(n8g) - ) - ) - ), - - c.setLocal( - "idx2", - c.i32_add( - c.getLocal("idx1"), - c.i32_mul( - c.getLocal("mdiv2"), - c.i32_const(n8g) - ) - ) - ), - - c.call( - opGtimesF, - c.getLocal("idx2"), - W, - T - ), - - c.call( - gPrefix + "_copy", - c.getLocal("idx1"), - U - ), - - c.call( - gPrefix + "_add", - U, - T, - c.getLocal("idx1"), - ), - - c.call( - gPrefix + "_sub", - U, - T, - c.getLocal("idx2"), - ), - - c.call( - fPrefix + "_mul", - W, - c.getLocal("pwm"), - W, - ), - - c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), - c.br(0) - )), - - c.setLocal("k", c.i32_add(c.getLocal("k"), c.getLocal("m"))), - c.br(0) - )), - - c.setLocal("s", c.i32_add(c.getLocal("s"), c.i32_const(1))), - c.br(0) - )), - c.call( - prefix + "__fftFinal", - c.getLocal("px"), - c.getLocal("bits"), - c.getLocal("reverse"), - c.getLocal("mulFactor") - ) - ); - } - - - function buildFinalInverse() { - const f = module.addFunction(prefix+"__fftFinal"); - f.addParam("px", "i32"); - f.addParam("bits", "i32"); - f.addParam("reverse", "i32"); - f.addParam("mulFactor", "i32"); - f.addLocal("n", "i32"); - f.addLocal("ndiv2", "i32"); - f.addLocal("pInv2", "i32"); - f.addLocal("i", "i32"); - f.addLocal("mask", "i32"); - f.addLocal("idx1", "i32"); - f.addLocal("idx2", "i32"); - - const c = f.getCodeBuilder(); - - const T = c.i32_const(module.alloc(n8g)); - - f.addCode( - c.if( - c.i32_and( - c.i32_eqz(c.getLocal("reverse")), - c.call(fPrefix + "_isOne", c.getLocal("mulFactor")) - ), - c.ret([]) - ), - c.setLocal("n", c.i32_shl( c.i32_const(1), c.getLocal("bits"))), - - c.setLocal("mask", c.i32_sub( c.getLocal("n") , c.i32_const(1))), - c.setLocal("i", c.i32_const(1)), - c.setLocal( - "ndiv2", - c.i32_shr_u( - c.getLocal("n"), - c.i32_const(1) - ) - ), - c.block(c.loop( - c.br_if( - 1, - c.i32_ge_u( - c.getLocal("i"), - c.getLocal("ndiv2") - ) - ), - - c.setLocal("idx1", - c.i32_add( - c.getLocal("px"), - c.i32_mul( - c.getLocal("i"), - c.i32_const(n8g) - ) - ) - ), - - c.setLocal("idx2", - c.i32_add( - c.getLocal("px"), - c.i32_mul( - c.i32_sub( - c.getLocal("n"), - c.getLocal("i") - ), - c.i32_const(n8g) - ) - ) - ), - - c.if( - c.getLocal("reverse"), - c.if( - c.call(fPrefix + "_isOne", c.getLocal("mulFactor")), - [ - ...c.call(gPrefix + "_copy", c.getLocal("idx1"), T), - ...c.call(gPrefix + "_copy", c.getLocal("idx2") , c.getLocal("idx1") ), - ...c.call(gPrefix + "_copy", T , c.getLocal("idx2")), - ], - [ - ...c.call(gPrefix + "_copy", c.getLocal("idx1"), T), - ...c.call(opGtimesF , c.getLocal("idx2") , c.getLocal("mulFactor"), c.getLocal("idx1") ), - ...c.call(opGtimesF , T , c.getLocal("mulFactor"), c.getLocal("idx2")), - ] - ), - c.if( - c.call(fPrefix + "_isOne", c.getLocal("mulFactor")), - [ - // Do nothing (It should not be here) - ], - [ - ...c.call(opGtimesF , c.getLocal("idx1") , c.getLocal("mulFactor"), c.getLocal("idx1") ), - ...c.call(opGtimesF , c.getLocal("idx2") , c.getLocal("mulFactor"), c.getLocal("idx2")), - ] - ) - ), - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), - - c.br(0) - )), - - c.if( - c.call(fPrefix + "_isOne", c.getLocal("mulFactor")), - [ - // Do nothing (It should not be here) - ], - [ - ...c.call(opGtimesF, c.getLocal("px") , c.getLocal("mulFactor"), c.getLocal("px")), - ...c.setLocal("idx2", - c.i32_add( - c.getLocal("px"), - c.i32_mul( - c.getLocal("ndiv2"), - c.i32_const(n8g) - ) - ) - ), - ...c.call(opGtimesF, c.getLocal("idx2"),c.getLocal("mulFactor"), c.getLocal("idx2")) - ] - ) - ); - } - - function buildReversePermutation() { - const f = module.addFunction(prefix+"__reversePermutation"); - f.addParam("px", "i32"); - f.addParam("bits", "i32"); - f.addLocal("n", "i32"); - f.addLocal("i", "i32"); - f.addLocal("ri", "i32"); - f.addLocal("idx1", "i32"); - f.addLocal("idx2", "i32"); - - const c = f.getCodeBuilder(); - - const T = c.i32_const(module.alloc(n8g)); - - f.addCode( - c.setLocal("n", c.i32_shl( c.i32_const(1), c.getLocal("bits"))), - c.setLocal("i", c.i32_const(0)), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("i"), - c.getLocal("n") - ) - ), - - c.setLocal("idx1", - c.i32_add( - c.getLocal("px"), - c.i32_mul( - c.getLocal("i"), - c.i32_const(n8g) - ) - ) - ), - - c.setLocal("ri", c.call(prefix + "__rev", c.getLocal("i"), c.getLocal("bits"))), - - c.setLocal("idx2", - c.i32_add( - c.getLocal("px"), - c.i32_mul( - c.getLocal("ri"), - c.i32_const(n8g) - ) - ) - ), - - c.if( - c.i32_lt_u( - c.getLocal("i"), - c.getLocal("ri") - ), - [ - ...c.call(gPrefix + "_copy", c.getLocal("idx1"), T), - ...c.call(gPrefix + "_copy", c.getLocal("idx2") , c.getLocal("idx1")), - ...c.call(gPrefix + "_copy", T , c.getLocal("idx2")) - ] - ), - - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), - - c.br(0) - )) - ); - } - - function buildRev() { - const f = module.addFunction(prefix+"__rev"); - f.addParam("x", "i32"); - f.addParam("bits", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.i32_rotl( - c.i32_add( - c.i32_add( - c.i32_shl( - c.i32_load8_u( - c.i32_and( - c.getLocal("x"), - c.i32_const(0xFF) - ), - REVTABLE, - 0 - ), - c.i32_const(24) - ), - c.i32_shl( - c.i32_load8_u( - c.i32_and( - c.i32_shr_u( - c.getLocal("x"), - c.i32_const(8) - ), - c.i32_const(0xFF) - ), - REVTABLE, - 0 - ), - c.i32_const(16) - ), - ), - c.i32_add( - c.i32_shl( - c.i32_load8_u( - c.i32_and( - c.i32_shr_u( - c.getLocal("x"), - c.i32_const(16) - ), - c.i32_const(0xFF) - ), - REVTABLE, - 0 - ), - c.i32_const(8) - ), - c.i32_load8_u( - c.i32_and( - c.i32_shr_u( - c.getLocal("x"), - c.i32_const(24) - ), - c.i32_const(0xFF) - ), - REVTABLE, - 0 - ), - ) - ), - c.getLocal("bits") - ) - ); - } - - - function buildFFTJoin() { - const f = module.addFunction(prefix+"_fftJoin"); - f.addParam("pBuff1", "i32"); - f.addParam("pBuff2", "i32"); - f.addParam("n", "i32"); - f.addParam("first", "i32"); - f.addParam("inc", "i32"); - f.addLocal("idx1", "i32"); - f.addLocal("idx2", "i32"); - f.addLocal("i", "i32"); - - const c = f.getCodeBuilder(); - - const W = c.i32_const(module.alloc(n8f)); - const T = c.i32_const(module.alloc(n8g)); - const U = c.i32_const(module.alloc(n8g)); - - f.addCode( - c.call( fPrefix + "_copy", c.getLocal("first"), W), - c.setLocal("i", c.i32_const(0)), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("i"), - c.getLocal("n") - ) - ), - - c.setLocal( - "idx1", - c.i32_add( - c.getLocal("pBuff1"), - c.i32_mul( - c.getLocal("i"), - c.i32_const(n8g) - ) - ) - ), - - c.setLocal( - "idx2", - c.i32_add( - c.getLocal("pBuff2"), - c.i32_mul( - c.getLocal("i"), - c.i32_const(n8g) - ) - ) - ), - - c.call( - opGtimesF, - c.getLocal("idx2"), - W, - T - ), - - c.call( - gPrefix + "_copy", - c.getLocal("idx1"), - U - ), - - c.call( - gPrefix + "_add", - U, - T, - c.getLocal("idx1"), - ), - - c.call( - gPrefix + "_sub", - U, - T, - c.getLocal("idx2"), - ), - - c.call( - fPrefix + "_mul", - W, - c.getLocal("inc"), - W, - ), - - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - ); - } - - - function buildFFTJoinExt() { - const f = module.addFunction(prefix+"_fftJoinExt"); - f.addParam("pBuff1", "i32"); - f.addParam("pBuff2", "i32"); - f.addParam("n", "i32"); - f.addParam("first", "i32"); - f.addParam("inc", "i32"); - f.addParam("totalBits", "i32"); - f.addLocal("idx1", "i32"); - f.addLocal("idx2", "i32"); - f.addLocal("i", "i32"); - f.addLocal("pShiftToM", "i32"); - - const c = f.getCodeBuilder(); - - const W = c.i32_const(module.alloc(n8f)); - const U = c.i32_const(module.alloc(n8g)); - - f.addCode( - - c.setLocal("pShiftToM", - c.i32_add( - c.i32_const(SHIFT_TO_M), - c.i32_mul( - c.getLocal("totalBits"), - c.i32_const(n8f) - ) - ) - ), - - - c.call( fPrefix + "_copy", c.getLocal("first"), W), - c.setLocal("i", c.i32_const(0)), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("i"), - c.getLocal("n") - ) - ), - - c.setLocal( - "idx1", - c.i32_add( - c.getLocal("pBuff1"), - c.i32_mul( - c.getLocal("i"), - c.i32_const(n8g) - ) - ) - ), - - c.setLocal( - "idx2", - c.i32_add( - c.getLocal("pBuff2"), - c.i32_mul( - c.getLocal("i"), - c.i32_const(n8g) - ) - ) - ), - - c.call( - gPrefix + "_add", - c.getLocal("idx1"), - c.getLocal("idx2"), - U - ), - - c.call( - opGtimesF, - c.getLocal("idx2"), - c.getLocal("pShiftToM"), - c.getLocal("idx2") - ), - - c.call( - gPrefix + "_add", - c.getLocal("idx1"), - c.getLocal("idx2"), - c.getLocal("idx2") - ), - - c.call( - opGtimesF, - c.getLocal("idx2"), - W, - c.getLocal("idx2"), - ), - - c.call( - gPrefix + "_copy", - U, - c.getLocal("idx1") - ), - - c.call( - fPrefix + "_mul", - W, - c.getLocal("inc"), - W - ), - - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - ); - } - - function buildFFTJoinExtInv() { - const f = module.addFunction(prefix+"_fftJoinExtInv"); - f.addParam("pBuff1", "i32"); - f.addParam("pBuff2", "i32"); - f.addParam("n", "i32"); - f.addParam("first", "i32"); - f.addParam("inc", "i32"); - f.addParam("totalBits", "i32"); - f.addLocal("idx1", "i32"); - f.addLocal("idx2", "i32"); - f.addLocal("i", "i32"); - f.addLocal("pShiftToM", "i32"); - f.addLocal("pSConst", "i32"); - - const c = f.getCodeBuilder(); - - const W = c.i32_const(module.alloc(n8f)); - const U = c.i32_const(module.alloc(n8g)); - - f.addCode( - - c.setLocal("pShiftToM", - c.i32_add( - c.i32_const(SHIFT_TO_M), - c.i32_mul( - c.getLocal("totalBits"), - c.i32_const(n8f) - ) - ) - ), - c.setLocal("pSConst", - c.i32_add( - c.i32_const(SCONST), - c.i32_mul( - c.getLocal("totalBits"), - c.i32_const(n8f) - ) - ) - ), - - - c.call( fPrefix + "_copy", c.getLocal("first"), W), - c.setLocal("i", c.i32_const(0)), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("i"), - c.getLocal("n") - ) - ), - - c.setLocal( - "idx1", - c.i32_add( - c.getLocal("pBuff1"), - c.i32_mul( - c.getLocal("i"), - c.i32_const(n8g) - ) - ) - ), - - c.setLocal( - "idx2", - c.i32_add( - c.getLocal("pBuff2"), - c.i32_mul( - c.getLocal("i"), - c.i32_const(n8g) - ) - ) - ), - - c.call( - opGtimesF, - c.getLocal("idx2"), - W, - U - ), - - c.call( - gPrefix + "_sub", - c.getLocal("idx1"), - U, - c.getLocal("idx2"), - ), - - c.call( - opGtimesF, - c.getLocal("idx2"), - c.getLocal("pSConst"), - c.getLocal("idx2") - ), - - c.call( - opGtimesF, - c.getLocal("idx1"), - c.getLocal("pShiftToM"), - c.getLocal("idx1") - ), - - c.call( - gPrefix + "_sub", - U, - c.getLocal("idx1"), - c.getLocal("idx1") - ), - - c.call( - opGtimesF, - c.getLocal("idx1"), - c.getLocal("pSConst"), - c.getLocal("idx1") - ), - - c.call( - fPrefix + "_mul", - W, - c.getLocal("inc"), - W - ), - - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - ); - } - - - - function buildPrepareLagrangeEvaluation() { - const f = module.addFunction(prefix+"_prepareLagrangeEvaluation"); - f.addParam("pBuff1", "i32"); - f.addParam("pBuff2", "i32"); - f.addParam("n", "i32"); - f.addParam("first", "i32"); - f.addParam("inc", "i32"); - f.addParam("totalBits", "i32"); - f.addLocal("idx1", "i32"); - f.addLocal("idx2", "i32"); - f.addLocal("i", "i32"); - f.addLocal("pShiftToM", "i32"); - f.addLocal("pSConst", "i32"); - - const c = f.getCodeBuilder(); - - const W = c.i32_const(module.alloc(n8f)); - const U = c.i32_const(module.alloc(n8g)); - - f.addCode( - - c.setLocal("pShiftToM", - c.i32_add( - c.i32_const(SHIFT_TO_M), - c.i32_mul( - c.getLocal("totalBits"), - c.i32_const(n8f) - ) - ) - ), - c.setLocal("pSConst", - c.i32_add( - c.i32_const(SCONST), - c.i32_mul( - c.getLocal("totalBits"), - c.i32_const(n8f) - ) - ) - ), - - - c.call( fPrefix + "_copy", c.getLocal("first"), W), - c.setLocal("i", c.i32_const(0)), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("i"), - c.getLocal("n") - ) - ), - - c.setLocal( - "idx1", - c.i32_add( - c.getLocal("pBuff1"), - c.i32_mul( - c.getLocal("i"), - c.i32_const(n8g) - ) - ) - ), - - c.setLocal( - "idx2", - c.i32_add( - c.getLocal("pBuff2"), - c.i32_mul( - c.getLocal("i"), - c.i32_const(n8g) - ) - ) - ), - - - c.call( - opGtimesF, - c.getLocal("idx1"), - c.getLocal("pShiftToM"), - U - ), - - c.call( - gPrefix + "_sub", - c.getLocal("idx2"), - U, - U - ), - - c.call( - gPrefix + "_sub", - c.getLocal("idx1"), - c.getLocal("idx2"), - c.getLocal("idx2"), - ), - - c.call( - opGtimesF, - U, - c.getLocal("pSConst"), - c.getLocal("idx1"), - ), - - c.call( - opGtimesF, - c.getLocal("idx2"), - W, - c.getLocal("idx2"), - ), - - c.call( - fPrefix + "_mul", - W, - c.getLocal("inc"), - W - ), - - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - ); - } - - function buildFFTMix() { - const f = module.addFunction(prefix+"_fftMix"); - f.addParam("pBuff", "i32"); - f.addParam("n", "i32"); - f.addParam("exp", "i32"); - f.addLocal("nGroups", "i32"); - f.addLocal("nPerGroup", "i32"); - f.addLocal("nPerGroupDiv2", "i32"); - f.addLocal("pairOffset", "i32"); - f.addLocal("idx1", "i32"); - f.addLocal("idx2", "i32"); - f.addLocal("i", "i32"); - f.addLocal("j", "i32"); - f.addLocal("pwm", "i32"); - - const c = f.getCodeBuilder(); - - const W = c.i32_const(module.alloc(n8f)); - const T = c.i32_const(module.alloc(n8g)); - const U = c.i32_const(module.alloc(n8g)); - - f.addCode( - c.setLocal("nPerGroup", c.i32_shl(c.i32_const(1), c.getLocal("exp"))), - c.setLocal("nPerGroupDiv2", c.i32_shr_u(c.getLocal("nPerGroup"), c.i32_const(1))), - c.setLocal("nGroups", c.i32_shr_u(c.getLocal("n"), c.getLocal("exp"))), - c.setLocal("pairOffset", c.i32_mul(c.getLocal("nPerGroupDiv2"), c.i32_const(n8g))), - c.setLocal("pwm", - c.i32_add( - c.i32_const(ROOTs), - c.i32_mul( - c.getLocal("exp"), - c.i32_const(n8f) - ) - ) - ), - c.setLocal("i", c.i32_const(0)), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("i"), - c.getLocal("nGroups") - ) - ), - c.call( fPrefix + "_one", W), - c.setLocal("j", c.i32_const(0)), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("j"), - c.getLocal("nPerGroupDiv2") - ) - ), - - c.setLocal( - "idx1", - c.i32_add( - c.getLocal("pBuff"), - c.i32_mul( - c.i32_add( - c.i32_mul( - c.getLocal("i"), - c.getLocal("nPerGroup") - ), - c.getLocal("j") - ), - c.i32_const(n8g) - ) - ) - ), - - c.setLocal( - "idx2", - c.i32_add( - c.getLocal("idx1"), - c.getLocal("pairOffset") - ) - ), - - c.call( - opGtimesF, - c.getLocal("idx2"), - W, - T - ), - - c.call( - gPrefix + "_copy", - c.getLocal("idx1"), - U - ), - - c.call( - gPrefix + "_add", - U, - T, - c.getLocal("idx1"), - ), - - c.call( - gPrefix + "_sub", - U, - T, - c.getLocal("idx2"), - ), - - c.call( - fPrefix + "_mul", - W, - c.getLocal("pwm"), - W, - ), - c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), - c.br(0) - )), - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - ); - } - - - // Reverse all and multiply by factor - function buildFFTFinal() { - const f = module.addFunction(prefix+"_fftFinal"); - f.addParam("pBuff", "i32"); - f.addParam("n", "i32"); - f.addParam("factor", "i32"); - f.addLocal("idx1", "i32"); - f.addLocal("idx2", "i32"); - f.addLocal("i", "i32"); - f.addLocal("ndiv2", "i32"); - - const c = f.getCodeBuilder(); - - const T = c.i32_const(module.alloc(n8g)); - - f.addCode( - c.setLocal("ndiv2", c.i32_shr_u(c.getLocal("n"), c.i32_const(1))), - c.if( - c.i32_and( - c.getLocal("n"), - c.i32_const(1) - ), - c.call( - opGtimesF, - c.i32_add( - c.getLocal("pBuff"), - c.i32_mul( - c.getLocal("ndiv2"), - c.i32_const(n8g) - ) - ), - c.getLocal("factor"), - c.i32_add( - c.getLocal("pBuff"), - c.i32_mul( - c.getLocal("ndiv2"), - c.i32_const(n8g) - ) - ), - ), - ), - c.setLocal("i", c.i32_const(0)), - c.block(c.loop( - c.br_if( - 1, - c.i32_ge_u( - c.getLocal("i"), - c.getLocal("ndiv2") - ) - ), - - c.setLocal( - "idx1", - c.i32_add( - c.getLocal("pBuff"), - c.i32_mul( - c.getLocal("i"), - c.i32_const(n8g) - ) - ) - ), - - c.setLocal( - "idx2", - c.i32_add( - c.getLocal("pBuff"), - c.i32_mul( - c.i32_sub( - c.i32_sub( - c.getLocal("n"), - c.i32_const(1) - ), - c.getLocal("i") - ), - c.i32_const(n8g) - ) - ) - ), - - c.call( - opGtimesF, - c.getLocal("idx2"), - c.getLocal("factor"), - T - ), - - c.call( - opGtimesF, - c.getLocal("idx1"), - c.getLocal("factor"), - c.getLocal("idx2"), - ), - - c.call( - gPrefix + "_copy", - T, - c.getLocal("idx1"), - ), - - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - ); - } - - buildRev(); - buildReversePermutation(); - buildFinalInverse(); - buildRawFFT(); - buildLog2(); - buildFFT(); - buildIFFT(); - buildFFTJoin(); - buildFFTJoinExt(); - buildFFTJoinExtInv(); - buildFFTMix(); - buildFFTFinal(); - buildPrepareLagrangeEvaluation(); - - module.exportFunction(prefix+"_fft"); - module.exportFunction(prefix+"_ifft"); - module.exportFunction(prefix+"_rawfft"); - module.exportFunction(prefix+"_fftJoin"); - module.exportFunction(prefix+"_fftJoinExt"); - module.exportFunction(prefix+"_fftJoinExtInv"); - module.exportFunction(prefix+"_fftMix"); - module.exportFunction(prefix+"_fftFinal"); - module.exportFunction(prefix+"_prepareLagrangeEvaluation"); - -}; - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -var build_pol = function buildPol(module, prefix, prefixField) { - - const n64 = module.modules[prefixField].n64; - const n8 = n64*8; - - - function buildZero() { - const f = module.addFunction(prefix+"_zero"); - f.addParam("px", "i32"); - f.addParam("n", "i32"); - f.addLocal("lastp", "i32"); - f.addLocal("p", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.setLocal("p", c.getLocal("px")), - c.setLocal( - "lastp", - c.i32_add( - c.getLocal("px"), - c.i32_mul( - c.getLocal("n"), - c.i32_const(n8) - ) - ) - ), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("p"), - c.getLocal("lastp") - ) - ), - c.call(prefixField + "_zero", c.getLocal("p")), - c.setLocal("p", c.i32_add(c.getLocal("p"), c.i32_const(n8))), - c.br(0) - )) - ); - } - - function buildConstructLC() { - const f = module.addFunction(prefix+"_constructLC"); - f.addParam("ppolynomials", "i32"); - f.addParam("psignals", "i32"); - f.addParam("nSignals", "i32"); - f.addParam("pres", "i32"); - f.addLocal("i", "i32"); - f.addLocal("j", "i32"); - f.addLocal("pp", "i32"); - f.addLocal("ps", "i32"); - f.addLocal("pd", "i32"); - f.addLocal("ncoefs", "i32"); - - const c = f.getCodeBuilder(); - - const aux = c.i32_const(module.alloc(n8)); - - f.addCode( - c.setLocal("i", c.i32_const(0)), - c.setLocal("pp", c.getLocal("ppolynomials")), - c.setLocal("ps", c.getLocal("psignals")), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("i"), - c.getLocal("nSignals") - ) - ), - - c.setLocal("ncoefs", c.i32_load(c.getLocal("pp"))), - c.setLocal("pp", c.i32_add(c.getLocal("pp"), c.i32_const(4))), - - c.setLocal("j", c.i32_const(0)), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("j"), - c.getLocal("ncoefs") - ) - ), - - c.setLocal( - "pd", - c.i32_add( - c.getLocal("pres"), - c.i32_mul( - c.i32_load(c.getLocal("pp")), - c.i32_const(n8) - ) - ) - ), - - c.setLocal("pp", c.i32_add(c.getLocal("pp"), c.i32_const(4))), - - - c.call( - prefixField + "_mul", - c.getLocal("ps"), - c.getLocal("pp"), - aux - ), - - c.call( - prefixField + "_add", - aux, - c.getLocal("pd"), - c.getLocal("pd") - ), - - c.setLocal("pp", c.i32_add(c.getLocal("pp"), c.i32_const(n8))), - c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), - c.br(0) - )), - - c.setLocal("ps", c.i32_add(c.getLocal("ps"), c.i32_const(n8))), - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - ); - - } - - buildZero(); - buildConstructLC(); - - - module.exportFunction(prefix + "_zero"); - module.exportFunction(prefix + "_constructLC"); - - return prefix; - - - - -}; - -var build_qap = function buildQAP(module, prefix, prefixField) { - - const n64 = module.modules[prefixField].n64; - const n8 = n64*8; - - - function buildBuildABC() { - const f = module.addFunction(prefix+"_buildABC"); - f.addParam("pCoefs", "i32"); - f.addParam("nCoefs", "i32"); - f.addParam("pWitness", "i32"); - f.addParam("pA", "i32"); - f.addParam("pB", "i32"); - f.addParam("pC", "i32"); - f.addParam("offsetOut", "i32"); - f.addParam("nOut", "i32"); - f.addParam("offsetWitness", "i32"); - f.addParam("nWitness", "i32"); - f.addLocal("it", "i32"); - f.addLocal("ita", "i32"); - f.addLocal("itb", "i32"); - f.addLocal("last", "i32"); - f.addLocal("m", "i32"); - f.addLocal("c", "i32"); - f.addLocal("s", "i32"); - f.addLocal("pOut", "i32"); - - const c = f.getCodeBuilder(); - - const aux = c.i32_const(module.alloc(n8)); - - f.addCode( - - // Set output a and b to 0 - c.setLocal("ita", c.getLocal("pA")), - c.setLocal("itb", c.getLocal("pB")), - c.setLocal( - "last", - c.i32_add( - c.getLocal("pA"), - c.i32_mul( - c.getLocal("nOut"), - c.i32_const(n8) - ) - ) - ), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("ita"), - c.getLocal("last") - ) - ), - c.call(prefixField + "_zero", c.getLocal("ita")), - c.call(prefixField + "_zero", c.getLocal("itb")), - c.setLocal("ita", c.i32_add(c.getLocal("ita"), c.i32_const(n8))), - c.setLocal("itb", c.i32_add(c.getLocal("itb"), c.i32_const(n8))), - c.br(0) - )), - - - c.setLocal("it", c.getLocal("pCoefs")), - c.setLocal( - "last", - c.i32_add( - c.getLocal("pCoefs"), - c.i32_mul( - c.getLocal("nCoefs"), - c.i32_const(n8+12) - ) - ) - ), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("it"), - c.getLocal("last") - ) - ), - c.setLocal( - "s", - c.i32_load(c.getLocal("it"), 8) - ), - c.if( - c.i32_or( - c.i32_lt_u( - c.getLocal("s"), - c.getLocal("offsetWitness"), - ), - c.i32_ge_u( - c.getLocal("s"), - c.i32_add( - c.getLocal("offsetWitness"), - c.getLocal("nWitness"), - ) - ) - ), - [ - ...c.setLocal("it", c.i32_add(c.getLocal("it"), c.i32_const(n8+12))), - ...c.br(1) - ] - ), - - c.setLocal( - "m", - c.i32_load(c.getLocal("it")) - ), - c.if( - c.i32_eq(c.getLocal("m"), c.i32_const(0)), - c.setLocal("pOut", c.getLocal("pA")), - c.if( - c.i32_eq(c.getLocal("m"), c.i32_const(1)), - c.setLocal("pOut", c.getLocal("pB")), - [ - ...c.setLocal("it", c.i32_add(c.getLocal("it"), c.i32_const(n8+12))), - ...c.br(1) - ] - ) - ), - c.setLocal( - "c", - c.i32_load(c.getLocal("it"), 4) - ), - c.if( - c.i32_or( - c.i32_lt_u( - c.getLocal("c"), - c.getLocal("offsetOut"), - ), - c.i32_ge_u( - c.getLocal("c"), - c.i32_add( - c.getLocal("offsetOut"), - c.getLocal("nOut"), - ) - ) - ), - [ - ...c.setLocal("it", c.i32_add(c.getLocal("it"), c.i32_const(n8+12))), - ...c.br(1) - ] - ), - c.setLocal( - "pOut", - c.i32_add( - c.getLocal("pOut"), - c.i32_mul( - c.i32_sub( - c.getLocal("c"), - c.getLocal("offsetOut") - ), - c.i32_const(n8) - ) - ) - ), - c.call( - prefixField + "_mul", - c.i32_add( - c.getLocal("pWitness"), - c.i32_mul( - c.i32_sub(c.getLocal("s"), c.getLocal("offsetWitness")), - c.i32_const(n8) - ) - ), - c.i32_add( c.getLocal("it"), c.i32_const(12)), - aux - ), - c.call( - prefixField + "_add", - c.getLocal("pOut"), - aux, - c.getLocal("pOut"), - ), - c.setLocal("it", c.i32_add(c.getLocal("it"), c.i32_const(n8+12))), - c.br(0) - )), - - c.setLocal("ita", c.getLocal("pA")), - c.setLocal("itb", c.getLocal("pB")), - c.setLocal("it", c.getLocal("pC")), - c.setLocal( - "last", - c.i32_add( - c.getLocal("pA"), - c.i32_mul( - c.getLocal("nOut"), - c.i32_const(n8) - ) - ) - ), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("ita"), - c.getLocal("last") - ) - ), - c.call( - prefixField + "_mul", - c.getLocal("ita"), - c.getLocal("itb"), - c.getLocal("it") - ), - c.setLocal("ita", c.i32_add(c.getLocal("ita"), c.i32_const(n8))), - c.setLocal("itb", c.i32_add(c.getLocal("itb"), c.i32_const(n8))), - c.setLocal("it", c.i32_add(c.getLocal("it"), c.i32_const(n8))), - c.br(0) - )), - - ); - } - - function buildJoinABC() { - const f = module.addFunction(prefix+"_joinABC"); - f.addParam("pA", "i32"); - f.addParam("pB", "i32"); - f.addParam("pC", "i32"); - f.addParam("n", "i32"); - f.addParam("pP", "i32"); - f.addLocal("ita", "i32"); - f.addLocal("itb", "i32"); - f.addLocal("itc", "i32"); - f.addLocal("itp", "i32"); - f.addLocal("last", "i32"); - - const c = f.getCodeBuilder(); - - const aux = c.i32_const(module.alloc(n8)); - - f.addCode( - c.setLocal("ita", c.getLocal("pA")), - c.setLocal("itb", c.getLocal("pB")), - c.setLocal("itc", c.getLocal("pC")), - c.setLocal("itp", c.getLocal("pP")), - c.setLocal( - "last", - c.i32_add( - c.getLocal("pA"), - c.i32_mul( - c.getLocal("n"), - c.i32_const(n8) - ) - ) - ), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("ita"), - c.getLocal("last") - ) - ), - c.call( - prefixField + "_mul", - c.getLocal("ita"), - c.getLocal("itb"), - aux - ), - c.call( - prefixField + "_sub", - aux, - c.getLocal("itc"), - c.getLocal("itp"), - ), - c.setLocal("ita", c.i32_add(c.getLocal("ita"), c.i32_const(n8))), - c.setLocal("itb", c.i32_add(c.getLocal("itb"), c.i32_const(n8))), - c.setLocal("itc", c.i32_add(c.getLocal("itc"), c.i32_const(n8))), - c.setLocal("itp", c.i32_add(c.getLocal("itp"), c.i32_const(n8))), - c.br(0) - )) - ); - } - - function buildBatchAdd() { - const f = module.addFunction(prefix+"_batchAdd"); - f.addParam("pa", "i32"); - f.addParam("pb", "i32"); - f.addParam("n", "i32"); - f.addParam("pr", "i32"); - f.addLocal("ita", "i32"); - f.addLocal("itb", "i32"); - f.addLocal("itr", "i32"); - f.addLocal("last", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.setLocal("ita", c.getLocal("pa")), - c.setLocal("itb", c.getLocal("pb")), - c.setLocal("itr", c.getLocal("pr")), - c.setLocal( - "last", - c.i32_add( - c.getLocal("pa"), - c.i32_mul( - c.getLocal("n"), - c.i32_const(n8) - ) - ) - ), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("ita"), - c.getLocal("last") - ) - ), - c.call( - prefixField + "_add", - c.getLocal("ita"), - c.getLocal("itb"), - c.getLocal("itr"), - ), - c.setLocal("ita", c.i32_add(c.getLocal("ita"), c.i32_const(n8))), - c.setLocal("itb", c.i32_add(c.getLocal("itb"), c.i32_const(n8))), - c.setLocal("itr", c.i32_add(c.getLocal("itr"), c.i32_const(n8))), - c.br(0) - )) - ); - } - - buildBuildABC(); - buildJoinABC(); - buildBatchAdd(); - - module.exportFunction(prefix + "_buildABC"); - module.exportFunction(prefix + "_joinABC"); - module.exportFunction(prefix + "_batchAdd"); - - return prefix; - -}; - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -var build_applykey = function buildApplyKey(module, fnName, gPrefix, frPrefix, sizeGIn, sizeGOut, sizeF, opGtimesF) { - - const f = module.addFunction(fnName); - f.addParam("pIn", "i32"); - f.addParam("n", "i32"); - f.addParam("pFirst", "i32"); - f.addParam("pInc", "i32"); - f.addParam("pOut", "i32"); - f.addLocal("pOldFree", "i32"); - f.addLocal("i", "i32"); - f.addLocal("pFrom", "i32"); - f.addLocal("pTo", "i32"); - - const c = f.getCodeBuilder(); - - const t = c.i32_const(module.alloc(sizeF)); - - f.addCode( - c.setLocal("pFrom", c.getLocal("pIn")), - c.setLocal("pTo", c.getLocal("pOut")), - ); - - // t = first - f.addCode( - c.call( - frPrefix + "_copy", - c.getLocal("pFirst"), - t - ) - ); - f.addCode( - c.setLocal("i", c.i32_const(0)), - c.block(c.loop( - c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), - - c.call( - opGtimesF, - c.getLocal("pFrom"), - t, - c.getLocal("pTo") - ), - c.setLocal("pFrom", c.i32_add(c.getLocal("pFrom"), c.i32_const(sizeGIn))), - c.setLocal("pTo", c.i32_add(c.getLocal("pTo"), c.i32_const(sizeGOut))), - - // t = t* inc - c.call( - frPrefix + "_mul", - t, - c.getLocal("pInc"), - t - ), - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - ); - - module.exportFunction(fnName); - -}; - -const bigInt$2 = BigIntegerExports; -const utils$6 = utils$b; - -const buildF1m$1 =build_f1m; -const buildF1$1 =build_f1; -const buildF2m$1 =build_f2m; -const buildF3m$1 =build_f3m; -const buildCurve$1 =build_curve_jacobian_a0; -const buildFFT$2 = build_fft; -const buildPol$1 = build_pol; -const buildQAP$1 = build_qap; -const buildApplyKey$1 = build_applykey; - -var build_bn128 = function buildBN128(module, _prefix) { - - const prefix = _prefix || "bn128"; - - if (module.modules[prefix]) return prefix; // already builded - - const q = bigInt$2("21888242871839275222246405745257275088696311157297823662689037894645226208583"); - const r = bigInt$2("21888242871839275222246405745257275088548364400416034343698204186575808495617"); - - - const n64 = Math.floor((q.minus(1).bitLength() - 1)/64) +1; - const n8 = n64*8; - const frsize = n8; - const f1size = n8; - const f2size = f1size * 2; - const ftsize = f1size * 12; - - const pr = module.alloc(utils$6.bigInt2BytesLE( r, frsize )); - - const f1mPrefix = buildF1m$1(module, q, "f1m"); - buildF1$1(module, r, "fr", "frm"); - - const pG1b = module.alloc(utils$6.bigInt2BytesLE( toMontgomery(bigInt$2(3)), f1size )); - const g1mPrefix = buildCurve$1(module, "g1m", "f1m", pG1b); - - buildFFT$2(module, "frm", "frm", "frm", "frm_mul"); - - buildPol$1(module, "pol", "frm"); - buildQAP$1(module, "qap", "frm"); - - const f2mPrefix = buildF2m$1(module, "f1m_neg", "f2m", "f1m"); - const pG2b = module.alloc([ - ...utils$6.bigInt2BytesLE( toMontgomery(bigInt$2("19485874751759354771024239261021720505790618469301721065564631296452457478373")), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(bigInt$2("266929791119991161246907387137283842545076965332900288569378510910307636690")), f1size ) - ]); - const g2mPrefix = buildCurve$1(module, "g2m", "f2m", pG2b); - - - function buildGTimesFr(fnName, opMul) { - const f = module.addFunction(fnName); - f.addParam("pG", "i32"); - f.addParam("pFr", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - const AUX = c.i32_const(module.alloc(n8)); - - f.addCode( - c.call("frm_fromMontgomery", c.getLocal("pFr"), AUX), - c.call( - opMul, - c.getLocal("pG"), - AUX, - c.i32_const(n8), - c.getLocal("pr") - ) - ); - - module.exportFunction(fnName); - } - buildGTimesFr("g1m_timesFr", "g1m_timesScalar"); - buildFFT$2(module, "g1m", "g1m", "frm", "g1m_timesFr"); - - buildGTimesFr("g2m_timesFr", "g2m_timesScalar"); - buildFFT$2(module, "g2m", "g2m", "frm", "g2m_timesFr"); - - buildGTimesFr("g1m_timesFrAffine", "g1m_timesScalarAffine"); - buildGTimesFr("g2m_timesFrAffine", "g2m_timesScalarAffine"); - - buildApplyKey$1(module, "frm_batchApplyKey", "fmr", "frm", n8, n8, n8, "frm_mul"); - buildApplyKey$1(module, "g1m_batchApplyKey", "g1m", "frm", n8*3, n8*3, n8, "g1m_timesFr"); - buildApplyKey$1(module, "g1m_batchApplyKeyMixed", "g1m", "frm", n8*2, n8*3, n8, "g1m_timesFrAffine"); - buildApplyKey$1(module, "g2m_batchApplyKey", "g2m", "frm", n8*2*3, n8*3*2, n8, "g2m_timesFr"); - buildApplyKey$1(module, "g2m_batchApplyKeyMixed", "g2m", "frm", n8*2*2, n8*3*2, n8, "g2m_timesFrAffine"); - - function toMontgomery(a) { - return bigInt$2(a).times( bigInt$2.one.shiftLeft(f1size*8)).mod(q); - } - - const G1gen = [ - bigInt$2("1"), - bigInt$2("2"), - bigInt$2.one - ]; - - const pG1gen = module.alloc( - [ - ...utils$6.bigInt2BytesLE( toMontgomery(G1gen[0]), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(G1gen[1]), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(G1gen[2]), f1size ), - ] - ); - - const G1zero = [ - bigInt$2.zero, - bigInt$2.one, - bigInt$2.zero - ]; - - const pG1zero = module.alloc( - [ - ...utils$6.bigInt2BytesLE( toMontgomery(G1zero[0]), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(G1zero[1]), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(G1zero[2]), f1size ) - ] - ); - - const G2gen = [ - [ - bigInt$2("10857046999023057135944570762232829481370756359578518086990519993285655852781"), - bigInt$2("11559732032986387107991004021392285783925812861821192530917403151452391805634"), - ],[ - bigInt$2("8495653923123431417604973247489272438418190587263600148770280649306958101930"), - bigInt$2("4082367875863433681332203403145435568316851327593401208105741076214120093531"), - ],[ - bigInt$2.one, - bigInt$2.zero, - ] - ]; - - const pG2gen = module.alloc( - [ - ...utils$6.bigInt2BytesLE( toMontgomery(G2gen[0][0]), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(G2gen[0][1]), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(G2gen[1][0]), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(G2gen[1][1]), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(G2gen[2][0]), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(G2gen[2][1]), f1size ), - ] - ); - - const G2zero = [ - [ - bigInt$2.zero, - bigInt$2.zero, - ],[ - bigInt$2.one, - bigInt$2.zero, - ],[ - bigInt$2.zero, - bigInt$2.zero, - ] - ]; - - const pG2zero = module.alloc( - [ - ...utils$6.bigInt2BytesLE( toMontgomery(G2zero[0][0]), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(G2zero[0][1]), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(G2zero[1][0]), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(G2zero[1][1]), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(G2zero[2][0]), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(G2zero[2][1]), f1size ), - ] - ); - - const pOneT = module.alloc([ - ...utils$6.bigInt2BytesLE( toMontgomery(1), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(0), f1size ), - ]); - - const pNonResidueF6 = module.alloc([ - ...utils$6.bigInt2BytesLE( toMontgomery(9), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery(1), f1size ), - ]); - - const pTwoInv = module.alloc([ - ...utils$6.bigInt2BytesLE( toMontgomery( bigInt$2(2).modInv(q)), f1size ), - ...utils$6.bigInt2BytesLE( bigInt$2(0), f1size ) - ]); - - const pAltBn128Twist = pNonResidueF6; - - const pTwistCoefB = module.alloc([ - ...utils$6.bigInt2BytesLE( toMontgomery("19485874751759354771024239261021720505790618469301721065564631296452457478373"), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery("266929791119991161246907387137283842545076965332900288569378510910307636690"), f1size ), - ]); - - function build_mulNR6() { - const f = module.addFunction(prefix + "_mulNR6"); - f.addParam("x", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call( - f2mPrefix + "_mul", - c.i32_const(pNonResidueF6), - c.getLocal("x"), - c.getLocal("pr") - ) - ); - } - build_mulNR6(); - - const f6mPrefix = buildF3m$1(module, prefix+"_mulNR6", "f6m", "f2m"); - - function build_mulNR12() { - const f = module.addFunction(prefix + "_mulNR12"); - f.addParam("x", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call( - f2mPrefix + "_mul", - c.i32_const(pNonResidueF6), - c.i32_add(c.getLocal("x"), c.i32_const(n8*4)), - c.getLocal("pr") - ), - c.call( - f2mPrefix + "_copy", - c.getLocal("x"), - c.i32_add(c.getLocal("pr"), c.i32_const(n8*2)), - ), - c.call( - f2mPrefix + "_copy", - c.i32_add(c.getLocal("x"), c.i32_const(n8*2)), - c.i32_add(c.getLocal("pr"), c.i32_const(n8*4)), - ) - ); - } - build_mulNR12(); - - const ftmPrefix = buildF2m$1(module, prefix+"_mulNR12", "ftm", f6mPrefix); - - - const ateLoopCount = bigInt$2("29793968203157093288"); - const ateLoopBitBytes = bits(ateLoopCount); - const pAteLoopBitBytes = module.alloc(ateLoopBitBytes); - - const ateCoefSize = 3 * f2size; - const ateNDblCoefs = ateLoopBitBytes.length-1; - const ateNAddCoefs = ateLoopBitBytes.reduce((acc, b) => acc + ( b!=0 ? 1 : 0) ,0); - const ateNCoefs = ateNAddCoefs + ateNDblCoefs + 1; - const prePSize = 3*2*n8; - const preQSize = 3*n8*2 + ateNCoefs*ateCoefSize; - - - module.modules[prefix] = { - n64: n64, - pG1gen: pG1gen, - pG1zero: pG1zero, - pG1b: pG1b, - pG2gen: pG2gen, - pG2zero: pG2zero, - pG2b: pG2b, - pq: module.modules["f1m"].pq, - pr: pr, - pOneT: pOneT, - prePSize: prePSize, - preQSize: preQSize, - r: r.toString(), - q: q.toString() - }; - - // console.log("PrePSize: " +prePSize); - // console.log("PreQSize: " +preQSize); - - const finalExpZ = bigInt$2("4965661367192848881"); - - function naf(n) { - let E = n; - const res = []; - while (E.gt(bigInt$2.zero)) { - if (E.isOdd()) { - const z = 2 - E.mod(4).toJSNumber(); - res.push( z ); - E = E.minus(z); - } else { - res.push( 0 ); - } - E = E.shiftRight(1); - } - return res; - } - - function bits(n) { - let E = n; - const res = []; - while (E.gt(bigInt$2.zero)) { - if (E.isOdd()) { - res.push( 1 ); - } else { - res.push( 0 ); - } - E = E.shiftRight(1); - } - return res; - } - - function buildPrepareG1() { - const f = module.addFunction(prefix+ "_prepareG1"); - f.addParam("pP", "i32"); - f.addParam("ppreP", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call(g1mPrefix + "_normalize", c.getLocal("pP"), c.getLocal("ppreP")), // TODO Remove if already in affine - ); - } - - function buildPrepAddStep() { - const f = module.addFunction(prefix+ "_prepAddStep"); - f.addParam("pQ", "i32"); - f.addParam("pR", "i32"); - f.addParam("pCoef", "i32"); - - const c = f.getCodeBuilder(); - - const X2 = c.getLocal("pQ"); - const Y2 = c.i32_add(c.getLocal("pQ"), c.i32_const(f2size)); - - const X1 = c.getLocal("pR"); - const Y1 = c.i32_add(c.getLocal("pR"), c.i32_const(f2size)); - const Z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*f2size)); - - const ELL_0 = c.getLocal("pCoef"); - const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); - const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); - - const D = ELL_VW; - const E = c.i32_const(module.alloc(f2size)); - const F = c.i32_const(module.alloc(f2size)); - const G = c.i32_const(module.alloc(f2size)); - const H = c.i32_const(module.alloc(f2size)); - const I = c.i32_const(module.alloc(f2size)); - const J = c.i32_const(module.alloc(f2size)); - const AUX = c.i32_const(module.alloc(f2size)); - - f.addCode( - // D = X1 - X2*Z1 - c.call(f2mPrefix + "_mul", X2, Z1, D), - c.call(f2mPrefix + "_sub", X1, D, D), - - // E = Y1 - Y2*Z1 - c.call(f2mPrefix + "_mul", Y2, Z1, E), - c.call(f2mPrefix + "_sub", Y1, E, E), - - // F = D^2 - c.call(f2mPrefix + "_square", D, F), - - // G = E^2 - c.call(f2mPrefix + "_square", E, G), - - // H = D*F - c.call(f2mPrefix + "_mul", D, F, H), - - // I = X1 * F - c.call(f2mPrefix + "_mul", X1, F, I), - - // J = H + Z1*G - (I+I) - c.call(f2mPrefix + "_add", I, I, AUX), - c.call(f2mPrefix + "_mul", Z1, G, J), - c.call(f2mPrefix + "_add", H, J, J), - c.call(f2mPrefix + "_sub", J, AUX, J), - - - // X3 (X1) = D*J - c.call(f2mPrefix + "_mul", D, J, X1), - - // Y3 (Y1) = E*(I-J)-(H*Y1) - c.call(f2mPrefix + "_mul", H, Y1, Y1), - c.call(f2mPrefix + "_sub", I, J, AUX), - c.call(f2mPrefix + "_mul", E, AUX, AUX), - c.call(f2mPrefix + "_sub", AUX, Y1, Y1), - - // Z3 (Z1) = Z1*H - c.call(f2mPrefix + "_mul", Z1, H, Z1), - - // ell_0 = xi * (E * X2 - D * Y2) - c.call(f2mPrefix + "_mul", D, Y2, AUX), - c.call(f2mPrefix + "_mul", E, X2, ELL_0), - c.call(f2mPrefix + "_sub", ELL_0, AUX, ELL_0), - c.call(f2mPrefix + "_mul", ELL_0, c.i32_const(pAltBn128Twist), ELL_0), - - - // ell_VV = - E (later: * xP) - c.call(f2mPrefix + "_neg", E, ELL_VV), - - // ell_VW = D (later: * yP ) - // Already assigned - - ); - } - - - - function buildPrepDoubleStep() { - const f = module.addFunction(prefix+ "_prepDblStep"); - f.addParam("pR", "i32"); - f.addParam("pCoef", "i32"); - - const c = f.getCodeBuilder(); - - const X1 = c.getLocal("pR"); - const Y1 = c.i32_add(c.getLocal("pR"), c.i32_const(f2size)); - const Z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*f2size)); - - const ELL_0 = c.getLocal("pCoef"); - const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); - const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); - - const A = c.i32_const(module.alloc(f2size)); - const B = c.i32_const(module.alloc(f2size)); - const C = c.i32_const(module.alloc(f2size)); - const D = c.i32_const(module.alloc(f2size)); - const E = c.i32_const(module.alloc(f2size)); - const F = c.i32_const(module.alloc(f2size)); - const G = c.i32_const(module.alloc(f2size)); - const H = c.i32_const(module.alloc(f2size)); - const I = c.i32_const(module.alloc(f2size)); - const J = c.i32_const(module.alloc(f2size)); - const E2 = c.i32_const(module.alloc(f2size)); - const AUX = c.i32_const(module.alloc(f2size)); - - f.addCode( - - // A = X1 * Y1 / 2 - c.call(f2mPrefix + "_mul", Y1, c.i32_const(pTwoInv), A), - c.call(f2mPrefix + "_mul", X1, A, A), - - // B = Y1^2 - c.call(f2mPrefix + "_square", Y1, B), - - // C = Z1^2 - c.call(f2mPrefix + "_square", Z1, C), - - // D = 3 * C - c.call(f2mPrefix + "_add", C, C, D), - c.call(f2mPrefix + "_add", D, C, D), - - // E = twist_b * D - c.call(f2mPrefix + "_mul", c.i32_const(pTwistCoefB), D, E), - - // F = 3 * E - c.call(f2mPrefix + "_add", E, E, F), - c.call(f2mPrefix + "_add", E, F, F), - - // G = (B+F)/2 - c.call(f2mPrefix + "_add", B, F, G), - c.call(f2mPrefix + "_mul", G, c.i32_const(pTwoInv), G), - - // H = (Y1+Z1)^2-(B+C) - c.call(f2mPrefix + "_add", B, C, AUX), - c.call(f2mPrefix + "_add", Y1, Z1, H), - c.call(f2mPrefix + "_square", H, H), - c.call(f2mPrefix + "_sub", H, AUX, H), - - // I = E-B - c.call(f2mPrefix + "_sub", E, B, I), - - // J = X1^2 - c.call(f2mPrefix + "_square", X1, J), - - // E_squared = E^2 - c.call(f2mPrefix + "_square", E, E2), - - // X3 (X1) = A * (B-F) - c.call(f2mPrefix + "_sub", B, F, AUX), - c.call(f2mPrefix + "_mul", A, AUX, X1), - - // Y3 (Y1) = G^2 - 3*E^2 - c.call(f2mPrefix + "_add", E2, E2, AUX), - c.call(f2mPrefix + "_add", E2, AUX, AUX), - c.call(f2mPrefix + "_square", G, Y1), - c.call(f2mPrefix + "_sub", Y1, AUX, Y1), - - // Z3 (Z1) = B * H - c.call(f2mPrefix + "_mul", B, H, Z1), - - // ell_0 = xi * I - c.call(f2mPrefix + "_mul", c.i32_const(pAltBn128Twist), I, ELL_0), - - // ell_VW = - H (later: * yP) - c.call(f2mPrefix + "_neg", H, ELL_VW), - - // ell_VV = 3*J (later: * xP) - c.call(f2mPrefix + "_add", J, J, ELL_VV), - c.call(f2mPrefix + "_add", J, ELL_VV, ELL_VV), - - ); - } - - function buildMulByQ() { - const f = module.addFunction(prefix + "_mulByQ"); - f.addParam("p1", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - const x = c.getLocal("p1"); - const y = c.i32_add(c.getLocal("p1"), c.i32_const(f2size)); - const z = c.i32_add(c.getLocal("p1"), c.i32_const(f2size*2)); - const x3 = c.getLocal("pr"); - const y3 = c.i32_add(c.getLocal("pr"), c.i32_const(f2size)); - const z3 = c.i32_add(c.getLocal("pr"), c.i32_const(f2size*2)); - - const MulByQX = c.i32_const(module.alloc([ - ...utils$6.bigInt2BytesLE( toMontgomery("21575463638280843010398324269430826099269044274347216827212613867836435027261"), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery("10307601595873709700152284273816112264069230130616436755625194854815875713954"), f1size ), - ])); - - const MulByQY = c.i32_const(module.alloc([ - ...utils$6.bigInt2BytesLE( toMontgomery("2821565182194536844548159561693502659359617185244120367078079554186484126554"), f1size ), - ...utils$6.bigInt2BytesLE( toMontgomery("3505843767911556378687030309984248845540243509899259641013678093033130930403"), f1size ), - ])); - - f.addCode( - // The frobeniusMap(1) in this field, is the conjugate - c.call(f2mPrefix + "_conjugate", x, x3), - c.call(f2mPrefix + "_mul", MulByQX, x3, x3), - c.call(f2mPrefix + "_conjugate", y, y3), - c.call(f2mPrefix + "_mul", MulByQY, y3, y3), - c.call(f2mPrefix + "_conjugate", z, z3), - ); - } - - - function buildPrepareG2() { - buildMulByQ(); - const f = module.addFunction(prefix+ "_prepareG2"); - f.addParam("pQ", "i32"); - f.addParam("ppreQ", "i32"); - f.addLocal("pCoef", "i32"); - f.addLocal("i", "i32"); - - const c = f.getCodeBuilder(); - - const QX = c.getLocal("pQ"); - c.i32_add( c.getLocal("pQ"), c.i32_const(f2size)); - c.i32_add( c.getLocal("pQ"), c.i32_const(f2size*2)); - - const pR = module.alloc(f2size*3); - const R = c.i32_const(pR); - const RX = c.i32_const(pR); - const RY = c.i32_const(pR+f2size); - const RZ = c.i32_const(pR+2*f2size); - - const cQX = c.i32_add( c.getLocal("ppreQ"), c.i32_const(0)); - const cQY = c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size)); - c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*2)); - - const pQ1 = module.alloc(f2size*3); - const Q1 = c.i32_const(pQ1); - - const pQ2 = module.alloc(f2size*3); - const Q2 = c.i32_const(pQ2); - c.i32_const(pQ2); - const Q2Y = c.i32_const(pQ2 + f2size); - c.i32_const(pQ2 + f2size*2); - - f.addCode( - c.call(g2mPrefix + "_normalize", QX, cQX), // TODO Remove if already in affine - c.call(f2mPrefix + "_copy", cQX, RX), - c.call(f2mPrefix + "_copy", cQY, RY), - c.call(f2mPrefix + "_one", RZ), - ); - - f.addCode( - c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), - c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), - c.block(c.loop( - - c.call(prefix + "_prepDblStep", R, c.getLocal("pCoef")), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - c.if( - c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), - [ - ...c.call(prefix + "_prepAddStep", cQX, R, c.getLocal("pCoef")), - ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - ] - ), - c.br_if(1, c.i32_eqz ( c.getLocal("i") )), - c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - ); - - f.addCode( - c.call(prefix + "_mulByQ", cQX, Q1), - c.call(prefix + "_mulByQ", Q1, Q2) - ); - - f.addCode( - c.call(f2mPrefix + "_neg", Q2Y, Q2Y), - - c.call(prefix + "_prepAddStep", Q1, R, c.getLocal("pCoef")), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - c.call(prefix + "_prepAddStep", Q2, R, c.getLocal("pCoef")), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - ); - } - - function buildMulBy024Old() { - const f = module.addFunction(prefix+ "__mulBy024Old"); - f.addParam("pEll0", "i32"); - f.addParam("pEllVW", "i32"); - f.addParam("pEllVV", "i32"); - f.addParam("pR", "i32"); // Result in F12 - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("pEll0"); - const x2 = c.getLocal("pEllVV"); - const x4 = c.getLocal("pEllVW"); - - const z0 = c.getLocal("pR"); - - const pAUX12 = module.alloc(ftsize); - const AUX12 = c.i32_const(pAUX12); - const AUX12_0 = c.i32_const(pAUX12); - const AUX12_2 = c.i32_const(pAUX12+f2size); - const AUX12_4 = c.i32_const(pAUX12+f2size*2); - const AUX12_6 = c.i32_const(pAUX12+f2size*3); - const AUX12_8 = c.i32_const(pAUX12+f2size*4); - const AUX12_10 = c.i32_const(pAUX12+f2size*5); - - f.addCode( - - c.call(f2mPrefix + "_copy", x0, AUX12_0), - c.call(f2mPrefix + "_zero", AUX12_2), - c.call(f2mPrefix + "_copy", x2, AUX12_4), - c.call(f2mPrefix + "_zero", AUX12_6), - c.call(f2mPrefix + "_copy", x4, AUX12_8), - c.call(f2mPrefix + "_zero", AUX12_10), - c.call(ftmPrefix + "_mul", AUX12, z0, z0), - ); - } - - function buildMulBy024() { - const f = module.addFunction(prefix+ "__mulBy024"); - f.addParam("pEll0", "i32"); - f.addParam("pEllVW", "i32"); - f.addParam("pEllVV", "i32"); - f.addParam("pR", "i32"); // Result in F12 - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("pEll0"); - const x2 = c.getLocal("pEllVV"); - const x4 = c.getLocal("pEllVW"); - - const z0 = c.getLocal("pR"); - const z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*n8)); - const z2 = c.i32_add(c.getLocal("pR"), c.i32_const(4*n8)); - const z3 = c.i32_add(c.getLocal("pR"), c.i32_const(6*n8)); - const z4 = c.i32_add(c.getLocal("pR"), c.i32_const(8*n8)); - const z5 = c.i32_add(c.getLocal("pR"), c.i32_const(10*n8)); - - const t0 = c.i32_const(module.alloc(f2size)); - const t1 = c.i32_const(module.alloc(f2size)); - const t2 = c.i32_const(module.alloc(f2size)); - const s0 = c.i32_const(module.alloc(f2size)); - const T3 = c.i32_const(module.alloc(f2size)); - const T4 = c.i32_const(module.alloc(f2size)); - const D0 = c.i32_const(module.alloc(f2size)); - const D2 = c.i32_const(module.alloc(f2size)); - const D4 = c.i32_const(module.alloc(f2size)); - const S1 = c.i32_const(module.alloc(f2size)); - const AUX = c.i32_const(module.alloc(f2size)); - - f.addCode( - - // D0 = z0 * x0; - c.call(f2mPrefix + "_mul", z0, x0, D0), - // D2 = z2 * x2; - c.call(f2mPrefix + "_mul", z2, x2, D2), - // D4 = z4 * x4; - c.call(f2mPrefix + "_mul", z4, x4, D4), - // t2 = z0 + z4; - c.call(f2mPrefix + "_add", z0, z4, t2), - // t1 = z0 + z2; - c.call(f2mPrefix + "_add", z0, z2, t1), - // s0 = z1 + z3 + z5; - c.call(f2mPrefix + "_add", z1, z3, s0), - c.call(f2mPrefix + "_add", s0, z5, s0), - - - // For z.a_.a_ = z0. - // S1 = z1 * x2; - c.call(f2mPrefix + "_mul", z1, x2, S1), - // T3 = S1 + D4; - c.call(f2mPrefix + "_add", S1, D4, T3), - // T4 = my_Fp6::non_residue * T3 + D0; - c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), - c.call(f2mPrefix + "_add", T4, D0, z0), - // z0 = T4; - - // For z.a_.b_ = z1 - // T3 = z5 * x4; - c.call(f2mPrefix + "_mul", z5, x4, T3), - // S1 = S1 + T3; - c.call(f2mPrefix + "_add", S1, T3, S1), - // T3 = T3 + D2; - c.call(f2mPrefix + "_add", T3, D2, T3), - // T4 = my_Fp6::non_residue * T3; - c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), - // T3 = z1 * x0; - c.call(f2mPrefix + "_mul", z1, x0, T3), - // S1 = S1 + T3; - c.call(f2mPrefix + "_add", S1, T3, S1), - // T4 = T4 + T3; - c.call(f2mPrefix + "_add", T4, T3, z1), - // z1 = T4; - - - - // For z.a_.c_ = z2 - // t0 = x0 + x2; - c.call(f2mPrefix + "_add", x0, x2, t0), - // T3 = t1 * t0 - D0 - D2; - c.call(f2mPrefix + "_mul", t1, t0, T3), - c.call(f2mPrefix + "_add", D0, D2, AUX), - c.call(f2mPrefix + "_sub", T3, AUX, T3), - // T4 = z3 * x4; - c.call(f2mPrefix + "_mul", z3, x4, T4), - // S1 = S1 + T4; - c.call(f2mPrefix + "_add", S1, T4, S1), - - - // For z.b_.a_ = z3 (z3 needs z2) - // t0 = z2 + z4; - c.call(f2mPrefix + "_add", z2, z4, t0), - // T3 = T3 + T4; - // z2 = T3; - c.call(f2mPrefix + "_add", T3, T4, z2), - // t1 = x2 + x4; - c.call(f2mPrefix + "_add", x2, x4, t1), - // T3 = t0 * t1 - D2 - D4; - c.call(f2mPrefix + "_mul", t1, t0, T3), - c.call(f2mPrefix + "_add", D2, D4, AUX), - c.call(f2mPrefix + "_sub", T3, AUX, T3), - // T4 = my_Fp6::non_residue * T3; - c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), - // T3 = z3 * x0; - c.call(f2mPrefix + "_mul", z3, x0, T3), - // S1 = S1 + T3; - c.call(f2mPrefix + "_add", S1, T3, S1), - // T4 = T4 + T3; - c.call(f2mPrefix + "_add", T4, T3, z3), - // z3 = T4; - - // For z.b_.b_ = z4 - // T3 = z5 * x2; - c.call(f2mPrefix + "_mul", z5, x2, T3), - // S1 = S1 + T3; - c.call(f2mPrefix + "_add", S1, T3, S1), - // T4 = my_Fp6::non_residue * T3; - c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), - // t0 = x0 + x4; - c.call(f2mPrefix + "_add", x0, x4, t0), - // T3 = t2 * t0 - D0 - D4; - c.call(f2mPrefix + "_mul", t2, t0, T3), - c.call(f2mPrefix + "_add", D0, D4, AUX), - c.call(f2mPrefix + "_sub", T3, AUX, T3), - // T4 = T4 + T3; - c.call(f2mPrefix + "_add", T4, T3, z4), - // z4 = T4; - - // For z.b_.c_ = z5. - // t0 = x0 + x2 + x4; - c.call(f2mPrefix + "_add", x0, x2, t0), - c.call(f2mPrefix + "_add", t0, x4, t0), - // T3 = s0 * t0 - S1; - c.call(f2mPrefix + "_mul", s0, t0, T3), - c.call(f2mPrefix + "_sub", T3, S1, z5), - // z5 = T3; - - ); - } - - - function buildMillerLoop() { - const f = module.addFunction(prefix+ "_millerLoop"); - f.addParam("ppreP", "i32"); - f.addParam("ppreQ", "i32"); - f.addParam("r", "i32"); - f.addLocal("pCoef", "i32"); - f.addLocal("i", "i32"); - - const c = f.getCodeBuilder(); - - const preP_PX = c.getLocal("ppreP"); - const preP_PY = c.i32_add(c.getLocal("ppreP"), c.i32_const(f1size)); - - const ELL_0 = c.getLocal("pCoef"); - const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); - const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); - - - const pVW = module.alloc(f2size); - const VW = c.i32_const(pVW); - const pVV = module.alloc(f2size); - const VV = c.i32_const(pVV); - - const F = c.getLocal("r"); - - - f.addCode( - c.call(ftmPrefix + "_one", F), - - c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), - - c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), - c.block(c.loop( - - - c.call(ftmPrefix + "_square", F, F), - - c.call(f2mPrefix + "_mul1", ELL_VW,preP_PY, VW), - c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), - c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - c.if( - c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), - [ - ...c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), - ...c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), - - ...c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), - ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - ] - ), - c.br_if(1, c.i32_eqz ( c.getLocal("i") )), - c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - - ); - - f.addCode( - c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), - c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), - c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), - c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), - c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - ); - - } - - - function buildFrobeniusMap(n) { - const F12 = [ - [ - [bigInt$2("1"), bigInt$2("0")], - [bigInt$2("1"), bigInt$2("0")], - [bigInt$2("1"), bigInt$2("0")], - [bigInt$2("1"), bigInt$2("0")], - [bigInt$2("1"), bigInt$2("0")], - [bigInt$2("1"), bigInt$2("0")], - [bigInt$2("1"), bigInt$2("0")], - [bigInt$2("1"), bigInt$2("0")], - [bigInt$2("1"), bigInt$2("0")], - [bigInt$2("1"), bigInt$2("0")], - [bigInt$2("1"), bigInt$2("0")], - [bigInt$2("1"), bigInt$2("0")], - ], - [ - [bigInt$2("1"), bigInt$2("0")], - [bigInt$2("8376118865763821496583973867626364092589906065868298776909617916018768340080"), bigInt$2("16469823323077808223889137241176536799009286646108169935659301613961712198316")], - [bigInt$2("21888242871839275220042445260109153167277707414472061641714758635765020556617"), bigInt$2("0")], - [bigInt$2("11697423496358154304825782922584725312912383441159505038794027105778954184319"), bigInt$2("303847389135065887422783454877609941456349188919719272345083954437860409601")], - [bigInt$2("21888242871839275220042445260109153167277707414472061641714758635765020556616"), bigInt$2("0")], - [bigInt$2("3321304630594332808241809054958361220322477375291206261884409189760185844239"), bigInt$2("5722266937896532885780051958958348231143373700109372999374820235121374419868")], - [bigInt$2("21888242871839275222246405745257275088696311157297823662689037894645226208582"), bigInt$2("0")], - [bigInt$2("13512124006075453725662431877630910996106405091429524885779419978626457868503"), bigInt$2("5418419548761466998357268504080738289687024511189653727029736280683514010267")], - [bigInt$2("2203960485148121921418603742825762020974279258880205651966"), bigInt$2("0")], - [bigInt$2("10190819375481120917420622822672549775783927716138318623895010788866272024264"), bigInt$2("21584395482704209334823622290379665147239961968378104390343953940207365798982")], - [bigInt$2("2203960485148121921418603742825762020974279258880205651967"), bigInt$2("0")], - [bigInt$2("18566938241244942414004596690298913868373833782006617400804628704885040364344"), bigInt$2("16165975933942742336466353786298926857552937457188450663314217659523851788715")], - ] - ]; - - const F6 = [ - [ - [bigInt$2("1"), bigInt$2("0")], - [bigInt$2("1"), bigInt$2("0")], - [bigInt$2("1"), bigInt$2("0")], - [bigInt$2("1"), bigInt$2("0")], - [bigInt$2("1"), bigInt$2("0")], - [bigInt$2("1"), bigInt$2("0")], - ], - [ - [bigInt$2("1"), bigInt$2("0")], - [bigInt$2("21575463638280843010398324269430826099269044274347216827212613867836435027261"), bigInt$2("10307601595873709700152284273816112264069230130616436755625194854815875713954")], - [bigInt$2("21888242871839275220042445260109153167277707414472061641714758635765020556616"), bigInt$2("0")], - [bigInt$2("3772000881919853776433695186713858239009073593817195771773381919316419345261"), bigInt$2("2236595495967245188281701248203181795121068902605861227855261137820944008926")], - [bigInt$2("2203960485148121921418603742825762020974279258880205651966"), bigInt$2("0")], - [bigInt$2("18429021223477853657660792034369865839114504446431234726392080002137598044644"), bigInt$2("9344045779998320333812420223237981029506012124075525679208581902008406485703")], - ], - [ - [bigInt$2("1"), bigInt$2("0")], - [bigInt$2("2581911344467009335267311115468803099551665605076196740867805258568234346338"), bigInt$2("19937756971775647987995932169929341994314640652964949448313374472400716661030")], - [bigInt$2("2203960485148121921418603742825762020974279258880205651966"), bigInt$2("0")], - [bigInt$2("5324479202449903542726783395506214481928257762400643279780343368557297135718"), bigInt$2("16208900380737693084919495127334387981393726419856888799917914180988844123039")], - [bigInt$2("21888242871839275220042445260109153167277707414472061641714758635765020556616"), bigInt$2("0")], - [bigInt$2("13981852324922362344252311234282257507216387789820983642040889267519694726527"), bigInt$2("7629828391165209371577384193250820201684255241773809077146787135900891633097")], - ] - ]; - - const f = module.addFunction(prefix+ "__frobeniusMap"+n); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - for (let i=0; i<6; i++) { - const X = (i==0) ? c.getLocal("x") : c.i32_add(c.getLocal("x"), c.i32_const(i*f2size)); - const Xc0 = X; - const Xc1 = c.i32_add(c.getLocal("x"), c.i32_const(i*f2size + f1size)); - const R = (i==0) ? c.getLocal("r") : c.i32_add(c.getLocal("r"), c.i32_const(i*f2size)); - const Rc0 = R; - const Rc1 = c.i32_add(c.getLocal("r"), c.i32_const(i*f2size + f1size)); - const coef = mul2(F12[Math.floor(i/3)][n%12] , F6[i%3][n%6]); - const pCoef = module.alloc([ - ...utils$6.bigInt2BytesLE(toMontgomery(coef[0]), 32), - ...utils$6.bigInt2BytesLE(toMontgomery(coef[1]), 32), - ]); - if (n%2 == 1) { - f.addCode( - c.call(f1mPrefix + "_copy", Xc0, Rc0), - c.call(f1mPrefix + "_neg", Xc1, Rc1), - c.call(f2mPrefix + "_mul", R, c.i32_const(pCoef), R), - ); - } else { - f.addCode(c.call(f2mPrefix + "_mul", X, c.i32_const(pCoef), R)); - } - } - - function mul2(a, b) { - const ac0 = bigInt$2(a[0]); - const ac1 = bigInt$2(a[1]); - const bc0 = bigInt$2(b[0]); - const bc1 = bigInt$2(b[1]); - const res = [ - ac0.times(bc0).minus( ac1.times(bc1) ).mod(q), - ac0.times(bc1).add( ac1.times(bc0) ).mod(q), - ]; - if (res[0].isNegative()) res[0] = res[0].add(q); - return res; - } - - } - - - - function buildFinalExponentiationFirstChunk() { - - const f = module.addFunction(prefix+ "__finalExponentiationFirstChunk"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const elt = c.getLocal("x"); - const eltC0 = elt; - const eltC1 = c.i32_add(elt, c.i32_const(n8*6)); - const r = c.getLocal("r"); - const pA = module.alloc(ftsize); - const A = c.i32_const(pA); - const Ac0 = A; - const Ac1 = c.i32_const(pA + n8*6); - const B = c.i32_const(module.alloc(ftsize)); - const C = c.i32_const(module.alloc(ftsize)); - const D = c.i32_const(module.alloc(ftsize)); - - f.addCode( - // const alt_bn128_Fq12 A = alt_bn128_Fq12(elt.c0,-elt.c1); - c.call(f6mPrefix + "_copy", eltC0, Ac0), - c.call(f6mPrefix + "_neg", eltC1, Ac1), - - // const alt_bn128_Fq12 B = elt.inverse(); - c.call(ftmPrefix + "_inverse", elt, B), - - // const alt_bn128_Fq12 C = A * B; - c.call(ftmPrefix + "_mul", A, B, C), - // const alt_bn128_Fq12 D = C.Frobenius_map(2); - c.call(prefix + "__frobeniusMap2", C, D), - // const alt_bn128_Fq12 result = D * C; - c.call(ftmPrefix + "_mul", C, D, r), - ); - } - - function buildCyclotomicSquare() { - const f = module.addFunction(prefix+ "__cyclotomicSquare"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x4 = c.i32_add(c.getLocal("x"), c.i32_const(f2size)); - const x3 = c.i32_add(c.getLocal("x"), c.i32_const(2*f2size)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(3*f2size)); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(4*f2size)); - const x5 = c.i32_add(c.getLocal("x"), c.i32_const(5*f2size)); - - const r0 = c.getLocal("r"); - const r4 = c.i32_add(c.getLocal("r"), c.i32_const(f2size)); - const r3 = c.i32_add(c.getLocal("r"), c.i32_const(2*f2size)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(3*f2size)); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(4*f2size)); - const r5 = c.i32_add(c.getLocal("r"), c.i32_const(5*f2size)); - - const t0 = c.i32_const(module.alloc(f2size)); - const t1 = c.i32_const(module.alloc(f2size)); - const t2 = c.i32_const(module.alloc(f2size)); - const t3 = c.i32_const(module.alloc(f2size)); - const t4 = c.i32_const(module.alloc(f2size)); - const t5 = c.i32_const(module.alloc(f2size)); - const tmp = c.i32_const(module.alloc(f2size)); - const AUX = c.i32_const(module.alloc(f2size)); - - - f.addCode( - -// c.call(ftmPrefix + "_square", x0, r0), - - // // t0 + t1*y = (z0 + z1*y)^2 = a^2 - // tmp = z0 * z1; - // t0 = (z0 + z1) * (z0 + my_Fp6::non_residue * z1) - tmp - my_Fp6::non_residue * tmp; - // t1 = tmp + tmp; - c.call(f2mPrefix + "_mul", x0, x1, tmp), - c.call(f2mPrefix + "_mul", x1, c.i32_const(pNonResidueF6), t0), - c.call(f2mPrefix + "_add", x0, t0, t0), - c.call(f2mPrefix + "_add", x0, x1, AUX), - c.call(f2mPrefix + "_mul", AUX, t0, t0), - c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), - c.call(f2mPrefix + "_add", tmp, AUX, AUX), - c.call(f2mPrefix + "_sub", t0, AUX, t0), - c.call(f2mPrefix + "_add", tmp, tmp, t1), - - // // t2 + t3*y = (z2 + z3*y)^2 = b^2 - // tmp = z2 * z3; - // t2 = (z2 + z3) * (z2 + my_Fp6::non_residue * z3) - tmp - my_Fp6::non_residue * tmp; - // t3 = tmp + tmp; - c.call(f2mPrefix + "_mul", x2, x3, tmp), - c.call(f2mPrefix + "_mul", x3, c.i32_const(pNonResidueF6), t2), - c.call(f2mPrefix + "_add", x2, t2, t2), - c.call(f2mPrefix + "_add", x2, x3, AUX), - c.call(f2mPrefix + "_mul", AUX, t2, t2), - c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), - c.call(f2mPrefix + "_add", tmp, AUX, AUX), - c.call(f2mPrefix + "_sub", t2, AUX, t2), - c.call(f2mPrefix + "_add", tmp, tmp, t3), - - // // t4 + t5*y = (z4 + z5*y)^2 = c^2 - // tmp = z4 * z5; - // t4 = (z4 + z5) * (z4 + my_Fp6::non_residue * z5) - tmp - my_Fp6::non_residue * tmp; - // t5 = tmp + tmp; - c.call(f2mPrefix + "_mul", x4, x5, tmp), - c.call(f2mPrefix + "_mul", x5, c.i32_const(pNonResidueF6), t4), - c.call(f2mPrefix + "_add", x4, t4, t4), - c.call(f2mPrefix + "_add", x4, x5, AUX), - c.call(f2mPrefix + "_mul", AUX, t4, t4), - c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), - c.call(f2mPrefix + "_add", tmp, AUX, AUX), - c.call(f2mPrefix + "_sub", t4, AUX, t4), - c.call(f2mPrefix + "_add", tmp, tmp, t5), - - // For A - // z0 = 3 * t0 - 2 * z0 - c.call(f2mPrefix + "_sub", t0, x0, r0), - c.call(f2mPrefix + "_add", r0, r0, r0), - c.call(f2mPrefix + "_add", t0, r0, r0), - // z1 = 3 * t1 + 2 * z1 - c.call(f2mPrefix + "_add", t1, x1, r1), - c.call(f2mPrefix + "_add", r1, r1, r1), - c.call(f2mPrefix + "_add", t1, r1, r1), - - // For B - // z2 = 3 * (xi * t5) + 2 * z2 - c.call(f2mPrefix + "_mul", t5, c.i32_const(pAltBn128Twist), AUX), - c.call(f2mPrefix + "_add", AUX, x2, r2), - c.call(f2mPrefix + "_add", r2, r2, r2), - c.call(f2mPrefix + "_add", AUX, r2, r2), - // z3 = 3 * t4 - 2 * z3 - c.call(f2mPrefix + "_sub", t4, x3, r3), - c.call(f2mPrefix + "_add", r3, r3, r3), - c.call(f2mPrefix + "_add", t4, r3, r3), - - // For C - // z4 = 3 * t2 - 2 * z4 - c.call(f2mPrefix + "_sub", t2, x4, r4), - c.call(f2mPrefix + "_add", r4, r4, r4), - c.call(f2mPrefix + "_add", t2, r4, r4), - // z5 = 3 * t3 + 2 * z5 - c.call(f2mPrefix + "_add", t3, x5, r5), - c.call(f2mPrefix + "_add", r5, r5, r5), - c.call(f2mPrefix + "_add", t3, r5, r5), - - ); - } - - - function buildCyclotomicExp(exponent, fnName) { - const exponentNafBytes = naf(exponent).map( (b) => (b==-1 ? 0xFF: b) ); - const pExponentNafBytes = module.alloc(exponentNafBytes); - module.alloc(utils$6.bigInt2BytesLE(exponent, 32)); - - const f = module.addFunction(prefix+ "__cyclotomicExp_"+fnName); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - f.addLocal("bit", "i32"); - f.addLocal("i", "i32"); - - const c = f.getCodeBuilder(); - - const x = c.getLocal("x"); - - const res = c.getLocal("r"); - - const inverse = c.i32_const(module.alloc(ftsize)); - - - f.addCode( -// c.call(ftmPrefix + "_exp", x, c.i32_const(pExponent), c.i32_const(32), res), - - c.call(ftmPrefix + "_conjugate", x, inverse), - c.call(ftmPrefix + "_one", res), - - c.if( - c.teeLocal("bit", c.i32_load8_s(c.i32_const(exponentNafBytes.length-1), pExponentNafBytes)), - c.if( - c.i32_eq( - c.getLocal("bit"), - c.i32_const(1) - ), - c.call(ftmPrefix + "_mul", res, x, res), - c.call(ftmPrefix + "_mul", res, inverse, res), - ) - ), - - c.setLocal("i", c.i32_const(exponentNafBytes.length-2)), - c.block(c.loop( -// c.call(ftmPrefix + "_square", res, res), - c.call(prefix + "__cyclotomicSquare", res, res), - c.if( - c.teeLocal("bit", c.i32_load8_s(c.getLocal("i"), pExponentNafBytes)), - c.if( - c.i32_eq( - c.getLocal("bit"), - c.i32_const(1) - ), - c.call(ftmPrefix + "_mul", res, x, res), - c.call(ftmPrefix + "_mul", res, inverse, res), - ) - ), - c.br_if(1, c.i32_eqz ( c.getLocal("i") )), - c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - ); - } - - - - function buildFinalExponentiationLastChunk() { - buildCyclotomicSquare(); - buildCyclotomicExp(finalExpZ, "w0"); - - const f = module.addFunction(prefix+ "__finalExponentiationLastChunk"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const elt = c.getLocal("x"); - const result = c.getLocal("r"); - const A = c.i32_const(module.alloc(ftsize)); - const B = c.i32_const(module.alloc(ftsize)); - const C = c.i32_const(module.alloc(ftsize)); - const D = c.i32_const(module.alloc(ftsize)); - const E = c.i32_const(module.alloc(ftsize)); - const F = c.i32_const(module.alloc(ftsize)); - const G = c.i32_const(module.alloc(ftsize)); - const H = c.i32_const(module.alloc(ftsize)); - const I = c.i32_const(module.alloc(ftsize)); - const J = c.i32_const(module.alloc(ftsize)); - const K = c.i32_const(module.alloc(ftsize)); - const L = c.i32_const(module.alloc(ftsize)); - const M = c.i32_const(module.alloc(ftsize)); - const N = c.i32_const(module.alloc(ftsize)); - const O = c.i32_const(module.alloc(ftsize)); - const P = c.i32_const(module.alloc(ftsize)); - const Q = c.i32_const(module.alloc(ftsize)); - const R = c.i32_const(module.alloc(ftsize)); - const S = c.i32_const(module.alloc(ftsize)); - const T = c.i32_const(module.alloc(ftsize)); - const U = c.i32_const(module.alloc(ftsize)); - - f.addCode( - - - // A = exp_by_neg_z(elt) // = elt^(-z) - c.call(prefix + "__cyclotomicExp_w0", elt, A), - c.call(ftmPrefix + "_conjugate", A, A), - // B = A^2 // = elt^(-2*z) - c.call(prefix + "__cyclotomicSquare", A, B), - // C = B^2 // = elt^(-4*z) - c.call(prefix + "__cyclotomicSquare", B, C), - // D = C * B // = elt^(-6*z) - c.call(ftmPrefix + "_mul", C, B, D), - // E = exp_by_neg_z(D) // = elt^(6*z^2) - c.call(prefix + "__cyclotomicExp_w0", D, E), - c.call(ftmPrefix + "_conjugate", E, E), - // F = E^2 // = elt^(12*z^2) - c.call(prefix + "__cyclotomicSquare", E, F), - // G = epx_by_neg_z(F) // = elt^(-12*z^3) - c.call(prefix + "__cyclotomicExp_w0", F, G), - c.call(ftmPrefix + "_conjugate", G, G), - // H = conj(D) // = elt^(6*z) - c.call(ftmPrefix + "_conjugate", D, H), - // I = conj(G) // = elt^(12*z^3) - c.call(ftmPrefix + "_conjugate", G, I), - // J = I * E // = elt^(12*z^3 + 6*z^2) - c.call(ftmPrefix + "_mul", I, E, J), - // K = J * H // = elt^(12*z^3 + 6*z^2 + 6*z) - c.call(ftmPrefix + "_mul", J, H, K), - // L = K * B // = elt^(12*z^3 + 6*z^2 + 4*z) - c.call(ftmPrefix + "_mul", K, B, L), - // M = K * E // = elt^(12*z^3 + 12*z^2 + 6*z) - c.call(ftmPrefix + "_mul", K, E, M), - - // N = M * elt // = elt^(12*z^3 + 12*z^2 + 6*z + 1) - c.call(ftmPrefix + "_mul", M, elt, N), - - // O = L.Frobenius_map(1) // = elt^(q*(12*z^3 + 6*z^2 + 4*z)) - c.call(prefix + "__frobeniusMap1", L, O), - // P = O * N // = elt^(q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) - c.call(ftmPrefix + "_mul", O, N, P), - // Q = K.Frobenius_map(2) // = elt^(q^2 * (12*z^3 + 6*z^2 + 6*z)) - c.call(prefix + "__frobeniusMap2", K, Q), - // R = Q * P // = elt^(q^2 * (12*z^3 + 6*z^2 + 6*z) + q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) - c.call(ftmPrefix + "_mul", Q, P, R), - // S = conj(elt) // = elt^(-1) - c.call(ftmPrefix + "_conjugate", elt, S), - // T = S * L // = elt^(12*z^3 + 6*z^2 + 4*z - 1) - c.call(ftmPrefix + "_mul", S, L, T), - // U = T.Frobenius_map(3) // = elt^(q^3(12*z^3 + 6*z^2 + 4*z - 1)) - c.call(prefix + "__frobeniusMap3", T, U), - // V = U * R // = elt^(q^3(12*z^3 + 6*z^2 + 4*z - 1) + q^2 * (12*z^3 + 6*z^2 + 6*z) + q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) - c.call(ftmPrefix + "_mul", U, R, result), - // result = V - ); - } - - - function buildFinalExponentiation() { - buildFinalExponentiationFirstChunk(); - buildFinalExponentiationLastChunk(); - const f = module.addFunction(prefix+ "_finalExponentiation"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const elt = c.getLocal("x"); - const result = c.getLocal("r"); - const eltToFirstChunk = c.i32_const(module.alloc(ftsize)); - - f.addCode( - c.call(prefix + "__finalExponentiationFirstChunk", elt, eltToFirstChunk ), - c.call(prefix + "__finalExponentiationLastChunk", eltToFirstChunk, result ) - ); - } - - - function buildFinalExponentiationOld() { - const f = module.addFunction(prefix+ "_finalExponentiationOld"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const exponent = bigInt$2("552484233613224096312617126783173147097382103762957654188882734314196910839907541213974502761540629817009608548654680343627701153829446747810907373256841551006201639677726139946029199968412598804882391702273019083653272047566316584365559776493027495458238373902875937659943504873220554161550525926302303331747463515644711876653177129578303191095900909191624817826566688241804408081892785725967931714097716709526092261278071952560171111444072049229123565057483750161460024353346284167282452756217662335528813519139808291170539072125381230815729071544861602750936964829313608137325426383735122175229541155376346436093930287402089517426973178917569713384748081827255472576937471496195752727188261435633271238710131736096299798168852925540549342330775279877006784354801422249722573783561685179618816480037695005515426162362431072245638324744480"); - - const pExponent = module.alloc(utils$6.bigInt2BytesLE( exponent, 352 )); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call(ftmPrefix + "_exp", c.getLocal("x"), c.i32_const(pExponent), c.i32_const(352), c.getLocal("r")), - ); - } - - - - - const pPreP = module.alloc(prePSize); - const pPreQ = module.alloc(preQSize); - - function buildPairingEquation(nPairings) { - - const f = module.addFunction(prefix+ "_pairingEq"+nPairings); - for (let i=0; i acc + ( b!=0 ? 1 : 0) ,0); - const ateNCoefs = ateNAddCoefs + ateNDblCoefs + 1; - const prePSize = 3*2*n8q; - const preQSize = 3*n8q*2 + ateNCoefs*ateCoefSize; - const finalExpIsNegative = true; - - const finalExpZ = bigInt$1("15132376222941642752"); - - - module.modules[prefix] = { - n64q: n64q, - n64r: n64r, - n8q: n8q, - n8r: n8r, - pG1gen: pG1gen, - pG1zero: pG1zero, - pG1b: pG1b, - pG2gen: pG2gen, - pG2zero: pG2zero, - pG2b: pG2b, - pq: module.modules["f1m"].pq, - pr: pr, - pOneT: pOneT, - r: r, - q: q, - prePSize: prePSize, - preQSize: preQSize - }; - - - function naf(n) { - let E = n; - const res = []; - while (E.gt(bigInt$1.zero)) { - if (E.isOdd()) { - const z = 2 - E.mod(4).toJSNumber(); - res.push( z ); - E = E.minus(z); - } else { - res.push( 0 ); - } - E = E.shiftRight(1); - } - return res; - } - - function bits(n) { - let E = n; - const res = []; - while (E.gt(bigInt$1.zero)) { - if (E.isOdd()) { - res.push( 1 ); - } else { - res.push( 0 ); - } - E = E.shiftRight(1); - } - return res; - } - - function buildPrepareG1() { - const f = module.addFunction(prefix+ "_prepareG1"); - f.addParam("pP", "i32"); - f.addParam("ppreP", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call(g1mPrefix + "_normalize", c.getLocal("pP"), c.getLocal("ppreP")), // TODO Remove if already in affine - ); - } - - - - function buildPrepDoubleStep() { - const f = module.addFunction(prefix+ "_prepDblStep"); - f.addParam("R", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const Rx = c.getLocal("R"); - const Ry = c.i32_add(c.getLocal("R"), c.i32_const(2*n8q)); - const Rz = c.i32_add(c.getLocal("R"), c.i32_const(4*n8q)); - - const t0 = c.getLocal("r"); - const t3 = c.i32_add(c.getLocal("r"), c.i32_const(2*n8q)); - const t6 = c.i32_add(c.getLocal("r"), c.i32_const(4*n8q)); - - - const zsquared = c.i32_const(module.alloc(f2size)); - const t1 = c.i32_const(module.alloc(f2size)); - const t2 = c.i32_const(module.alloc(f2size)); - const t4 = c.i32_const(module.alloc(f2size)); - const t5 = c.i32_const(module.alloc(f2size)); - - f.addCode( - - // tmp0 = r.x.square(); - c.call(f2mPrefix + "_square", Rx, t0), - - // tmp1 = r.y.square(); - c.call(f2mPrefix + "_square", Ry, t1), - - // tmp2 = tmp1.square(); - c.call(f2mPrefix + "_square", t1, t2), - - // tmp3 = (tmp1 + r.x).square() - tmp0 - tmp2; - c.call(f2mPrefix + "_add", t1, Rx, t3), - c.call(f2mPrefix + "_square", t3, t3), - c.call(f2mPrefix + "_sub", t3, t0, t3), - c.call(f2mPrefix + "_sub", t3, t2, t3), - - // tmp3 = tmp3 + tmp3; - c.call(f2mPrefix + "_add", t3, t3, t3), - - // tmp4 = tmp0 + tmp0 + tmp0; - c.call(f2mPrefix + "_add", t0, t0, t4), - c.call(f2mPrefix + "_add", t4, t0, t4), - - // tmp6 = r.x + tmp4; - c.call(f2mPrefix + "_add", Rx, t4, t6), - - // tmp5 = tmp4.square(); - c.call(f2mPrefix + "_square", t4, t5), - - // zsquared = r.z.square(); - c.call(f2mPrefix + "_square", Rz, zsquared), - - // r.x = tmp5 - tmp3 - tmp3; - c.call(f2mPrefix + "_sub", t5, t3, Rx), - c.call(f2mPrefix + "_sub", Rx, t3, Rx), - - // r.z = (r.z + r.y).square() - tmp1 - zsquared; - c.call(f2mPrefix + "_add", Rz, Ry, Rz), - c.call(f2mPrefix + "_square", Rz, Rz), - c.call(f2mPrefix + "_sub", Rz, t1, Rz), - c.call(f2mPrefix + "_sub", Rz, zsquared, Rz), - - // r.y = (tmp3 - r.x) * tmp4; - c.call(f2mPrefix + "_sub", t3, Rx, Ry), - c.call(f2mPrefix + "_mul", Ry, t4, Ry), - - // tmp2 = tmp2 + tmp2; - c.call(f2mPrefix + "_add", t2, t2, t2), - - // tmp2 = tmp2 + tmp2; - c.call(f2mPrefix + "_add", t2, t2, t2), - - // tmp2 = tmp2 + tmp2; - c.call(f2mPrefix + "_add", t2, t2, t2), - - // r.y -= tmp2; - c.call(f2mPrefix + "_sub", Ry, t2, Ry), - - // tmp3 = tmp4 * zsquared; - c.call(f2mPrefix + "_mul", t4, zsquared, t3), - - // tmp3 = tmp3 + tmp3; - c.call(f2mPrefix + "_add", t3, t3, t3), - - // tmp3 = -tmp3; - c.call(f2mPrefix + "_neg", t3, t3), - - // tmp6 = tmp6.square() - tmp0 - tmp5; - c.call(f2mPrefix + "_square", t6, t6), - c.call(f2mPrefix + "_sub", t6, t0, t6), - c.call(f2mPrefix + "_sub", t6, t5, t6), - - // tmp1 = tmp1 + tmp1; - c.call(f2mPrefix + "_add", t1, t1, t1), - - // tmp1 = tmp1 + tmp1; - c.call(f2mPrefix + "_add", t1, t1, t1), - - // tmp6 = tmp6 - tmp1; - c.call(f2mPrefix + "_sub", t6, t1, t6), - - // tmp0 = r.z * zsquared; - c.call(f2mPrefix + "_mul", Rz, zsquared, t0), - - // tmp0 = tmp0 + tmp0; - c.call(f2mPrefix + "_add", t0, t0, t0), - - ); - } - - function buildPrepAddStep() { - const f = module.addFunction(prefix+ "_prepAddStep"); - f.addParam("R", "i32"); - f.addParam("Q", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const Rx = c.getLocal("R"); - const Ry = c.i32_add(c.getLocal("R"), c.i32_const(2*n8q)); - const Rz = c.i32_add(c.getLocal("R"), c.i32_const(4*n8q)); - - const Qx = c.getLocal("Q"); - const Qy = c.i32_add(c.getLocal("Q"), c.i32_const(2*n8q)); - - const t10 = c.getLocal("r"); - const t1 = c.i32_add(c.getLocal("r"), c.i32_const(2*n8q)); - const t9 = c.i32_add(c.getLocal("r"), c.i32_const(4*n8q)); - - const zsquared = c.i32_const(module.alloc(f2size)); - const ysquared = c.i32_const(module.alloc(f2size)); - const ztsquared = c.i32_const(module.alloc(f2size)); - const t0 = c.i32_const(module.alloc(f2size)); - const t2 = c.i32_const(module.alloc(f2size)); - const t3 = c.i32_const(module.alloc(f2size)); - const t4 = c.i32_const(module.alloc(f2size)); - const t5 = c.i32_const(module.alloc(f2size)); - const t6 = c.i32_const(module.alloc(f2size)); - const t7 = c.i32_const(module.alloc(f2size)); - const t8 = c.i32_const(module.alloc(f2size)); - - f.addCode( - - // zsquared = r.z.square(); - c.call(f2mPrefix + "_square", Rz, zsquared), - - // ysquared = q.y.square(); - c.call(f2mPrefix + "_square", Qy, ysquared), - - // t0 = zsquared * q.x; - c.call(f2mPrefix + "_mul", zsquared, Qx, t0), - - // t1 = ((q.y + r.z).square() - ysquared - zsquared) * zsquared; - c.call(f2mPrefix + "_add", Qy, Rz, t1), - c.call(f2mPrefix + "_square", t1, t1), - c.call(f2mPrefix + "_sub", t1, ysquared, t1), - c.call(f2mPrefix + "_sub", t1, zsquared, t1), - c.call(f2mPrefix + "_mul", t1, zsquared, t1), - - // t2 = t0 - r.x; - c.call(f2mPrefix + "_sub", t0, Rx, t2), - - // t3 = t2.square(); - c.call(f2mPrefix + "_square", t2, t3), - - // t4 = t3 + t3; - c.call(f2mPrefix + "_add", t3, t3, t4), - - // t4 = t4 + t4; - c.call(f2mPrefix + "_add", t4, t4, t4), - - // t5 = t4 * t2; - c.call(f2mPrefix + "_mul", t4, t2, t5), - - // t6 = t1 - r.y - r.y; - c.call(f2mPrefix + "_sub", t1, Ry, t6), - c.call(f2mPrefix + "_sub", t6, Ry, t6), - - // t9 = t6 * q.x; - c.call(f2mPrefix + "_mul", t6, Qx, t9), - - // t7 = t4 * r.x; - c.call(f2mPrefix + "_mul", t4, Rx, t7), - - // r.x = t6.square() - t5 - t7 - t7; - c.call(f2mPrefix + "_square", t6, Rx), - c.call(f2mPrefix + "_sub", Rx, t5, Rx), - c.call(f2mPrefix + "_sub", Rx, t7, Rx), - c.call(f2mPrefix + "_sub", Rx, t7, Rx), - - // r.z = (r.z + t2).square() - zsquared - t3; - c.call(f2mPrefix + "_add", Rz, t2, Rz), - c.call(f2mPrefix + "_square", Rz, Rz), - c.call(f2mPrefix + "_sub", Rz, zsquared, Rz), - c.call(f2mPrefix + "_sub", Rz, t3, Rz), - - // t10 = q.y + r.z; - c.call(f2mPrefix + "_add", Qy, Rz, t10), - - // t8 = (t7 - r.x) * t6; - c.call(f2mPrefix + "_sub", t7, Rx, t8), - c.call(f2mPrefix + "_mul", t8, t6, t8), - - // t0 = r.y * t5; - c.call(f2mPrefix + "_mul", Ry, t5, t0), - - // t0 = t0 + t0; - c.call(f2mPrefix + "_add", t0, t0, t0), - - // r.y = t8 - t0; - c.call(f2mPrefix + "_sub", t8, t0, Ry), - - // t10 = t10.square() - ysquared; - c.call(f2mPrefix + "_square", t10, t10), - c.call(f2mPrefix + "_sub", t10, ysquared, t10), - - // ztsquared = r.z.square(); - c.call(f2mPrefix + "_square", Rz, ztsquared), - - // t10 = t10 - ztsquared; - c.call(f2mPrefix + "_sub", t10, ztsquared, t10), - - // t9 = t9 + t9 - t10; - c.call(f2mPrefix + "_add", t9, t9, t9), - c.call(f2mPrefix + "_sub", t9, t10, t9), - - // t10 = r.z + r.z; - c.call(f2mPrefix + "_add", Rz, Rz, t10), - - // t6 = -t6; - c.call(f2mPrefix + "_neg", t6, t6), - - // t1 = t6 + t6; - c.call(f2mPrefix + "_add", t6, t6, t1), - ); - } - - - function buildPrepareG2() { - const f = module.addFunction(prefix+ "_prepareG2"); - f.addParam("pQ", "i32"); - f.addParam("ppreQ", "i32"); - f.addLocal("pCoef", "i32"); - f.addLocal("i", "i32"); - - const c = f.getCodeBuilder(); - - - const Q = c.getLocal("pQ"); - - const pR = module.alloc(f2size*3); - const R = c.i32_const(pR); - - const base = c.getLocal("ppreQ"); - - f.addCode( - c.call(g2mPrefix + "_normalize", Q, base), - c.if( - c.call(g2mPrefix + "_isZero", base), - c.ret([]) - ), - c.call(g2mPrefix + "_copy", base, R), - c.setLocal("pCoef", c.i32_add(c.getLocal("ppreQ"), c.i32_const(f2size*3))), - ); - - f.addCode( - c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), - c.block(c.loop( - - c.call(prefix + "_prepDblStep", R, c.getLocal("pCoef")), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - c.if( - c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), - [ - ...c.call(prefix + "_prepAddStep", R, base, c.getLocal("pCoef")), - ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - ] - ), - c.br_if(1, c.i32_eqz ( c.getLocal("i") )), - c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - ); - } - - - function buildF6Mul1() { - const f = module.addFunction(f6mPrefix+ "_mul1"); - f.addParam("pA", "i32"); // F6 - f.addParam("pC1", "i32"); // F2 - f.addParam("pR", "i32"); // F6 - - const c = f.getCodeBuilder(); - - const A_c0 = c.getLocal("pA"); - const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*2)); - const A_c2 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*4)); - - const c1 = c.getLocal("pC1"); - - const t1 = c.getLocal("pR"); - const t2 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*2)); - const b_b = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*4)); - - const Ac0_Ac1 = c.i32_const(module.alloc(f1size*2)); - const Ac1_Ac2 = c.i32_const(module.alloc(f1size*2)); - - f.addCode( - - c.call(f2mPrefix + "_add", A_c0, A_c1, Ac0_Ac1), - c.call(f2mPrefix + "_add", A_c1, A_c2, Ac1_Ac2), - - // let b_b = self.c1 * c1; - c.call(f2mPrefix + "_mul", A_c1, c1, b_b), - - // let t1 = (self.c1 + self.c2) * c1 - b_b; - c.call(f2mPrefix + "_mul", Ac1_Ac2, c1, t1), - c.call(f2mPrefix + "_sub", t1, b_b, t1), - - // let t1 = t1.mul_by_nonresidue(); - c.call(f2mPrefix + "_mulNR", t1, t1), - - // let t2 = (self.c0 + self.c1) * c1 - b_b; - c.call(f2mPrefix + "_mul", Ac0_Ac1, c1, t2), - c.call(f2mPrefix + "_sub", t2, b_b, t2), - ); - } - buildF6Mul1(); - - function buildF6Mul01() { - const f = module.addFunction(f6mPrefix+ "_mul01"); - f.addParam("pA", "i32"); // F6 - f.addParam("pC0", "i32"); // F2 - f.addParam("pC1", "i32"); // F2 - f.addParam("pR", "i32"); // F6 - - const c = f.getCodeBuilder(); - - const A_c0 = c.getLocal("pA"); - const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*2)); - const A_c2 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*4)); - - const c0 = c.getLocal("pC0"); - const c1 = c.getLocal("pC1"); - - const t1 = c.getLocal("pR"); - const t2 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*2)); - const t3 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*4)); - - const a_a = c.i32_const(module.alloc(f1size*2)); - const b_b = c.i32_const(module.alloc(f1size*2)); - const Ac0_Ac1 = c.i32_const(module.alloc(f1size*2)); - const Ac0_Ac2 = c.i32_const(module.alloc(f1size*2)); - - f.addCode( - // let a_a = self.c0 * c0; - c.call(f2mPrefix + "_mul", A_c0, c0, a_a), - - // let b_b = self.c1 * c1; - c.call(f2mPrefix + "_mul", A_c1, c1, b_b), - - - c.call(f2mPrefix + "_add", A_c0, A_c1, Ac0_Ac1), - c.call(f2mPrefix + "_add", A_c0, A_c2, Ac0_Ac2), - - // let t1 = (self.c1 + self.c2) * c1 - b_b; - c.call(f2mPrefix + "_add", A_c1, A_c2, t1), - c.call(f2mPrefix + "_mul", t1, c1, t1), - c.call(f2mPrefix + "_sub", t1, b_b, t1), - - // let t1 = t1.mul_by_nonresidue() + a_a; - c.call(f2mPrefix + "_mulNR", t1, t1), - c.call(f2mPrefix + "_add", t1, a_a, t1), - - // let t2 = (c0 + c1) * (self.c0 + self.c1) - a_a - b_b; - c.call(f2mPrefix + "_add", c0, c1, t2), - c.call(f2mPrefix + "_mul", t2, Ac0_Ac1, t2), - c.call(f2mPrefix + "_sub", t2, a_a, t2), - c.call(f2mPrefix + "_sub", t2, b_b, t2), - - // let t3 = (self.c0 + self.c2) * c0 - a_a + b_b; - c.call(f2mPrefix + "_mul", Ac0_Ac2, c0, t3), - c.call(f2mPrefix + "_sub", t3, a_a, t3), - c.call(f2mPrefix + "_add", t3, b_b, t3), - - - ); - } - buildF6Mul01(); - - - function buildF12Mul014() { - - const f = module.addFunction(ftmPrefix+ "_mul014"); - f.addParam("pA", "i32"); // F12 - f.addParam("pC0", "i32"); // F2 - f.addParam("pC1", "i32"); // F2 - f.addParam("pC4", "i32"); // F2 - f.addParam("pR", "i32"); // F12 - - const c = f.getCodeBuilder(); - - - const A_c0 = c.getLocal("pA"); - const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*6)); - - const c0 = c.getLocal("pC0"); - const c1 = c.getLocal("pC1"); - const c4 = c.getLocal("pC4"); - - const aa = c.i32_const(module.alloc(f1size*6)); - const bb = c.i32_const(module.alloc(f1size*6)); - const o = c.i32_const(module.alloc(f1size*2)); - - const R_c0 = c.getLocal("pR"); - const R_c1 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*6)); - - f.addCode( - // let aa = self.c0.mul_by_01(c0, c1); - c.call(f6mPrefix + "_mul01", A_c0, c0, c1, aa), - - // let bb = self.c1.mul_by_1(c4); - c.call(f6mPrefix + "_mul1", A_c1, c4, bb), - - // let o = c1 + c4; - c.call(f2mPrefix + "_add", c1, c4, o), - - // let c1 = self.c1 + self.c0; - c.call(f6mPrefix + "_add", A_c1, A_c0, R_c1), - - // let c1 = c1.mul_by_01(c0, &o); - c.call(f6mPrefix + "_mul01", R_c1, c0, o, R_c1), - - // let c1 = c1 - aa - bb; - c.call(f6mPrefix + "_sub", R_c1, aa, R_c1), - c.call(f6mPrefix + "_sub", R_c1, bb, R_c1), - - // let c0 = bb; - c.call(f6mPrefix + "_copy", bb, R_c0), - - // let c0 = c0.mul_by_nonresidue(); - c.call(f6mPrefix + "_mulNR", R_c0, R_c0), - - // let c0 = c0 + aa; - c.call(f6mPrefix + "_add", R_c0, aa, R_c0), - ); - } - buildF12Mul014(); - - - function buildELL() { - const f = module.addFunction(prefix+ "_ell"); - f.addParam("pP", "i32"); - f.addParam("pCoefs", "i32"); - f.addParam("pF", "i32"); - - const c = f.getCodeBuilder(); - - const Px = c.getLocal("pP"); - const Py = c.i32_add(c.getLocal("pP"), c.i32_const(n8q)); - - const F = c.getLocal("pF"); - - const coef0_0 = c.getLocal("pCoefs"); - const coef0_1 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size)); - const coef1_0 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*2)); - const coef1_1 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*3)); - const coef2 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*4)); - - const pc0 = module.alloc(f1size*2); - const c0 = c.i32_const(pc0); - const c0_c0 = c.i32_const(pc0); - const c0_c1 = c.i32_const(pc0+f1size); - - const pc1 = module.alloc(f1size*2); - const c1 = c.i32_const(pc1); - const c1_c0 = c.i32_const(pc1); - const c1_c1 = c.i32_const(pc1+f1size); - f.addCode( - // let mut c0 = coeffs.0; - // let mut c1 = coeffs.1; - // - // c0.c0 *= p.y; - // c0.c1 *= p.y; - // - // c1.c0 *= p.x; - // c1.c1 *= p.x; - // - // f.mul_by_014(&coeffs.2, &c1, &c0) - - c.call(f1mPrefix + "_mul", coef0_0, Py, c0_c0), - c.call(f1mPrefix + "_mul", coef0_1, Py, c0_c1), - c.call(f1mPrefix + "_mul", coef1_0, Px, c1_c0), - c.call(f1mPrefix + "_mul", coef1_1, Px, c1_c1), - - c.call(ftmPrefix + "_mul014", F, coef2, c1, c0, F), - - ); - - } - buildELL(); - - function buildMillerLoop() { - const f = module.addFunction(prefix+ "_millerLoop"); - f.addParam("ppreP", "i32"); - f.addParam("ppreQ", "i32"); - f.addParam("r", "i32"); - f.addLocal("pCoef", "i32"); - f.addLocal("i", "i32"); - - const c = f.getCodeBuilder(); - - const preP = c.getLocal("ppreP"); - c.getLocal("ppreQ"); - - const coefs = c.getLocal("pCoef"); - - const F = c.getLocal("r"); - - - f.addCode( - c.call(ftmPrefix + "_one", F), - - c.if( - c.call(g1mPrefix + "_isZero", preP), - c.ret([]) - ), - c.if( - c.call(g1mPrefix + "_isZero", c.getLocal("ppreQ")), - c.ret([]) - ), - c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), - - c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), - c.block(c.loop( - - - c.call(prefix + "_ell", preP, coefs, F), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - c.if( - c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), - [ - ...c.call(prefix + "_ell", preP, coefs, F), - ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - ] - ), - c.call(ftmPrefix + "_square", F, F), - - c.br_if(1, c.i32_eq ( c.getLocal("i"), c.i32_const(1) )), - c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )), - c.call(prefix + "_ell", preP, coefs, F), - - ); - - - { - f.addCode( - c.call(ftmPrefix + "_conjugate", F, F), - ); - } - } - - - function buildFrobeniusMap(n) { - const F12 = [ - [ - [bigInt$1("1"), bigInt$1("0")], - [bigInt$1("1"), bigInt$1("0")], - [bigInt$1("1"), bigInt$1("0")], - [bigInt$1("1"), bigInt$1("0")], - [bigInt$1("1"), bigInt$1("0")], - [bigInt$1("1"), bigInt$1("0")], - [bigInt$1("1"), bigInt$1("0")], - [bigInt$1("1"), bigInt$1("0")], - [bigInt$1("1"), bigInt$1("0")], - [bigInt$1("1"), bigInt$1("0")], - [bigInt$1("1"), bigInt$1("0")], - [bigInt$1("1"), bigInt$1("0")], - ], - [ - [bigInt$1("1"), bigInt$1("0")], - [bigInt$1("3850754370037169011952147076051364057158807420970682438676050522613628423219637725072182697113062777891589506424760"), bigInt$1("151655185184498381465642749684540099398075398968325446656007613510403227271200139370504932015952886146304766135027")], - [bigInt$1("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620351"), bigInt$1("0")], - [bigInt$1("2973677408986561043442465346520108879172042883009249989176415018091420807192182638567116318576472649347015917690530"), bigInt$1("1028732146235106349975324479215795277384839936929757896155643118032610843298655225875571310552543014690878354869257")], - [bigInt$1("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350"), bigInt$1("0")], - [bigInt$1("3125332594171059424908108096204648978570118281977575435832422631601824034463382777937621250592425535493320683825557"), bigInt$1("877076961050607968509681729531255177986764537961432449499635504522207616027455086505066378536590128544573588734230")], - [bigInt$1("4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786"), bigInt$1("0")], - [bigInt$1("151655185184498381465642749684540099398075398968325446656007613510403227271200139370504932015952886146304766135027"), bigInt$1("3850754370037169011952147076051364057158807420970682438676050522613628423219637725072182697113062777891589506424760")], - [bigInt$1("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436"), bigInt$1("0")], - [bigInt$1("1028732146235106349975324479215795277384839936929757896155643118032610843298655225875571310552543014690878354869257"), bigInt$1("2973677408986561043442465346520108879172042883009249989176415018091420807192182638567116318576472649347015917690530")], - [bigInt$1("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939437"), bigInt$1("0")], - [bigInt$1("877076961050607968509681729531255177986764537961432449499635504522207616027455086505066378536590128544573588734230"), bigInt$1("3125332594171059424908108096204648978570118281977575435832422631601824034463382777937621250592425535493320683825557")], - ] - ]; - - const F6 = [ - [ - [bigInt$1("1"), bigInt$1("0")], - [bigInt$1("1"), bigInt$1("0")], - [bigInt$1("1"), bigInt$1("0")], - [bigInt$1("1"), bigInt$1("0")], - [bigInt$1("1"), bigInt$1("0")], - [bigInt$1("1"), bigInt$1("0")], - ], - [ - [bigInt$1("1"), bigInt$1("0")], - [bigInt$1("0"), bigInt$1("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436")], - [bigInt$1("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350"), bigInt$1("0")], - [bigInt$1("0"), bigInt$1("1")], - [bigInt$1("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436"), bigInt$1("0")], - [bigInt$1("0"), bigInt$1("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350")], - ], - [ - [bigInt$1("1"), bigInt$1("0")], - [bigInt$1("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939437"), bigInt$1("0")], - [bigInt$1("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436"), bigInt$1("0")], - [bigInt$1("4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786"), bigInt$1("0")], - [bigInt$1("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350"), bigInt$1("0")], - [bigInt$1("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620351"), bigInt$1("0")], - ] - ]; - - const f = module.addFunction(ftmPrefix + "_frobeniusMap"+n); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - for (let i=0; i<6; i++) { - const X = (i==0) ? c.getLocal("x") : c.i32_add(c.getLocal("x"), c.i32_const(i*f2size)); - const Xc0 = X; - const Xc1 = c.i32_add(c.getLocal("x"), c.i32_const(i*f2size + f1size)); - const R = (i==0) ? c.getLocal("r") : c.i32_add(c.getLocal("r"), c.i32_const(i*f2size)); - const Rc0 = R; - const Rc1 = c.i32_add(c.getLocal("r"), c.i32_const(i*f2size + f1size)); - const coef = mul2(F12[Math.floor(i/3)][n%12] , F6[i%3][n%6]); - const pCoef = module.alloc([ - ...utils$5.bigInt2BytesLE(toMontgomery(coef[0]), n8q), - ...utils$5.bigInt2BytesLE(toMontgomery(coef[1]), n8q), - ]); - if (n%2 == 1) { - f.addCode( - c.call(f1mPrefix + "_copy", Xc0, Rc0), - c.call(f1mPrefix + "_neg", Xc1, Rc1), - c.call(f2mPrefix + "_mul", R, c.i32_const(pCoef), R), - ); - } else { - f.addCode(c.call(f2mPrefix + "_mul", X, c.i32_const(pCoef), R)); - } - } - - function mul2(a, b) { - const ac0 = bigInt$1(a[0]); - const ac1 = bigInt$1(a[1]); - const bc0 = bigInt$1(b[0]); - const bc1 = bigInt$1(b[1]); - const res = [ - ac0.times(bc0).minus( ac1.times(bc1) ).mod(q), - ac0.times(bc1).add( ac1.times(bc0) ).mod(q), - ]; - if (res[0].isNegative()) res[0] = res[0].add(q); - return res; - } - - } - - - function buildCyclotomicSquare() { - const f = module.addFunction(prefix+ "__cyclotomicSquare"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x4 = c.i32_add(c.getLocal("x"), c.i32_const(f2size)); - const x3 = c.i32_add(c.getLocal("x"), c.i32_const(2*f2size)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(3*f2size)); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(4*f2size)); - const x5 = c.i32_add(c.getLocal("x"), c.i32_const(5*f2size)); - - const r0 = c.getLocal("r"); - const r4 = c.i32_add(c.getLocal("r"), c.i32_const(f2size)); - const r3 = c.i32_add(c.getLocal("r"), c.i32_const(2*f2size)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(3*f2size)); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(4*f2size)); - const r5 = c.i32_add(c.getLocal("r"), c.i32_const(5*f2size)); - - const t0 = c.i32_const(module.alloc(f2size)); - const t1 = c.i32_const(module.alloc(f2size)); - const t2 = c.i32_const(module.alloc(f2size)); - const t3 = c.i32_const(module.alloc(f2size)); - const t4 = c.i32_const(module.alloc(f2size)); - const t5 = c.i32_const(module.alloc(f2size)); - const tmp = c.i32_const(module.alloc(f2size)); - const AUX = c.i32_const(module.alloc(f2size)); - - - f.addCode( - -// c.call(ftmPrefix + "_square", x0, r0), - - // // t0 + t1*y = (z0 + z1*y)^2 = a^2 - // tmp = z0 * z1; - // t0 = (z0 + z1) * (z0 + my_Fp6::non_residue * z1) - tmp - my_Fp6::non_residue * tmp; - // t1 = tmp + tmp; - c.call(f2mPrefix + "_mul", x0, x1, tmp), - c.call(f2mPrefix + "_mulNR", x1, t0), - c.call(f2mPrefix + "_add", x0, t0, t0), - c.call(f2mPrefix + "_add", x0, x1, AUX), - c.call(f2mPrefix + "_mul", AUX, t0, t0), - c.call(f2mPrefix + "_mulNR", tmp, AUX), - c.call(f2mPrefix + "_add", tmp, AUX, AUX), - c.call(f2mPrefix + "_sub", t0, AUX, t0), - c.call(f2mPrefix + "_add", tmp, tmp, t1), - - // // t2 + t3*y = (z2 + z3*y)^2 = b^2 - // tmp = z2 * z3; - // t2 = (z2 + z3) * (z2 + my_Fp6::non_residue * z3) - tmp - my_Fp6::non_residue * tmp; - // t3 = tmp + tmp; - c.call(f2mPrefix + "_mul", x2, x3, tmp), - c.call(f2mPrefix + "_mulNR", x3, t2), - c.call(f2mPrefix + "_add", x2, t2, t2), - c.call(f2mPrefix + "_add", x2, x3, AUX), - c.call(f2mPrefix + "_mul", AUX, t2, t2), - c.call(f2mPrefix + "_mulNR", tmp, AUX), - c.call(f2mPrefix + "_add", tmp, AUX, AUX), - c.call(f2mPrefix + "_sub", t2, AUX, t2), - c.call(f2mPrefix + "_add", tmp, tmp, t3), - - // // t4 + t5*y = (z4 + z5*y)^2 = c^2 - // tmp = z4 * z5; - // t4 = (z4 + z5) * (z4 + my_Fp6::non_residue * z5) - tmp - my_Fp6::non_residue * tmp; - // t5 = tmp + tmp; - c.call(f2mPrefix + "_mul", x4, x5, tmp), - c.call(f2mPrefix + "_mulNR", x5, t4), - c.call(f2mPrefix + "_add", x4, t4, t4), - c.call(f2mPrefix + "_add", x4, x5, AUX), - c.call(f2mPrefix + "_mul", AUX, t4, t4), - c.call(f2mPrefix + "_mulNR", tmp, AUX), - c.call(f2mPrefix + "_add", tmp, AUX, AUX), - c.call(f2mPrefix + "_sub", t4, AUX, t4), - c.call(f2mPrefix + "_add", tmp, tmp, t5), - - // For A - // z0 = 3 * t0 - 2 * z0 - c.call(f2mPrefix + "_sub", t0, x0, r0), - c.call(f2mPrefix + "_add", r0, r0, r0), - c.call(f2mPrefix + "_add", t0, r0, r0), - // z1 = 3 * t1 + 2 * z1 - c.call(f2mPrefix + "_add", t1, x1, r1), - c.call(f2mPrefix + "_add", r1, r1, r1), - c.call(f2mPrefix + "_add", t1, r1, r1), - - // For B - // z2 = 3 * (xi * t5) + 2 * z2 - c.call(f2mPrefix + "_mul", t5, c.i32_const(pBls12381Twist), AUX), - c.call(f2mPrefix + "_add", AUX, x2, r2), - c.call(f2mPrefix + "_add", r2, r2, r2), - c.call(f2mPrefix + "_add", AUX, r2, r2), - // z3 = 3 * t4 - 2 * z3 - c.call(f2mPrefix + "_sub", t4, x3, r3), - c.call(f2mPrefix + "_add", r3, r3, r3), - c.call(f2mPrefix + "_add", t4, r3, r3), - - // For C - // z4 = 3 * t2 - 2 * z4 - c.call(f2mPrefix + "_sub", t2, x4, r4), - c.call(f2mPrefix + "_add", r4, r4, r4), - c.call(f2mPrefix + "_add", t2, r4, r4), - // z5 = 3 * t3 + 2 * z5 - c.call(f2mPrefix + "_add", t3, x5, r5), - c.call(f2mPrefix + "_add", r5, r5, r5), - c.call(f2mPrefix + "_add", t3, r5, r5), - - ); - } - - - function buildCyclotomicExp(exponent, isExpNegative, fnName) { - const exponentNafBytes = naf(exponent).map( (b) => (b==-1 ? 0xFF: b) ); - const pExponentNafBytes = module.alloc(exponentNafBytes); - // const pExponent = module.alloc(utils.bigInt2BytesLE(exponent, n8)); - - const f = module.addFunction(prefix+ "__cyclotomicExp_"+fnName); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - f.addLocal("bit", "i32"); - f.addLocal("i", "i32"); - - const c = f.getCodeBuilder(); - - const x = c.getLocal("x"); - - const res = c.getLocal("r"); - - const inverse = c.i32_const(module.alloc(ftsize)); - - - f.addCode( -// c.call(ftmPrefix + "_exp", x, c.i32_const(pExponent), c.i32_const(32), res), - - c.call(ftmPrefix + "_conjugate", x, inverse), - c.call(ftmPrefix + "_one", res), - - c.if( - c.teeLocal("bit", c.i32_load8_s(c.i32_const(exponentNafBytes.length-1), pExponentNafBytes)), - c.if( - c.i32_eq( - c.getLocal("bit"), - c.i32_const(1) - ), - c.call(ftmPrefix + "_mul", res, x, res), - c.call(ftmPrefix + "_mul", res, inverse, res), - ) - ), - - c.setLocal("i", c.i32_const(exponentNafBytes.length-2)), - c.block(c.loop( -// c.call(ftmPrefix + "_square", res, res), - c.call(prefix + "__cyclotomicSquare", res, res), - c.if( - c.teeLocal("bit", c.i32_load8_s(c.getLocal("i"), pExponentNafBytes)), - c.if( - c.i32_eq( - c.getLocal("bit"), - c.i32_const(1) - ), - c.call(ftmPrefix + "_mul", res, x, res), - c.call(ftmPrefix + "_mul", res, inverse, res), - ) - ), - c.br_if(1, c.i32_eqz ( c.getLocal("i") )), - c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - ); - - if (isExpNegative) { - f.addCode( - c.call(ftmPrefix + "_conjugate", res, res), - ); - } - - } - - function buildFinalExponentiation() { - buildCyclotomicSquare(); - buildCyclotomicExp(finalExpZ, finalExpIsNegative, "w0"); - - const f = module.addFunction(prefix+ "_finalExponentiation"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const elt = c.getLocal("x"); - const res = c.getLocal("r"); - const t0 = c.i32_const(module.alloc(ftsize)); - const t1 = c.i32_const(module.alloc(ftsize)); - const t2 = c.i32_const(module.alloc(ftsize)); - const t3 = c.i32_const(module.alloc(ftsize)); - const t4 = c.i32_const(module.alloc(ftsize)); - const t5 = c.i32_const(module.alloc(ftsize)); - const t6 = c.i32_const(module.alloc(ftsize)); - - f.addCode( - - // let mut t0 = f.frobenius_map(6) - c.call(ftmPrefix + "_frobeniusMap6", elt, t0), - - // let t1 = f.invert() - c.call(ftmPrefix + "_inverse", elt, t1), - - // let mut t2 = t0 * t1; - c.call(ftmPrefix + "_mul", t0, t1, t2), - - // t1 = t2.clone(); - c.call(ftmPrefix + "_copy", t2, t1), - - // t2 = t2.frobenius_map().frobenius_map(); - c.call(ftmPrefix + "_frobeniusMap2", t2, t2), - - // t2 *= t1; - c.call(ftmPrefix + "_mul", t2, t1, t2), - - - // t1 = cyclotomic_square(t2).conjugate(); - c.call(prefix + "__cyclotomicSquare", t2, t1), - c.call(ftmPrefix + "_conjugate", t1, t1), - - // let mut t3 = cycolotomic_exp(t2); - c.call(prefix + "__cyclotomicExp_w0", t2, t3), - - // let mut t4 = cyclotomic_square(t3); - c.call(prefix + "__cyclotomicSquare", t3, t4), - - // let mut t5 = t1 * t3; - c.call(ftmPrefix + "_mul", t1, t3, t5), - - // t1 = cycolotomic_exp(t5); - c.call(prefix + "__cyclotomicExp_w0", t5, t1), - - // t0 = cycolotomic_exp(t1); - c.call(prefix + "__cyclotomicExp_w0", t1, t0), - - // let mut t6 = cycolotomic_exp(t0); - c.call(prefix + "__cyclotomicExp_w0", t0, t6), - - // t6 *= t4; - c.call(ftmPrefix + "_mul", t6, t4, t6), - - // t4 = cycolotomic_exp(t6); - c.call(prefix + "__cyclotomicExp_w0", t6, t4), - - // t5 = t5.conjugate(); - c.call(ftmPrefix + "_conjugate", t5, t5), - - // t4 *= t5 * t2; - c.call(ftmPrefix + "_mul", t4, t5, t4), - c.call(ftmPrefix + "_mul", t4, t2, t4), - - // t5 = t2.conjugate(); - c.call(ftmPrefix + "_conjugate", t2, t5), - - // t1 *= t2; - c.call(ftmPrefix + "_mul", t1, t2, t1), - - // t1 = t1.frobenius_map().frobenius_map().frobenius_map(); - c.call(ftmPrefix + "_frobeniusMap3", t1, t1), - - // t6 *= t5; - c.call(ftmPrefix + "_mul", t6, t5, t6), - - // t6 = t6.frobenius_map(); - c.call(ftmPrefix + "_frobeniusMap1", t6, t6), - - // t3 *= t0; - c.call(ftmPrefix + "_mul", t3, t0, t3), - - // t3 = t3.frobenius_map().frobenius_map(); - c.call(ftmPrefix + "_frobeniusMap2", t3, t3), - - // t3 *= t1; - c.call(ftmPrefix + "_mul", t3, t1, t3), - - // t3 *= t6; - c.call(ftmPrefix + "_mul", t3, t6, t3), - - // f = t3 * t4; - c.call(ftmPrefix + "_mul", t3, t4, res), - - ); - } - - - function buildFinalExponentiationOld() { - const f = module.addFunction(prefix+ "_finalExponentiationOld"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const exponent = bigInt$1("322277361516934140462891564586510139908379969514828494218366688025288661041104682794998680497580008899973249814104447692778988208376779573819485263026159588510513834876303014016798809919343532899164848730280942609956670917565618115867287399623286813270357901731510188149934363360381614501334086825442271920079363289954510565375378443704372994881406797882676971082200626541916413184642520269678897559532260949334760604962086348898118982248842634379637598665468817769075878555493752214492790122785850202957575200176084204422751485957336465472324810982833638490904279282696134323072515220044451592646885410572234451732790590013479358343841220074174848221722017083597872017638514103174122784843925578370430843522959600095676285723737049438346544753168912974976791528535276317256904336520179281145394686565050419250614107803233314658825463117900250701199181529205942363159325765991819433914303908860460720581408201373164047773794825411011922305820065611121544561808414055302212057471395719432072209245600258134364584636810093520285711072578721435517884103526483832733289802426157301542744476740008494780363354305116978805620671467071400711358839553375340724899735460480144599782014906586543813292157922220645089192130209334926661588737007768565838519456601560804957985667880395221049249803753582637708560"); - - const pExponent = module.alloc(utils$5.bigInt2BytesLE( exponent, 544 )); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call(ftmPrefix + "_exp", c.getLocal("x"), c.i32_const(pExponent), c.i32_const(544), c.getLocal("r")), - ); - } - - - const pPreP = module.alloc(prePSize); - const pPreQ = module.alloc(preQSize); - - function buildPairingEquation(nPairings) { - - const f = module.addFunction(prefix+ "_pairingEq"+nPairings); - for (let i=0; i. -*/ - -// module.exports.bn128_wasm = require("./build/bn128_wasm.js"); -// module.exports.bls12381_wasm = require("./build/bls12381_wasm.js"); -// module.exports.mnt6753_wasm = require("./build/mnt6753_wasm.js"); - -var buildBn128$1 = build_bn128; -var buildBls12381$1 = build_bls12381; - -/* global BigInt */ - -function stringifyBigInts$2(o) { - if ((typeof(o) == "bigint") || o.eq !== undefined) { - return o.toString(10); - } else if (o instanceof Uint8Array) { - return fromRprLE(o, 0); - } else if (Array.isArray(o)) { - return o.map(stringifyBigInts$2); - } else if (typeof o == "object") { - const res = {}; - const keys = Object.keys(o); - keys.forEach( (k) => { - res[k] = stringifyBigInts$2(o[k]); - }); - return res; - } else { - return o; - } -} - -function unstringifyBigInts$2(o) { - if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) { - return BigInt(o); - } else if ((typeof(o) == "string") && (/^0x[0-9a-fA-F]+$/.test(o) )) { - return BigInt(o); - } else if (Array.isArray(o)) { - return o.map(unstringifyBigInts$2); - } else if (typeof o == "object") { - if (o===null) return null; - const res = {}; - const keys = Object.keys(o); - keys.forEach( (k) => { - res[k] = unstringifyBigInts$2(o[k]); - }); - return res; - } else { - return o; - } -} - -function beBuff2int$2(buff) { - let res = BigInt(0); - let i = buff.length; - let offset = 0; - const buffV = new DataView(buff.buffer, buff.byteOffset, buff.byteLength); - while (i>0) { - if (i >= 4) { - i -= 4; - res += BigInt(buffV.getUint32(i)) << BigInt(offset*8); - offset += 4; - } else if (i >= 2) { - i -= 2; - res += BigInt(buffV.getUint16(i)) << BigInt(offset*8); - offset += 2; - } else { - i -= 1; - res += BigInt(buffV.getUint8(i)) << BigInt(offset*8); - offset += 1; - } - } - return res; -} - -function beInt2Buff$2(n, len) { - let r = n; - const buff = new Uint8Array(len); - const buffV = new DataView(buff.buffer); - let o = len; - while (o > 0) { - if (o-4 >= 0) { - o -= 4; - buffV.setUint32(o, Number(r & BigInt(0xFFFFFFFF))); - r = r >> BigInt(32); - } else if (o-2 >= 0) { - o -= 2; - buffV.setUint16(o, Number(r & BigInt(0xFFFF))); - r = r >> BigInt(16); - } else { - o -= 1; - buffV.setUint8(o, Number(r & BigInt(0xFF))); - r = r >> BigInt(8); - } - } - if (r) { - throw new Error("Number does not fit in this length"); - } - return buff; -} - - -function leBuff2int$2(buff) { - let res = BigInt(0); - let i = 0; - const buffV = new DataView(buff.buffer, buff.byteOffset, buff.byteLength); - while (i> BigInt(32); - } else if (o+2 <= len) { - buffV.setUint16(Number(o, r & BigInt(0xFFFF)), true ); - o += 2; - r = r >> BigInt(16); - } else { - buffV.setUint8(Number(o, r & BigInt(0xFF)), true ); - o += 1; - r = r >> BigInt(8); - } - } - if (r) { - throw new Error("Number does not fit in this length"); - } - return buff; -} - - -function stringifyFElements$1(F, o) { - if ((typeof(o) == "bigint") || o.eq !== undefined) { - return o.toString(10); - } else if (o instanceof Uint8Array) { - return F.toString(F.e(o)); - } else if (Array.isArray(o)) { - return o.map(stringifyFElements$1.bind(this,F)); - } else if (typeof o == "object") { - const res = {}; - const keys = Object.keys(o); - keys.forEach( (k) => { - res[k] = stringifyFElements$1(F, o[k]); - }); - return res; - } else { - return o; - } -} - - -function unstringifyFElements$1(F, o) { - if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) { - return F.e(o); - } else if ((typeof(o) == "string") && (/^0x[0-9a-fA-F]+$/.test(o) )) { - return F.e(o); - } else if (Array.isArray(o)) { - return o.map(unstringifyFElements$1.bind(this,F)); - } else if (typeof o == "object") { - if (o===null) return null; - const res = {}; - const keys = Object.keys(o); - keys.forEach( (k) => { - res[k] = unstringifyFElements$1(F, o[k]); - }); - return res; - } else { - return o; - } -} - -var utils_native = /*#__PURE__*/Object.freeze({ - __proto__: null, - beBuff2int: beBuff2int$2, - beInt2Buff: beInt2Buff$2, - leBuff2int: leBuff2int$2, - leInt2Buff: leInt2Buff$2, - stringifyBigInts: stringifyBigInts$2, - stringifyFElements: stringifyFElements$1, - unstringifyBigInts: unstringifyBigInts$2, - unstringifyFElements: unstringifyFElements$1 -}); - -function stringifyBigInts$1(o) { - if ((typeof(o) == "bigint") || o.eq !== undefined) { - return o.toString(10); - } else if (Array.isArray(o)) { - return o.map(stringifyBigInts$1); - } else if (typeof o == "object") { - const res = {}; - const keys = Object.keys(o); - keys.forEach( (k) => { - res[k] = stringifyBigInts$1(o[k]); - }); - return res; - } else { - return o; - } -} - -function unstringifyBigInts$1(o) { - if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) { - return bigInt$8(o); - } else if ((typeof(o) == "string") && (/^0x[0-9a-fA-F]+$/.test(o) )) { - return bigInt$8(o); - } else if (Array.isArray(o)) { - return o.map(unstringifyBigInts$1); - } else if (typeof o == "object") { - const res = {}; - const keys = Object.keys(o); - keys.forEach( (k) => { - res[k] = unstringifyBigInts$1(o[k]); - }); - return res; - } else { - return o; - } -} - -function beBuff2int$1(buff) { - let res = bigInt$8.zero; - for (let i=0; i=0)) { - let c = Number(r.and(bigInt$8("255"))); - buff[o] = c; - o--; - r = r.shiftRight(8); - } - if (!r.eq(bigInt$8.zero)) { - throw new Error("Number does not fit in this length"); - } - return buff; -} - - -function leBuff2int$1 (buff) { - let res = bigInt$8.zero; - for (let i=0; i>=1; - } - return res; -} - -utils$4.bitReverse = function bitReverse(idx, bits) { - return ( - _revTable[idx >>> 24] | - (_revTable[(idx >>> 16) & 0xFF] << 8) | - (_revTable[(idx >>> 8) & 0xFF] << 16) | - (_revTable[idx & 0xFF] << 24) - ) >>> (32-bits); -}; - - -utils$4.log2 = function log2( V ) -{ - return( ( ( V & 0xFFFF0000 ) !== 0 ? ( V &= 0xFFFF0000, 16 ) : 0 ) | ( ( V & 0xFF00FF00 ) !== 0 ? ( V &= 0xFF00FF00, 8 ) : 0 ) | ( ( V & 0xF0F0F0F0 ) !== 0 ? ( V &= 0xF0F0F0F0, 4 ) : 0 ) | ( ( V & 0xCCCCCCCC ) !== 0 ? ( V &= 0xCCCCCCCC, 2 ) : 0 ) | ( ( V & 0xAAAAAAAA ) !== 0 ) ); -}; - -utils$4.buffReverseBits = function buffReverseBits(buff, eSize) { - const n = buff.byteLength /eSize; - const bits = utils$4.log2(n); - if (n != (1 << bits)) { - throw new Error("Invalid number of pointers"); - } - for (let i=0; ir) { - const tmp = buff.slice(i*eSize, (i+1)*eSize); - buff.set( buff.slice(r*eSize, (r+1)*eSize), i*eSize); - buff.set(tmp, r*eSize); - } - } -}; - - -utils$4.array2buffer = function(arr, sG) { - const buff = new Uint8Array(sG*arr.length); - - for (let i=0; i0) { - // bytes to copy from this page - const l = (o+r > PAGE_SIZE) ? (PAGE_SIZE -o) : r; - const srcView = new Uint8Array(this.buffers[p].buffer, this.buffers[p].byteOffset+o, l); - if (l == len) return srcView.slice(); - if (!buff) { - if (len <= PAGE_SIZE) { - buff = new Uint8Array(len); - } else { - buff = new BigBuffer(len); - } - } - buff.set(srcView, len-r); - r = r-l; - p ++; - o = 0; - } - - return buff; - } - - set(buff, offset) { - if (offset === undefined) offset = 0; - - const len = buff.byteLength; - - if (len==0) return; - - const firstPage = Math.floor(offset / PAGE_SIZE); - const lastPage = Math.floor((offset+len-1) / PAGE_SIZE); - - if (firstPage == lastPage) { - if ((buff instanceof BigBuffer)&&(buff.buffers.length==1)) { - return this.buffers[firstPage].set(buff.buffers[0], offset % PAGE_SIZE); - } else { - return this.buffers[firstPage].set(buff, offset % PAGE_SIZE); - } - - } - - - let p = firstPage; - let o = offset % PAGE_SIZE; - let r = len; - while (r>0) { - const l = (o+r > PAGE_SIZE) ? (PAGE_SIZE -o) : r; - const srcView = buff.slice( len -r, len -r+l); - const dstView = new Uint8Array(this.buffers[p].buffer, this.buffers[p].byteOffset + o, l); - dstView.set(srcView); - r = r-l; - p ++; - o = 0; - } - - } -} - -function buildBatchConvert(tm, fnName, sIn, sOut) { - return async function batchConvert(buffIn) { - const nPoints = Math.floor(buffIn.byteLength / sIn); - if ( nPoints * sIn !== buffIn.byteLength) { - throw new Error("Invalid buffer size"); - } - const pointsPerChunk = Math.floor(nPoints/tm.concurrency); - const opPromises = []; - for (let i=0; i=0; i--) { - this.w[i] = this.square(this.w[i+1]); - } - - if (!this.eq(this.w[0], this.one)) { - throw new Error("Error calculating roots of unity"); - } - - this.batchToMontgomery = buildBatchConvert(tm, prefix + "_batchToMontgomery", this.n8, this.n8); - this.batchFromMontgomery = buildBatchConvert(tm, prefix + "_batchFromMontgomery", this.n8, this.n8); - } - - - op2(opName, a, b) { - this.tm.setBuff(this.pOp1, a); - this.tm.setBuff(this.pOp2, b); - this.tm.instance.exports[this.prefix + opName](this.pOp1, this.pOp2, this.pOp3); - return this.tm.getBuff(this.pOp3, this.n8); - } - - op2Bool(opName, a, b) { - this.tm.setBuff(this.pOp1, a); - this.tm.setBuff(this.pOp2, b); - return !!this.tm.instance.exports[this.prefix + opName](this.pOp1, this.pOp2); - } - - op1(opName, a) { - this.tm.setBuff(this.pOp1, a); - this.tm.instance.exports[this.prefix + opName](this.pOp1, this.pOp3); - return this.tm.getBuff(this.pOp3, this.n8); - } - - op1Bool(opName, a) { - this.tm.setBuff(this.pOp1, a); - return !!this.tm.instance.exports[this.prefix + opName](this.pOp1, this.pOp3); - } - - add(a,b) { - return this.op2("_add", a, b); - } - - - eq(a,b) { - return this.op2Bool("_eq", a, b); - } - - isZero(a) { - return this.op1Bool("_isZero", a); - } - - sub(a,b) { - return this.op2("_sub", a, b); - } - - neg(a) { - return this.op1("_neg", a); - } - - inv(a) { - return this.op1("_inverse", a); - } - - toMontgomery(a) { - return this.op1("_toMontgomery", a); - } - - fromMontgomery(a) { - return this.op1("_fromMontgomery", a); - } - - mul(a,b) { - return this.op2("_mul", a, b); - } - - div(a, b) { - this.tm.setBuff(this.pOp1, a); - this.tm.setBuff(this.pOp2, b); - this.tm.instance.exports[this.prefix + "_inverse"](this.pOp2, this.pOp2); - this.tm.instance.exports[this.prefix + "_mul"](this.pOp1, this.pOp2, this.pOp3); - return this.tm.getBuff(this.pOp3, this.n8); - } - - square(a) { - return this.op1("_square", a); - } - - isSquare(a) { - return this.op1Bool("_isSquare", a); - } - - sqrt(a) { - return this.op1("_sqrt", a); - } - - exp(a, b) { - if (!(b instanceof Uint8Array)) { - b = toLEBuff(e(b)); - } - this.tm.setBuff(this.pOp1, a); - this.tm.setBuff(this.pOp2, b); - this.tm.instance.exports[this.prefix + "_exp"](this.pOp1, this.pOp2, b.byteLength, this.pOp3); - return this.tm.getBuff(this.pOp3, this.n8); - } - - isNegative(a) { - return this.op1Bool("_isNegative", a); - } - - e(a, b) { - if (a instanceof Uint8Array) return a; - let ra = e(a, b); - if (isNegative(ra)) { - ra = neg(ra); - if (gt(ra, this.p)) { - ra = mod(ra, this.p); - } - ra = sub(this.p, ra); - } else { - if (gt(ra, this.p)) { - ra = mod(ra, this.p); - } - } - const buff = leInt2Buff(ra, this.n8); - return this.toMontgomery(buff); - } - - toString(a, radix) { - const an = this.fromMontgomery(a); - const s = fromRprLE(an, 0); - return toString(s, radix); - } - - fromRng(rng) { - let v; - const buff = new Uint8Array(this.n8); - do { - v = zero; - for (let i=0; i memory.buffer.byteLength) { - const currentPages = memory.buffer.byteLength / 0x10000; - let requiredPages = Math.floor((u32[0] + length) / 0x10000)+1; - if (requiredPages>MAXMEM) requiredPages=MAXMEM; - memory.grow(requiredPages-currentPages); - } - return res; - } - - function allocBuffer(buffer) { - const p = alloc(buffer.byteLength); - setBuffer(p, buffer); - return p; - } - - function getBuffer(pointer, length) { - const u8 = new Uint8Array(memory.buffer); - return new Uint8Array(u8.buffer, u8.byteOffset + pointer, length); - } - - function setBuffer(pointer, buffer) { - const u8 = new Uint8Array(memory.buffer); - u8.set(new Uint8Array(buffer), pointer); - } - - function runTask(task) { - if (task[0].cmd == "INIT") { - return init(task[0]); - } - const ctx = { - vars: [], - out: [] - }; - const u32a = new Uint32Array(memory.buffer, 0, 1); - const oldAlloc = u32a[0]; - for (let i=0; i { - try { - handler.call(this, event); - } - catch (err) { - console.error(err); - } - }); - } - addEventListener(type, fn) { - let events = this[EVENTS].get(type); - if (!events) this[EVENTS].set(type, events = []); - events.push(fn); - } - removeEventListener(type, fn) { - let events = this[EVENTS].get(type); - if (events) { - const index = events.indexOf(fn); - if (index !== -1) events.splice(index, 1); - } - } -} - -function Event(type, target) { - this.type = type; - this.timeStamp = Date.now(); - this.target = this.currentTarget = this.data = null; -} - -// this module is used self-referentially on both sides of the -// thread boundary, but behaves differently in each context. -var Worker = threads.isMainThread ? mainThread() : workerThread(); - -const baseUrl = URL.pathToFileURL(process.cwd() + '/'); - -function mainThread() { - - /** - * A web-compatible Worker implementation atop Node's worker_threads. - * - uses DOM-style events (Event.data, Event.type, etc) - * - supports event handler properties (worker.onmessage) - * - Worker() constructor accepts a module URL - * - accepts the {type:'module'} option - * - emulates WorkerGlobalScope within the worker - * @param {string} url The URL or module specifier to load - * @param {object} [options] Worker construction options - * @param {string} [options.name] Available as `self.name` within the Worker - * @param {string} [options.type="classic"] Pass "module" to create a Module Worker. - */ - class Worker extends EventTarget { - constructor(url, options) { - super(); - const { name, type } = options || {}; - url += ''; - let mod; - if (/^data:/.test(url)) { - mod = url; - } - else { - mod = URL.fileURLToPath(new URL.URL(url, baseUrl)); - } - const worker = new threads.Worker( - __filename, - { workerData: { mod, name, type } } - ); - Object.defineProperty(this, WORKER, { - value: worker - }); - worker.on('message', data => { - const event = new Event('message'); - event.data = data; - this.dispatchEvent(event); - }); - worker.on('error', error => { - error.type = 'error'; - this.dispatchEvent(error); - }); - worker.on('exit', () => { - this.dispatchEvent(new Event('close')); - }); - } - postMessage(data, transferList) { - this[WORKER].postMessage(data, transferList); - } - terminate() { - this[WORKER].terminate(); - } - } - Worker.prototype.onmessage = Worker.prototype.onerror = Worker.prototype.onclose = null; - return Worker; -} - -function workerThread() { - let { mod, name, type } = threads.workerData; - if (!mod) return mainThread(); - - // turn global into a mock WorkerGlobalScope - const self = global.self = global; - - // enqueue messages to dispatch after modules are loaded - let q = []; - function flush() { - const buffered = q; - q = null; - buffered.forEach(event => { self.dispatchEvent(event); }); - } - threads.parentPort.on('message', data => { - const event = new Event('message'); - event.data = data; - if (q == null) self.dispatchEvent(event); - else q.push(event); - }); - threads.parentPort.on('error', err => { - err.type = 'Error'; - self.dispatchEvent(err); - }); - - class WorkerGlobalScope extends EventTarget { - postMessage(data, transferList) { - threads.parentPort.postMessage(data, transferList); - } - // Emulates https://developer.mozilla.org/en-US/docs/Web/API/DedicatedWorkerGlobalScope/close - close() { - process.exit(); - } - } - let proto = Object.getPrototypeOf(global); - delete proto.constructor; - Object.defineProperties(WorkerGlobalScope.prototype, proto); - proto = Object.setPrototypeOf(global, new WorkerGlobalScope()); - ['postMessage', 'addEventListener', 'removeEventListener', 'dispatchEvent'].forEach(fn => { - proto[fn] = proto[fn].bind(global); - }); - global.name = name; - - const isDataUrl = /^data:/.test(mod); - if (type === 'module') { - import(mod) - .catch(err => { - if (isDataUrl && err.message === 'Not supported') { - console.warn('Worker(): Importing data: URLs requires Node 12.10+. Falling back to classic worker.'); - return evaluateDataUrl(mod, name); - } - console.error(err); - }) - .then(flush); - } - else { - try { - if (/^data:/.test(mod)) { - evaluateDataUrl(mod, name); - } - else { - require(mod); - } - } - catch (err) { - console.error(err); - } - Promise.resolve().then(flush); - } -} - -function evaluateDataUrl(url, name) { - const { data } = parseDataUrl(url); - return VM.runInThisContext(data, { - filename: 'worker.<'+(name || 'data:')+'>' - }); -} - -function parseDataUrl(url) { - let [m, type, encoding, data] = url.match(/^data: *([^;,]*)(?: *; *([^,]*))? *,(.*)$/) || []; - if (!m) throw Error('Invalid Data URL.'); - if (encoding) switch (encoding.toLowerCase()) { - case 'base64': - data = Buffer.from(data, 'base64').toString(); - break; - default: - throw Error('Unknown Data URL encoding "' + encoding + '"'); - } - return { type, data }; -} - -/* global navigator, WebAssembly */ -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -// const MEM_SIZE = 1000; // Memory size in 64K Pakes (512Mb) -const MEM_SIZE = 25; // Memory size in 64K Pakes (1600Kb) - -class Deferred { - constructor() { - this.promise = new Promise((resolve, reject)=> { - this.reject = reject; - this.resolve = resolve; - }); - } -} - -function sleep(ms) { - return new Promise(resolve => setTimeout(resolve, ms)); -} - -function stringToBase64(str) { - if (process.browser) { - return globalThis.btoa(str); - } else { - return Buffer.from(str).toString("base64"); - } -} - -const threadSource = stringToBase64("(" + thread.toString() + ")(self)"); -const workerSource = "data:application/javascript;base64," + threadSource; - - - -async function buildThreadManager(wasm, singleThread) { - const tm = new ThreadManager(); - - tm.memory = new WebAssembly.Memory({initial:MEM_SIZE}); - tm.u8 = new Uint8Array(tm.memory.buffer); - tm.u32 = new Uint32Array(tm.memory.buffer); - - const wasmModule = await WebAssembly.compile(wasm.code); - - tm.instance = await WebAssembly.instantiate(wasmModule, { - env: { - "memory": tm.memory - } - }); - - tm.singleThread = singleThread; - tm.initalPFree = tm.u32[0]; // Save the Pointer to free space. - tm.pq = wasm.pq; - tm.pr = wasm.pr; - tm.pG1gen = wasm.pG1gen; - tm.pG1zero = wasm.pG1zero; - tm.pG2gen = wasm.pG2gen; - tm.pG2zero = wasm.pG2zero; - tm.pOneT = wasm.pOneT; - - // tm.pTmp0 = tm.alloc(curve.G2.F.n8*3); - // tm.pTmp1 = tm.alloc(curve.G2.F.n8*3); - - - if (singleThread) { - tm.code = wasm.code; - tm.taskManager = thread(); - await tm.taskManager([{ - cmd: "INIT", - init: MEM_SIZE, - code: tm.code.slice() - }]); - tm.concurrency = 1; - } else { - tm.workers = []; - tm.pendingDeferreds = []; - tm.working = []; - - let concurrency; - - if ((typeof(navigator) === "object") && navigator.hardwareConcurrency) { - concurrency = navigator.hardwareConcurrency; - } else { - concurrency = os.cpus().length; - } - - if(concurrency == 0){ - concurrency = 2; - } - - // Limit to 64 threads for memory reasons. - if (concurrency>64) concurrency=64; - tm.concurrency = concurrency; - - for (let i = 0; i 0); i++) { - if (this.working[i] == false) { - const work = this.actionQueue.shift(); - this.postAction(i, work.data, work.transfers, work.deferred); - } - } - } - - queueAction(actionData, transfers) { - const d = new Deferred(); - - if (this.singleThread) { - const res = this.taskManager(actionData); - d.resolve(res); - } else { - this.actionQueue.push({ - data: actionData, - transfers: transfers, - deferred: d - }); - this.processWorks(); - } - return d.promise; - } - - resetMemory() { - this.u32[0] = this.initalPFree; - } - - allocBuff(buff) { - const pointer = this.alloc(buff.byteLength); - this.setBuff(pointer, buff); - return pointer; - } - - getBuff(pointer, length) { - return this.u8.slice(pointer, pointer+ length); - } - - setBuff(pointer, buffer) { - this.u8.set(new Uint8Array(buffer), pointer); - } - - alloc(length) { - while (this.u32[0] & 3) this.u32[0]++; // Return always aligned pointers - const res = this.u32[0]; - this.u32[0] += length; - return res; - } - - async terminate() { - for (let i=0; i=0; i--) { - if (!G.isZero(res)) { - for (let j=0; jMAX_CHUNK_SIZE) chunkSize = MAX_CHUNK_SIZE; - if (chunkSize { - if (logger) logger.debug(`Multiexp end: ${logText}: ${i}/${nPoints}`); - return r; - })); - } - - const result = await Promise.all(opPromises); - - let res = G.zero; - for (let i=result.length-1; i>=0; i--) { - res = G.add(res, result[i]); - } - - return res; - } - - G.multiExp = async function multiExpAffine(buffBases, buffScalars, logger, logText) { - return await _multiExp(buffBases, buffScalars, "jacobian", logger, logText); - }; - G.multiExpAffine = async function multiExpAffine(buffBases, buffScalars, logger, logText) { - return await _multiExp(buffBases, buffScalars, "affine", logger, logText); - }; -} - -function buildFFT(curve, groupName) { - const G = curve[groupName]; - const Fr = curve.Fr; - const tm = G.tm; - async function _fft(buff, inverse, inType, outType, logger, loggerTxt) { - - inType = inType || "affine"; - outType = outType || "affine"; - const MAX_BITS_THREAD = 14; - - let sIn, sMid, sOut, fnIn2Mid, fnMid2Out, fnFFTMix, fnFFTJoin, fnFFTFinal; - if (groupName == "G1") { - if (inType == "affine") { - sIn = G.F.n8*2; - fnIn2Mid = "g1m_batchToJacobian"; - } else { - sIn = G.F.n8*3; - } - sMid = G.F.n8*3; - if (inverse) { - fnFFTFinal = "g1m_fftFinal"; - } - fnFFTJoin = "g1m_fftJoin"; - fnFFTMix = "g1m_fftMix"; - - if (outType == "affine") { - sOut = G.F.n8*2; - fnMid2Out = "g1m_batchToAffine"; - } else { - sOut = G.F.n8*3; - } - - } else if (groupName == "G2") { - if (inType == "affine") { - sIn = G.F.n8*2; - fnIn2Mid = "g2m_batchToJacobian"; - } else { - sIn = G.F.n8*3; - } - sMid = G.F.n8*3; - if (inverse) { - fnFFTFinal = "g2m_fftFinal"; - } - fnFFTJoin = "g2m_fftJoin"; - fnFFTMix = "g2m_fftMix"; - if (outType == "affine") { - sOut = G.F.n8*2; - fnMid2Out = "g2m_batchToAffine"; - } else { - sOut = G.F.n8*3; - } - } else if (groupName == "Fr") { - sIn = G.n8; - sMid = G.n8; - sOut = G.n8; - if (inverse) { - fnFFTFinal = "frm_fftFinal"; - } - fnFFTMix = "frm_fftMix"; - fnFFTJoin = "frm_fftJoin"; - } - - - let returnArray = false; - if (Array.isArray(buff)) { - buff = array2buffer(buff, sIn); - returnArray = true; - } else { - buff = buff.slice(0, buff.byteLength); - } - - const nPoints = buff.byteLength / sIn; - const bits = log2(nPoints); - - if ((1 << bits) != nPoints) { - throw new Error("fft must be multiple of 2" ); - } - - if (bits == Fr.s +1) { - let buffOut; - - if (inverse) { - buffOut = await _fftExtInv(buff, inType, outType, logger, loggerTxt); - } else { - buffOut = await _fftExt(buff, inType, outType, logger, loggerTxt); - } - - if (returnArray) { - return buffer2array(buffOut, sOut); - } else { - return buffOut; - } - } - - let inv; - if (inverse) { - inv = Fr.inv(Fr.e(nPoints)); - } - - let buffOut; - - buffReverseBits(buff, sIn); - - let chunks; - let pointsInChunk = Math.min(1 << MAX_BITS_THREAD, nPoints); - let nChunks = nPoints / pointsInChunk; - - while ((nChunks < tm.concurrency)&&(pointsInChunk>=16)) { - nChunks *= 2; - pointsInChunk /= 2; - } - - const l2Chunk = log2(pointsInChunk); - - const promises = []; - for (let i = 0; i< nChunks; i++) { - if (logger) logger.debug(`${loggerTxt}: fft ${bits} mix start: ${i}/${nChunks}`); - const task = []; - task.push({cmd: "ALLOC", var: 0, len: sMid*pointsInChunk}); - const buffChunk = buff.slice( (pointsInChunk * i)*sIn, (pointsInChunk * (i+1))*sIn); - task.push({cmd: "SET", var: 0, buff: buffChunk}); - if (fnIn2Mid) { - task.push({cmd: "CALL", fnName:fnIn2Mid, params: [{var:0}, {val: pointsInChunk}, {var: 0}]}); - } - for (let j=1; j<=l2Chunk;j++) { - task.push({cmd: "CALL", fnName:fnFFTMix, params: [{var:0}, {val: pointsInChunk}, {val: j}]}); - } - - if (l2Chunk==bits) { - if (fnFFTFinal) { - task.push({cmd: "ALLOCSET", var: 1, buff: inv}); - task.push({cmd: "CALL", fnName: fnFFTFinal, params:[ - {var: 0}, - {val: pointsInChunk}, - {var: 1}, - ]}); - } - if (fnMid2Out) { - task.push({cmd: "CALL", fnName:fnMid2Out, params: [{var:0}, {val: pointsInChunk}, {var: 0}]}); - } - task.push({cmd: "GET", out: 0, var: 0, len: pointsInChunk*sOut}); - } else { - task.push({cmd: "GET", out:0, var: 0, len: sMid*pointsInChunk}); - } - promises.push(tm.queueAction(task).then( (r) => { - if (logger) logger.debug(`${loggerTxt}: fft ${bits} mix end: ${i}/${nChunks}`); - return r; - })); - } - - chunks = await Promise.all(promises); - for (let i = 0; i< nChunks; i++) chunks[i] = chunks[i][0]; - - for (let i = l2Chunk+1; i<=bits; i++) { - if (logger) logger.debug(`${loggerTxt}: fft ${bits} join: ${i}/${bits}`); - const nGroups = 1 << (bits - i); - const nChunksPerGroup = nChunks / nGroups; - const opPromises = []; - for (let j=0; j { - if (logger) logger.debug(`${loggerTxt}: fft ${bits} join ${i}/${bits} ${j+1}/${nGroups} ${k}/${nChunksPerGroup/2}`); - return r; - })); - } - } - - const res = await Promise.all(opPromises); - for (let j=0; j0; i--) { - buffOut.set(chunks[i], p); - p += pointsInChunk*sOut; - delete chunks[i]; // Liberate mem - } - buffOut.set(chunks[0].slice(0, (pointsInChunk-1)*sOut), p); - delete chunks[0]; - } else { - for (let i=0; i (1<<28)) { - buffOut = new BigBuffer(res1[0].byteLength*2); - } else { - buffOut = new Uint8Array(res1[0].byteLength*2); - } - - buffOut.set(res1[0]); - buffOut.set(res1[1], res1[0].byteLength); - - return buffOut; - } - - async function _fftExtInv(buff, inType, outType, logger, loggerTxt) { - let b1, b2; - b1 = buff.slice( 0 , buff.byteLength/2); - b2 = buff.slice( buff.byteLength/2, buff.byteLength); - - const promises = []; - - promises.push( _fft(b1, true, inType, "jacobian", logger, loggerTxt)); - promises.push( _fft(b2, true, inType, "jacobian", logger, loggerTxt)); - - [b1, b2] = await Promise.all(promises); - - const res1 = await _fftJoinExt(b1, b2, "fftJoinExtInv", Fr.one, Fr.shiftInv, "jacobian", outType, logger, loggerTxt); - - let buffOut; - if (res1[0].byteLength > (1<<28)) { - buffOut = new BigBuffer(res1[0].byteLength*2); - } else { - buffOut = new Uint8Array(res1[0].byteLength*2); - } - - buffOut.set(res1[0]); - buffOut.set(res1[1], res1[0].byteLength); - - return buffOut; - } - - - async function _fftJoinExt(buff1, buff2, fn, first, inc, inType, outType, logger, loggerTxt) { - const MAX_CHUNK_SIZE = 1<<16; - const MIN_CHUNK_SIZE = 1<<4; - - let fnName; - let fnIn2Mid, fnMid2Out; - let sOut, sIn, sMid; - - if (groupName == "G1") { - if (inType == "affine") { - sIn = G.F.n8*2; - fnIn2Mid = "g1m_batchToJacobian"; - } else { - sIn = G.F.n8*3; - } - sMid = G.F.n8*3; - fnName = "g1m_"+fn; - if (outType == "affine") { - fnMid2Out = "g1m_batchToAffine"; - sOut = G.F.n8*2; - } else { - sOut = G.F.n8*3; - } - } else if (groupName == "G2") { - if (inType == "affine") { - sIn = G.F.n8*2; - fnIn2Mid = "g2m_batchToJacobian"; - } else { - sIn = G.F.n8*3; - } - fnName = "g2m_"+fn; - sMid = G.F.n8*3; - if (outType == "affine") { - fnMid2Out = "g2m_batchToAffine"; - sOut = G.F.n8*2; - } else { - sOut = G.F.n8*3; - } - } else if (groupName == "Fr") { - sIn = Fr.n8; - sOut = Fr.n8; - sMid = Fr.n8; - fnName = "frm_" + fn; - } else { - throw new Error("Invalid group"); - } - - if (buff1.byteLength != buff2.byteLength) { - throw new Error("Invalid buffer size"); - } - const nPoints = Math.floor(buff1.byteLength / sIn); - if (nPoints != 1 << log2(nPoints)) { - throw new Error("Invalid number of points"); - } - - let chunkSize = Math.floor(nPoints /tm.concurrency); - if (chunkSize < MIN_CHUNK_SIZE) chunkSize = MIN_CHUNK_SIZE; - if (chunkSize > MAX_CHUNK_SIZE) chunkSize = MAX_CHUNK_SIZE; - - const opPromises = []; - - for (let i=0; i { - if (logger) logger.debug(`${loggerTxt}: fftJoinExt End: ${i}/${nPoints}`); - return r; - }) - ); - } - - const result = await Promise.all(opPromises); - - let fullBuffOut1; - let fullBuffOut2; - if (nPoints * sOut > 1<<28) { - fullBuffOut1 = new BigBuffer(nPoints*sOut); - fullBuffOut2 = new BigBuffer(nPoints*sOut); - } else { - fullBuffOut1 = new Uint8Array(nPoints*sOut); - fullBuffOut2 = new Uint8Array(nPoints*sOut); - } - - let p =0; - for (let i=0; i Fr.s+1) { - if (logger) logger.error("lagrangeEvaluations input too big"); - throw new Error("lagrangeEvaluations input too big"); - } - - let t0 = buff.slice(0, buff.byteLength/2); - let t1 = buff.slice(buff.byteLength/2, buff.byteLength); - - - const shiftToSmallM = Fr.exp(Fr.shift, nPoints/2); - const sConst = Fr.inv( Fr.sub(Fr.one, shiftToSmallM)); - - [t0, t1] = await _fftJoinExt(t0, t1, "prepareLagrangeEvaluation", sConst, Fr.shiftInv, inType, "jacobian", logger, loggerTxt + " prep"); - - const promises = []; - - promises.push( _fft(t0, true, "jacobian", outType, logger, loggerTxt + " t0")); - promises.push( _fft(t1, true, "jacobian", outType, logger, loggerTxt + " t1")); - - [t0, t1] = await Promise.all(promises); - - let buffOut; - if (t0.byteLength > (1<<28)) { - buffOut = new BigBuffer(t0.byteLength*2); - } else { - buffOut = new Uint8Array(t0.byteLength*2); - } - - buffOut.set(t0); - buffOut.set(t1, t0.byteLength); - - return buffOut; - }; - - G.fftMix = async function fftMix(buff) { - const sG = G.F.n8*3; - let fnName, fnFFTJoin; - if (groupName == "G1") { - fnName = "g1m_fftMix"; - fnFFTJoin = "g1m_fftJoin"; - } else if (groupName == "G2") { - fnName = "g2m_fftMix"; - fnFFTJoin = "g2m_fftJoin"; - } else if (groupName == "Fr") { - fnName = "frm_fftMix"; - fnFFTJoin = "frm_fftJoin"; - } else { - throw new Error("Invalid group"); - } - - const nPoints = Math.floor(buff.byteLength / sG); - const power = log2(nPoints); - - let nChunks = 1 << log2(tm.concurrency); - - if (nPoints <= nChunks*2) nChunks = 1; - - const pointsPerChunk = nPoints / nChunks; - - const powerChunk = log2(pointsPerChunk); - - const opPromises = []; - for (let i=0; i=0; i--) { - fullBuffOut.set(result[i][0], p); - p+=result[i][0].byteLength; - } - - return fullBuffOut; - }; -} - -async function buildEngine(params) { - - const tm = await buildThreadManager(params.wasm, params.singleThread); - - - const curve = {}; - - curve.q = e(params.wasm.q); - curve.r = e(params.wasm.r); - curve.name = params.name; - curve.tm = tm; - curve.prePSize = params.wasm.prePSize; - curve.preQSize = params.wasm.preQSize; - curve.Fr = new WasmField1(tm, "frm", params.n8r, params.r); - curve.F1 = new WasmField1(tm, "f1m", params.n8q, params.q); - curve.F2 = new WasmField2(tm, "f2m", curve.F1); - curve.G1 = new WasmCurve(tm, "g1m", curve.F1, params.wasm.pG1gen, params.wasm.pG1b, params.cofactorG1); - curve.G2 = new WasmCurve(tm, "g2m", curve.F2, params.wasm.pG2gen, params.wasm.pG2b, params.cofactorG2); - curve.F6 = new WasmField3(tm, "f6m", curve.F2); - curve.F12 = new WasmField2(tm, "ftm", curve.F6); - - curve.Gt = curve.F12; - - buildBatchApplyKey(curve, "G1"); - buildBatchApplyKey(curve, "G2"); - buildBatchApplyKey(curve, "Fr"); - - buildMultiexp(curve, "G1"); - buildMultiexp(curve, "G2"); - - buildFFT(curve, "G1"); - buildFFT(curve, "G2"); - buildFFT(curve, "Fr"); - - buildPairing(curve); - - curve.array2buffer = function(arr, sG) { - const buff = new Uint8Array(sG*arr.length); - - for (let i=0; i. -*/ - -const bigInt = BigIntegerExports; - -function toNumber(n) { - let v; - if (typeof n=="string") { - if (n.slice(0,2).toLowerCase() == "0x") { - v = bigInt(n.slice(2),16); - } else { - v = bigInt(n); - } - } else { - v = bigInt(n); - } - return v; -} - -function u32(n) { - const b = []; - const v = toNumber(n); - b.push(v.and(0xFF).toJSNumber()); - b.push(v.shiftRight(8).and(0xFF).toJSNumber()); - b.push(v.shiftRight(16).and(0xFF).toJSNumber()); - b.push(v.shiftRight(24).and(0xFF).toJSNumber()); - return b; -} - -function u64(n) { - const b = []; - const v = toNumber(n); - b.push(v.and(0xFF).toJSNumber()); - b.push(v.shiftRight(8).and(0xFF).toJSNumber()); - b.push(v.shiftRight(16).and(0xFF).toJSNumber()); - b.push(v.shiftRight(24).and(0xFF).toJSNumber()); - b.push(v.shiftRight(32).and(0xFF).toJSNumber()); - b.push(v.shiftRight(40).and(0xFF).toJSNumber()); - b.push(v.shiftRight(48).and(0xFF).toJSNumber()); - b.push(v.shiftRight(56).and(0xFF).toJSNumber()); - return b; -} - -function toUTF8Array(str) { - var utf8 = []; - for (var i=0; i < str.length; i++) { - var charcode = str.charCodeAt(i); - if (charcode < 0x80) utf8.push(charcode); - else if (charcode < 0x800) { - utf8.push(0xc0 | (charcode >> 6), - 0x80 | (charcode & 0x3f)); - } - else if (charcode < 0xd800 || charcode >= 0xe000) { - utf8.push(0xe0 | (charcode >> 12), - 0x80 | ((charcode>>6) & 0x3f), - 0x80 | (charcode & 0x3f)); - } - // surrogate pair - else { - i++; - // UTF-16 encodes 0x10000-0x10FFFF by - // subtracting 0x10000 and splitting the - // 20 bits of 0x0-0xFFFFF into two halves - charcode = 0x10000 + (((charcode & 0x3ff)<<10) - | (str.charCodeAt(i) & 0x3ff)); - utf8.push(0xf0 | (charcode >>18), - 0x80 | ((charcode>>12) & 0x3f), - 0x80 | ((charcode>>6) & 0x3f), - 0x80 | (charcode & 0x3f)); - } - } - return utf8; -} - -function string(str) { - const bytes = toUTF8Array(str); - return [ ...varuint32(bytes.length), ...bytes ]; -} - -function varuint(n) { - const code = []; - let v = toNumber(n); - if (v.isNegative()) throw new Error("Number cannot be negative"); - while (!v.isZero()) { - code.push(v.and(0x7F).toJSNumber()); - v = v.shiftRight(7); - } - if (code.length==0) code.push(0); - for (let i=0; i. -*/ - -const utils$2 = utils$3; - -let CodeBuilder$1 = class CodeBuilder { - constructor(func) { - this.func = func; - this.functionName = func.functionName; - this.module = func.module; - } - - setLocal(localName, valCode) { - const idx = this.func.localIdxByName[localName]; - if (idx === undefined) - throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); - return [...valCode, 0x21, ...utils$2.varuint32( idx )]; - } - - teeLocal(localName, valCode) { - const idx = this.func.localIdxByName[localName]; - if (idx === undefined) - throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); - return [...valCode, 0x22, ...utils$2.varuint32( idx )]; - } - - getLocal(localName) { - const idx = this.func.localIdxByName[localName]; - if (idx === undefined) - throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); - return [0x20, ...utils$2.varuint32( idx )]; - } - - i64_load8_s(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 0 : _align; // 8 bits alignment by default - return [...idxCode, 0x30, align, ...utils$2.varuint32(offset)]; - } - - i64_load8_u(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 0 : _align; // 8 bits alignment by default - return [...idxCode, 0x31, align, ...utils$2.varuint32(offset)]; - } - - i64_load16_s(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 1 : _align; // 16 bits alignment by default - return [...idxCode, 0x32, align, ...utils$2.varuint32(offset)]; - } - - i64_load16_u(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 1 : _align; // 16 bits alignment by default - return [...idxCode, 0x33, align, ...utils$2.varuint32(offset)]; - } - - i64_load32_s(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default - return [...idxCode, 0x34, align, ...utils$2.varuint32(offset)]; - } - - i64_load32_u(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default - return [...idxCode, 0x35, align, ...utils$2.varuint32(offset)]; - } - - i64_load(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 3 : _align; // 64 bits alignment by default - return [...idxCode, 0x29, align, ...utils$2.varuint32(offset)]; - } - - - i64_store(idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (Array.isArray(_offset)) { - offset = 0; - align = 3; - codeVal = _offset; - } else if (Array.isArray(_align)) { - offset = _offset; - align = 3; - codeVal = _align; - } else if (Array.isArray(_codeVal)) { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - return [...idxCode, ...codeVal, 0x37, align, ...utils$2.varuint32(offset)]; - } - - i64_store32(idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (Array.isArray(_offset)) { - offset = 0; - align = 2; - codeVal = _offset; - } else if (Array.isArray(_align)) { - offset = _offset; - align = 2; - codeVal = _align; - } else if (Array.isArray(_codeVal)) { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - return [...idxCode, ...codeVal, 0x3e, align, ...utils$2.varuint32(offset)]; - } - - - i64_store16(idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (Array.isArray(_offset)) { - offset = 0; - align = 1; - codeVal = _offset; - } else if (Array.isArray(_align)) { - offset = _offset; - align = 1; - codeVal = _align; - } else if (Array.isArray(_codeVal)) { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - return [...idxCode, ...codeVal, 0x3d, align, ...utils$2.varuint32(offset)]; - } - - - i64_store8(idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (Array.isArray(_offset)) { - offset = 0; - align = 0; - codeVal = _offset; - } else if (Array.isArray(_align)) { - offset = _offset; - align = 0; - codeVal = _align; - } else if (Array.isArray(_codeVal)) { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - return [...idxCode, ...codeVal, 0x3c, align, ...utils$2.varuint32(offset)]; - } - - i32_load8_s(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default - return [...idxCode, 0x2c, align, ...utils$2.varuint32(offset)]; - } - - i32_load8_u(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default - return [...idxCode, 0x2d, align, ...utils$2.varuint32(offset)]; - } - - i32_load16_s(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default - return [...idxCode, 0x2e, align, ...utils$2.varuint32(offset)]; - } - - i32_load16_u(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default - return [...idxCode, 0x2f, align, ...utils$2.varuint32(offset)]; - } - - i32_load(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default - return [...idxCode, 0x28, align, ...utils$2.varuint32(offset)]; - } - - i32_store(idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (Array.isArray(_offset)) { - offset = 0; - align = 2; - codeVal = _offset; - } else if (Array.isArray(_align)) { - offset = _offset; - align = 2; - codeVal = _align; - } else if (Array.isArray(_codeVal)) { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - return [...idxCode, ...codeVal, 0x36, align, ...utils$2.varuint32(offset)]; - } - - - i32_store16(idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (Array.isArray(_offset)) { - offset = 0; - align = 1; - codeVal = _offset; - } else if (Array.isArray(_align)) { - offset = _offset; - align = 1; - codeVal = _align; - } else if (Array.isArray(_codeVal)) { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - return [...idxCode, ...codeVal, 0x3b, align, ...utils$2.varuint32(offset)]; - } - - i32_store8(idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (Array.isArray(_offset)) { - offset = 0; - align = 0; - codeVal = _offset; - } else if (Array.isArray(_align)) { - offset = _offset; - align = 0; - codeVal = _align; - } else if (Array.isArray(_codeVal)) { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - return [...idxCode, ...codeVal, 0x3a, align, ...utils$2.varuint32(offset)]; - } - - call(fnName, ...args) { - const idx = this.module.functionIdxByName[fnName]; - if (idx === undefined) - throw new Error(`Function not defined: Function: ${fnName}`); - return [...[].concat(...args), 0x10, ...utils$2.varuint32(idx)]; - } - - call_indirect(fnIdx, ...args) { - return [...[].concat(...args), ...fnIdx, 0x11, 0, 0]; - } - - if(condCode, thenCode, elseCode) { - if (elseCode) { - return [...condCode, 0x04, 0x40, ...thenCode, 0x05, ...elseCode, 0x0b]; - } else { - return [...condCode, 0x04, 0x40, ...thenCode, 0x0b]; - } - } - - block(bCode) { return [0x02, 0x40, ...bCode, 0x0b]; } - loop(...args) { - return [0x03, 0x40, ...[].concat(...[...args]), 0x0b]; - } - br_if(relPath, condCode) { return [...condCode, 0x0d, ...utils$2.varuint32(relPath)]; } - br(relPath) { return [0x0c, ...utils$2.varuint32(relPath)]; } - ret(rCode) { return [...rCode, 0x0f]; } - drop(dCode) { return [...dCode, 0x1a]; } - - i64_const(num) { return [0x42, ...utils$2.varint64(num)]; } - i32_const(num) { return [0x41, ...utils$2.varint32(num)]; } - - - i64_eqz(opcode) { return [...opcode, 0x50]; } - i64_eq(op1code, op2code) { return [...op1code, ...op2code, 0x51]; } - i64_ne(op1code, op2code) { return [...op1code, ...op2code, 0x52]; } - i64_lt_s(op1code, op2code) { return [...op1code, ...op2code, 0x53]; } - i64_lt_u(op1code, op2code) { return [...op1code, ...op2code, 0x54]; } - i64_gt_s(op1code, op2code) { return [...op1code, ...op2code, 0x55]; } - i64_gt_u(op1code, op2code) { return [...op1code, ...op2code, 0x56]; } - i64_le_s(op1code, op2code) { return [...op1code, ...op2code, 0x57]; } - i64_le_u(op1code, op2code) { return [...op1code, ...op2code, 0x58]; } - i64_ge_s(op1code, op2code) { return [...op1code, ...op2code, 0x59]; } - i64_ge_u(op1code, op2code) { return [...op1code, ...op2code, 0x5a]; } - i64_add(op1code, op2code) { return [...op1code, ...op2code, 0x7c]; } - i64_sub(op1code, op2code) { return [...op1code, ...op2code, 0x7d]; } - i64_mul(op1code, op2code) { return [...op1code, ...op2code, 0x7e]; } - i64_div_s(op1code, op2code) { return [...op1code, ...op2code, 0x7f]; } - i64_div_u(op1code, op2code) { return [...op1code, ...op2code, 0x80]; } - i64_rem_s(op1code, op2code) { return [...op1code, ...op2code, 0x81]; } - i64_rem_u(op1code, op2code) { return [...op1code, ...op2code, 0x82]; } - i64_and(op1code, op2code) { return [...op1code, ...op2code, 0x83]; } - i64_or(op1code, op2code) { return [...op1code, ...op2code, 0x84]; } - i64_xor(op1code, op2code) { return [...op1code, ...op2code, 0x85]; } - i64_shl(op1code, op2code) { return [...op1code, ...op2code, 0x86]; } - i64_shr_s(op1code, op2code) { return [...op1code, ...op2code, 0x87]; } - i64_shr_u(op1code, op2code) { return [...op1code, ...op2code, 0x88]; } - i64_extend_i32_s(op1code) { return [...op1code, 0xac]; } - i64_extend_i32_u(op1code) { return [...op1code, 0xad]; } - i64_clz(op1code) { return [...op1code, 0x79]; } - i64_ctz(op1code) { return [...op1code, 0x7a]; } - - i32_eqz(op1code) { return [...op1code, 0x45]; } - i32_eq(op1code, op2code) { return [...op1code, ...op2code, 0x46]; } - i32_ne(op1code, op2code) { return [...op1code, ...op2code, 0x47]; } - i32_lt_s(op1code, op2code) { return [...op1code, ...op2code, 0x48]; } - i32_lt_u(op1code, op2code) { return [...op1code, ...op2code, 0x49]; } - i32_gt_s(op1code, op2code) { return [...op1code, ...op2code, 0x4a]; } - i32_gt_u(op1code, op2code) { return [...op1code, ...op2code, 0x4b]; } - i32_le_s(op1code, op2code) { return [...op1code, ...op2code, 0x4c]; } - i32_le_u(op1code, op2code) { return [...op1code, ...op2code, 0x4d]; } - i32_ge_s(op1code, op2code) { return [...op1code, ...op2code, 0x4e]; } - i32_ge_u(op1code, op2code) { return [...op1code, ...op2code, 0x4f]; } - i32_add(op1code, op2code) { return [...op1code, ...op2code, 0x6a]; } - i32_sub(op1code, op2code) { return [...op1code, ...op2code, 0x6b]; } - i32_mul(op1code, op2code) { return [...op1code, ...op2code, 0x6c]; } - i32_div_s(op1code, op2code) { return [...op1code, ...op2code, 0x6d]; } - i32_div_u(op1code, op2code) { return [...op1code, ...op2code, 0x6e]; } - i32_rem_s(op1code, op2code) { return [...op1code, ...op2code, 0x6f]; } - i32_rem_u(op1code, op2code) { return [...op1code, ...op2code, 0x70]; } - i32_and(op1code, op2code) { return [...op1code, ...op2code, 0x71]; } - i32_or(op1code, op2code) { return [...op1code, ...op2code, 0x72]; } - i32_xor(op1code, op2code) { return [...op1code, ...op2code, 0x73]; } - i32_shl(op1code, op2code) { return [...op1code, ...op2code, 0x74]; } - i32_shr_s(op1code, op2code) { return [...op1code, ...op2code, 0x75]; } - i32_shr_u(op1code, op2code) { return [...op1code, ...op2code, 0x76]; } - i32_rotl(op1code, op2code) { return [...op1code, ...op2code, 0x77]; } - i32_rotr(op1code, op2code) { return [...op1code, ...op2code, 0x78]; } - i32_wrap_i64(op1code) { return [...op1code, 0xa7]; } - i32_clz(op1code) { return [...op1code, 0x67]; } - i32_ctz(op1code) { return [...op1code, 0x68]; } - - unreachable() { return [ 0x0 ]; } - - current_memory() { return [ 0x3f, 0]; } - - comment() { return []; } -}; - -var codebuilder = CodeBuilder$1; - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmbuilder - - wasmbuilder is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmbuilder is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmbuilder. If not, see . -*/ - -const CodeBuilder = codebuilder; -const utils$1 = utils$3; - -const typeCodes = { - "i32": 0x7f, - "i64": 0x7e, - "f32": 0x7d, - "f64": 0x7c, - "anyfunc": 0x70, - "func": 0x60, - "emptyblock": 0x40 -}; - - -let FunctionBuilder$1 = class FunctionBuilder { - - constructor (module, fnName, fnType, moduleName, fieldName) { - if (fnType == "import") { - this.fnType = "import"; - this.moduleName = moduleName; - this.fieldName = fieldName; - } else if (fnType == "internal") { - this.fnType = "internal"; - } else { - throw new Error("Invalid function fnType: " + fnType); - } - this.module = module; - this.fnName = fnName; - this.params = []; - this.locals = []; - this.localIdxByName = {}; - this.code = []; - this.returnType = null; - this.nextLocal =0; - } - - addParam(paramName, paramType) { - if (this.localIdxByName[paramName]) - throw new Error(`param already exists. Function: ${this.fnName}, Param: ${paramName} `); - const idx = this.nextLocal++; - this.localIdxByName[paramName] = idx; - this.params.push({ - type: paramType - }); - } - - addLocal(localName, localType, _length) { - const length = _length || 1; - if (this.localIdxByName[localName]) - throw new Error(`local already exists. Function: ${this.fnName}, Param: ${localName} `); - const idx = this.nextLocal++; - this.localIdxByName[localName] = idx; - this.locals.push({ - type: localType, - length: length - }); - } - - setReturnType(returnType) { - if (this.returnType) - throw new Error(`returnType already defined. Function: ${this.fnName}`); - this.returnType = returnType; - } - - getSignature() { - const params = [...utils$1.varuint32(this.params.length), ...this.params.map((p) => typeCodes[p.type])]; - const returns = this.returnType ? [0x01, typeCodes[this.returnType]] : [0]; - return [0x60, ...params, ...returns]; - } - - getBody() { - const locals = this.locals.map((l) => [ - ...utils$1.varuint32(l.length), - typeCodes[l.type] - ]); - - const body = [ - ...utils$1.varuint32(this.locals.length), - ...[].concat(...locals), - ...this.code, - 0x0b - ]; - return [ - ...utils$1.varuint32(body.length), - ...body - ]; - } - - addCode(...code) { - this.code.push(...[].concat(...[...code])); - } - - getCodeBuilder() { - return new CodeBuilder(this); - } -}; - -var functionbuilder = FunctionBuilder$1; - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmbuilder - - wasmbuilder is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmbuilder is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmbuilder. If not, see . -*/ - -const FunctionBuilder = functionbuilder; -const utils = utils$3; - -let ModuleBuilder$1 = class ModuleBuilder { - - constructor() { - this.functions = []; - this.functionIdxByName = {}; - this.nImportFunctions = 0; - this.nInternalFunctions =0; - this.memory = { - pagesSize: 1, - moduleName: "env", - fieldName: "memory" - }; - this.free = 8; - this.datas = []; - this.modules = {}; - this.exports = []; - this.functionsTable = []; - } - - build() { - this._setSignatures(); - return new Uint8Array([ - ...utils.u32(0x6d736100), - ...utils.u32(1), - ...this._buildType(), - ...this._buildImport(), - ...this._buildFunctionDeclarations(), - ...this._buildFunctionsTable(), - ...this._buildExports(), - ...this._buildElements(), - ...this._buildCode(), - ...this._buildData() - ]); - } - - addFunction(fnName) { - if (typeof(this.functionIdxByName[fnName]) !== "undefined") - throw new Error(`Function already defined: ${fnName}`); - - const idx = this.functions.length; - this.functionIdxByName[fnName] = idx; - - this.functions.push(new FunctionBuilder(this, fnName, "internal")); - - this.nInternalFunctions++; - return this.functions[idx]; - } - - addIimportFunction(fnName, moduleName, _fieldName) { - if (typeof(this.functionIdxByName[fnName]) !== "undefined") - throw new Error(`Function already defined: ${fnName}`); - - if ( (this.functions.length>0) - &&(this.functions[this.functions.length-1].type == "internal")) - throw new Error(`Import functions must be declared before internal: ${fnName}`); - - let fieldName = _fieldName || fnName; - - const idx = this.functions.length; - this.functionIdxByName[fnName] = idx; - - this.functions.push(new FunctionBuilder(this, fnName, "import", moduleName, fieldName)); - - this.nImportFunctions ++; - return this.functions[idx]; - } - - setMemory(pagesSize, moduleName, fieldName) { - this.memory = { - pagesSize: pagesSize, - moduleName: moduleName || "env", - fieldName: fieldName || "memory" - }; - } - - exportFunction(fnName, _exportName) { - const exportName = _exportName || fnName; - if (typeof(this.functionIdxByName[fnName]) === "undefined") - throw new Error(`Function not defined: ${fnName}`); - const idx = this.functionIdxByName[fnName]; - if (exportName != fnName) { - this.functionIdxByName[exportName] = idx; - } - this.exports.push({ - exportName: exportName, - idx: idx - }); - } - - addFunctionToTable(fnName) { - const idx = this.functionIdxByName[fnName]; - this.functionsTable.push(idx); - } - - addData(offset, bytes) { - this.datas.push({ - offset: offset, - bytes: bytes - }); - } - - alloc(a, b) { - let size; - let bytes; - if ((Array.isArray(a) || ArrayBuffer.isView(a)) && (typeof(b) === "undefined")) { - size = a.length; - bytes = a; - } else { - size = a; - bytes = b; - } - size = (((size-1)>>3) +1)<<3; // Align to 64 bits. - const p = this.free; - this.free += size; - if (bytes) { - this.addData(p, bytes); - } - return p; - } - - allocString(s) { - const encoder = new globalThis.TextEncoder(); - const uint8array = encoder.encode(s); - return this.alloc([...uint8array, 0]); - } - - _setSignatures() { - this.signatures = []; - const signatureIdxByName = {}; - if (this.functionsTable.length>0) { - const signature = this.functions[this.functionsTable[0]].getSignature(); - const signatureName = "s_"+utils.toHexString(signature); - signatureIdxByName[signatureName] = 0; - this.signatures.push(signature); - } - for (let i=0; i. -*/ - -var ModuleBuilder = modulebuilder; - -globalThis.curve_bn128 = null; - -async function buildBn128(singleThread, plugins) { - - const moduleBuilder = new ModuleBuilder(); - moduleBuilder.setMemory(25); - buildBn128$1(moduleBuilder); - - if (plugins) plugins(moduleBuilder); - - const bn128wasm = {}; - - bn128wasm.code = moduleBuilder.build(); - bn128wasm.pq = moduleBuilder.modules.f1m.pq; - bn128wasm.pr = moduleBuilder.modules.frm.pq; - bn128wasm.pG1gen = moduleBuilder.modules.bn128.pG1gen; - bn128wasm.pG1zero = moduleBuilder.modules.bn128.pG1zero; - bn128wasm.pG1b = moduleBuilder.modules.bn128.pG1b; - bn128wasm.pG2gen = moduleBuilder.modules.bn128.pG2gen; - bn128wasm.pG2zero = moduleBuilder.modules.bn128.pG2zero; - bn128wasm.pG2b = moduleBuilder.modules.bn128.pG2b; - bn128wasm.pOneT = moduleBuilder.modules.bn128.pOneT; - bn128wasm.prePSize = moduleBuilder.modules.bn128.prePSize; - bn128wasm.preQSize = moduleBuilder.modules.bn128.preQSize; - bn128wasm.n8q = 32; - bn128wasm.n8r = 32; - bn128wasm.q = moduleBuilder.modules.bn128.q; - bn128wasm.r = moduleBuilder.modules.bn128.r; - - if ((!singleThread) && (globalThis.curve_bn128)) return globalThis.curve_bn128; - const params = { - name: "bn128", - wasm: bn128wasm, - q: e("21888242871839275222246405745257275088696311157297823662689037894645226208583"), - r: e("21888242871839275222246405745257275088548364400416034343698204186575808495617"), - n8q: 32, - n8r: 32, - cofactorG2: e("30644e72e131a029b85045b68181585e06ceecda572a2489345f2299c0f9fa8d", 16), - singleThread: singleThread ? true : false - }; - - const curve = await buildEngine(params); - curve.terminate = async function () { - if (!params.singleThread) { - globalThis.curve_bn128 = null; - await this.tm.terminate(); - } - }; - - if (!singleThread) { - globalThis.curve_bn128 = curve; - } - - return curve; -} - -globalThis.curve_bls12381 = null; - -async function buildBls12381(singleThread, plugins) { - - const moduleBuilder = new ModuleBuilder(); - moduleBuilder.setMemory(25); - buildBls12381$1(moduleBuilder); - - if (plugins) plugins(moduleBuilder); - - const bls12381wasm = {}; - - bls12381wasm.code = moduleBuilder.build(); - bls12381wasm.pq = moduleBuilder.modules.f1m.pq; - bls12381wasm.pr = moduleBuilder.modules.frm.pq; - bls12381wasm.pG1gen = moduleBuilder.modules.bls12381.pG1gen; - bls12381wasm.pG1zero = moduleBuilder.modules.bls12381.pG1zero; - bls12381wasm.pG1b = moduleBuilder.modules.bls12381.pG1b; - bls12381wasm.pG2gen = moduleBuilder.modules.bls12381.pG2gen; - bls12381wasm.pG2zero = moduleBuilder.modules.bls12381.pG2zero; - bls12381wasm.pG2b = moduleBuilder.modules.bls12381.pG2b; - bls12381wasm.pOneT = moduleBuilder.modules.bls12381.pOneT; - bls12381wasm.prePSize = moduleBuilder.modules.bls12381.prePSize; - bls12381wasm.preQSize = moduleBuilder.modules.bls12381.preQSize; - bls12381wasm.n8q = 48; - bls12381wasm.n8r = 32; - bls12381wasm.q = moduleBuilder.modules.bn128.q; - bls12381wasm.r = moduleBuilder.modules.bn128.r; - - - if ((!singleThread) && (globalThis.curve_bls12381)) return globalThis.curve_bls12381; - const params = { - name: "bls12381", - wasm: bls12381wasm, - q: e("1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab", 16), - r: e("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001", 16), - n8q: 48, - n8r: 32, - cofactorG1: e("0x396c8c005555e1568c00aaab0000aaab", 16), - cofactorG2: e("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5", 16), - singleThread: singleThread ? true : false - }; - - const curve = await buildEngine(params); - curve.terminate = async function () { - if (!params.singleThread) { - globalThis.curve_bls12381 = null; - await this.tm.terminate(); - } - }; - - if (!singleThread) { - globalThis.curve_bls12381 = curve; - } - - return curve; -} - -e("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001", 16); -e("21888242871839275222246405745257275088548364400416034343698204186575808495617"); - -e("1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab", 16); -e("21888242871839275222246405745257275088696311157297823662689037894645226208583"); - -async function getCurveFromName(name, singleThread, plugins) { - let curve; - const normName = normalizeName(name); - if (["BN128", "BN254", "ALTBN128"].indexOf(normName) >= 0) { - curve = await buildBn128(singleThread, plugins); - } else if (["BLS12381"].indexOf(normName) >= 0) { - curve = await buildBls12381(singleThread, plugins); - } else { - throw new Error(`Curve not supported: ${name}`); - } - return curve; - - function normalizeName(n) { - return n.toUpperCase().match(/[A-Za-z0-9]+/g).join(""); - } - -} - -const Scalar=_Scalar; - const version$2 = "logger/5.7.0"; let _permanentCensorErrors = false; @@ -18867,9 +923,6 @@ function isHexString(value, length) { if (typeof (value) !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) { return false; } - if (length && value.length !== 2 + 2 * length) { - return false; - } return true; } @@ -19616,7 +1669,7 @@ const SEED = "mimcsponge"; const NROUNDS = 220; async function buildMimcSponge() { - const bn128 = await getCurveFromName("bn128", true); + const bn128 = await ffjavascript.getCurveFromName("bn128", true); return new MimcSponge(bn128.Fr); } @@ -19630,7 +1683,7 @@ class MimcSponge { const F = this.F; if (typeof seed === "undefined") seed = SEED; const c = keccak256(toUtf8Bytes(seed+"_iv")); - const cn = Scalar.e(c); + const cn = ffjavascript.Scalar.e(c); const iv = cn.mod(F.p); return iv; }; @@ -19781,23 +1834,23 @@ var __async = (__this, __arguments, generator) => { function nodePostWork() { return __async(this, null, function* () { const { hash: hashFunction } = yield mimc.getHash(); - const { merkleTreeHeight, edge, elements, zeroElement } = threads.workerData; + const { merkleTreeHeight, edge, elements, zeroElement } = workerThreads.workerData; if (edge) { const merkleTree2 = new lib.PartialMerkleTree(merkleTreeHeight, edge, elements, { zeroElement, hashFunction }); - threads.parentPort.postMessage(merkleTree2.toString()); + workerThreads.parentPort.postMessage(merkleTree2.toString()); return; } const merkleTree = new lib.MerkleTree(merkleTreeHeight, elements, { zeroElement, hashFunction }); - threads.parentPort.postMessage(merkleTree.toString()); + workerThreads.parentPort.postMessage(merkleTree.toString()); }); } -if (isNode && threads) { +if (isNode && workerThreads) { nodePostWork(); } else if (!isNode && typeof addEventListener === "function" && typeof postMessage === "function") { addEventListener("message", (e) => __async(undefined, null, function* () { diff --git a/dist/merkleTreeWorker.umd.js b/dist/merkleTreeWorker.umd.js index e29bdd7..04b1c98 100644 --- a/dist/merkleTreeWorker.umd.js +++ b/dist/merkleTreeWorker.umd.js @@ -15,160 +15,160 @@ return /******/ (() => { // webpackBootstrap /***/ ((__unused_webpack_module, exports) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BaseTree = void 0; -class BaseTree { - get capacity() { - return 2 ** this.levels; - } - get layers() { - return this._layers.slice(); - } - get zeros() { - return this._zeros.slice(); - } - get elements() { - return this._layers[0].slice(); - } - get root() { - var _a; - return (_a = this._layers[this.levels][0]) !== null && _a !== void 0 ? _a : this._zeros[this.levels]; - } - /** - * Find an element in the tree - * @param elements elements of tree - * @param element An element to find - * @param comparator A function that checks leaf value equality - * @param fromIndex The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned - * @returns {number} Index if element is found, otherwise -1 - */ - static indexOf(elements, element, fromIndex, comparator) { - if (comparator) { - return elements.findIndex((el) => comparator(element, el)); - } - else { - return elements.indexOf(element, fromIndex); - } - } - /** - * Insert new element into the tree - * @param element Element to insert - */ - insert(element) { - if (this._layers[0].length >= this.capacity) { - throw new Error('Tree is full'); - } - this.update(this._layers[0].length, element); - } - /* - * Insert multiple elements into the tree. - * @param {Array} elements Elements to insert - */ - bulkInsert(elements) { - if (!elements.length) { - return; - } - if (this._layers[0].length + elements.length > this.capacity) { - throw new Error('Tree is full'); - } - // First we insert all elements except the last one - // updating only full subtree hashes (all layers where inserted element has odd index) - // the last element will update the full path to the root making the tree consistent again - for (let i = 0; i < elements.length - 1; i++) { - this._layers[0].push(elements[i]); - let level = 0; - let index = this._layers[0].length - 1; - while (index % 2 === 1) { - level++; - index >>= 1; - const left = this._layers[level - 1][index * 2]; - const right = this._layers[level - 1][index * 2 + 1]; - this._layers[level][index] = this._hashFn(left, right); - } - } - this.insert(elements[elements.length - 1]); - } - /** - * Change an element in the tree - * @param {number} index Index of element to change - * @param element Updated element value - */ - update(index, element) { - if (isNaN(Number(index)) || index < 0 || index > this._layers[0].length || index >= this.capacity) { - throw new Error('Insert index out of bounds: ' + index); - } - this._layers[0][index] = element; - this._processUpdate(index); - } - /** - * Get merkle path to a leaf - * @param {number} index Leaf index to generate path for - * @returns {{pathElements: Object[], pathIndex: number[]}} An object containing adjacent elements and left-right index - */ - path(index) { - if (isNaN(Number(index)) || index < 0 || index >= this._layers[0].length) { - throw new Error('Index out of bounds: ' + index); - } - let elIndex = +index; - const pathElements = []; - const pathIndices = []; - const pathPositions = []; - for (let level = 0; level < this.levels; level++) { - pathIndices[level] = elIndex % 2; - const leafIndex = elIndex ^ 1; - if (leafIndex < this._layers[level].length) { - pathElements[level] = this._layers[level][leafIndex]; - pathPositions[level] = leafIndex; - } - else { - pathElements[level] = this._zeros[level]; - pathPositions[level] = 0; - } - elIndex >>= 1; - } - return { - pathElements, - pathIndices, - pathPositions, - pathRoot: this.root, - }; - } - _buildZeros() { - this._zeros = [this.zeroElement]; - for (let i = 1; i <= this.levels; i++) { - this._zeros[i] = this._hashFn(this._zeros[i - 1], this._zeros[i - 1]); - } - } - _processNodes(nodes, layerIndex) { - const length = nodes.length; - let currentLength = Math.ceil(length / 2); - const currentLayer = new Array(currentLength); - currentLength--; - const starFrom = length - ((length % 2) ^ 1); - let j = 0; - for (let i = starFrom; i >= 0; i -= 2) { - if (nodes[i - 1] === undefined) - break; - const left = nodes[i - 1]; - const right = (i === starFrom && length % 2 === 1) ? this._zeros[layerIndex - 1] : nodes[i]; - currentLayer[currentLength - j] = this._hashFn(left, right); - j++; - } - return currentLayer; - } - _processUpdate(index) { - for (let level = 1; level <= this.levels; level++) { - index >>= 1; - const left = this._layers[level - 1][index * 2]; - const right = index * 2 + 1 < this._layers[level - 1].length - ? this._layers[level - 1][index * 2 + 1] - : this._zeros[level - 1]; - this._layers[level][index] = this._hashFn(left, right); - } - } -} -exports.BaseTree = BaseTree; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BaseTree = void 0; +class BaseTree { + get capacity() { + return 2 ** this.levels; + } + get layers() { + return this._layers.slice(); + } + get zeros() { + return this._zeros.slice(); + } + get elements() { + return this._layers[0].slice(); + } + get root() { + var _a; + return (_a = this._layers[this.levels][0]) !== null && _a !== void 0 ? _a : this._zeros[this.levels]; + } + /** + * Find an element in the tree + * @param elements elements of tree + * @param element An element to find + * @param comparator A function that checks leaf value equality + * @param fromIndex The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned + * @returns {number} Index if element is found, otherwise -1 + */ + static indexOf(elements, element, fromIndex, comparator) { + if (comparator) { + return elements.findIndex((el) => comparator(element, el)); + } + else { + return elements.indexOf(element, fromIndex); + } + } + /** + * Insert new element into the tree + * @param element Element to insert + */ + insert(element) { + if (this._layers[0].length >= this.capacity) { + throw new Error('Tree is full'); + } + this.update(this._layers[0].length, element); + } + /* + * Insert multiple elements into the tree. + * @param {Array} elements Elements to insert + */ + bulkInsert(elements) { + if (!elements.length) { + return; + } + if (this._layers[0].length + elements.length > this.capacity) { + throw new Error('Tree is full'); + } + // First we insert all elements except the last one + // updating only full subtree hashes (all layers where inserted element has odd index) + // the last element will update the full path to the root making the tree consistent again + for (let i = 0; i < elements.length - 1; i++) { + this._layers[0].push(elements[i]); + let level = 0; + let index = this._layers[0].length - 1; + while (index % 2 === 1) { + level++; + index >>= 1; + const left = this._layers[level - 1][index * 2]; + const right = this._layers[level - 1][index * 2 + 1]; + this._layers[level][index] = this._hashFn(left, right); + } + } + this.insert(elements[elements.length - 1]); + } + /** + * Change an element in the tree + * @param {number} index Index of element to change + * @param element Updated element value + */ + update(index, element) { + if (isNaN(Number(index)) || index < 0 || index > this._layers[0].length || index >= this.capacity) { + throw new Error('Insert index out of bounds: ' + index); + } + this._layers[0][index] = element; + this._processUpdate(index); + } + /** + * Get merkle path to a leaf + * @param {number} index Leaf index to generate path for + * @returns {{pathElements: Object[], pathIndex: number[]}} An object containing adjacent elements and left-right index + */ + path(index) { + if (isNaN(Number(index)) || index < 0 || index >= this._layers[0].length) { + throw new Error('Index out of bounds: ' + index); + } + let elIndex = +index; + const pathElements = []; + const pathIndices = []; + const pathPositions = []; + for (let level = 0; level < this.levels; level++) { + pathIndices[level] = elIndex % 2; + const leafIndex = elIndex ^ 1; + if (leafIndex < this._layers[level].length) { + pathElements[level] = this._layers[level][leafIndex]; + pathPositions[level] = leafIndex; + } + else { + pathElements[level] = this._zeros[level]; + pathPositions[level] = 0; + } + elIndex >>= 1; + } + return { + pathElements, + pathIndices, + pathPositions, + pathRoot: this.root, + }; + } + _buildZeros() { + this._zeros = [this.zeroElement]; + for (let i = 1; i <= this.levels; i++) { + this._zeros[i] = this._hashFn(this._zeros[i - 1], this._zeros[i - 1]); + } + } + _processNodes(nodes, layerIndex) { + const length = nodes.length; + let currentLength = Math.ceil(length / 2); + const currentLayer = new Array(currentLength); + currentLength--; + const starFrom = length - ((length % 2) ^ 1); + let j = 0; + for (let i = starFrom; i >= 0; i -= 2) { + if (nodes[i - 1] === undefined) + break; + const left = nodes[i - 1]; + const right = (i === starFrom && length % 2 === 1) ? this._zeros[layerIndex - 1] : nodes[i]; + currentLayer[currentLength - j] = this._hashFn(left, right); + j++; + } + return currentLayer; + } + _processUpdate(index) { + for (let level = 1; level <= this.levels; level++) { + index >>= 1; + const left = this._layers[level - 1][index * 2]; + const right = index * 2 + 1 < this._layers[level - 1].length + ? this._layers[level - 1][index * 2 + 1] + : this._zeros[level - 1]; + this._layers[level][index] = this._hashFn(left, right); + } + } +} +exports.BaseTree = BaseTree; /***/ }), @@ -177,120 +177,120 @@ exports.BaseTree = BaseTree; /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const simpleHash_1 = __importDefault(__webpack_require__(5319)); -const BaseTree_1 = __webpack_require__(7736); -class MerkleTree extends BaseTree_1.BaseTree { - constructor(levels, elements = [], { hashFunction = simpleHash_1.default, zeroElement = 0, } = {}) { - super(); - this.levels = levels; - if (elements.length > this.capacity) { - throw new Error('Tree is full'); - } - this._hashFn = hashFunction; - this.zeroElement = zeroElement; - this._layers = []; - const leaves = elements.slice(); - this._layers = [leaves]; - this._buildZeros(); - this._buildHashes(); - } - _buildHashes() { - for (let layerIndex = 1; layerIndex <= this.levels; layerIndex++) { - const nodes = this._layers[layerIndex - 1]; - this._layers[layerIndex] = this._processNodes(nodes, layerIndex); - } - } - /** - * Insert multiple elements into the tree. - * @param {Array} elements Elements to insert - */ - bulkInsert(elements) { - if (!elements.length) { - return; - } - if (this._layers[0].length + elements.length > this.capacity) { - throw new Error('Tree is full'); - } - // First we insert all elements except the last one - // updating only full subtree hashes (all layers where inserted element has odd index) - // the last element will update the full path to the root making the tree consistent again - for (let i = 0; i < elements.length - 1; i++) { - this._layers[0].push(elements[i]); - let level = 0; - let index = this._layers[0].length - 1; - while (index % 2 === 1) { - level++; - index >>= 1; - this._layers[level][index] = this._hashFn(this._layers[level - 1][index * 2], this._layers[level - 1][index * 2 + 1]); - } - } - this.insert(elements[elements.length - 1]); - } - indexOf(element, comparator) { - return BaseTree_1.BaseTree.indexOf(this._layers[0], element, 0, comparator); - } - proof(element) { - const index = this.indexOf(element); - return this.path(index); - } - getTreeEdge(edgeIndex) { - const edgeElement = this._layers[0][edgeIndex]; - if (edgeElement === undefined) { - throw new Error('Element not found'); - } - const edgePath = this.path(edgeIndex); - return { edgePath, edgeElement, edgeIndex, edgeElementsCount: this._layers[0].length }; - } - /** - * 🪓 - * @param count - */ - getTreeSlices(count = 4) { - const length = this._layers[0].length; - let size = Math.ceil(length / count); - if (size % 2) - size++; - const slices = []; - for (let i = 0; i < length; i += size) { - const edgeLeft = i; - const edgeRight = i + size; - slices.push({ edge: this.getTreeEdge(edgeLeft), elements: this.elements.slice(edgeLeft, edgeRight) }); - } - return slices; - } - /** - * Serialize entire tree state including intermediate layers into a plain object - * Deserializing it back will not require to recompute any hashes - * Elements are not converted to a plain type, this is responsibility of the caller - */ - serialize() { - return { - levels: this.levels, - _zeros: this._zeros, - _layers: this._layers, - }; - } - /** - * Deserialize data into a MerkleTree instance - * Make sure to provide the same hashFunction as was used in the source tree, - * otherwise the tree state will be invalid - */ - static deserialize(data, hashFunction) { - const instance = Object.assign(Object.create(this.prototype), data); - instance._hashFn = hashFunction || simpleHash_1.default; - instance.zeroElement = instance._zeros[0]; - return instance; - } - toString() { - return JSON.stringify(this.serialize()); - } -} -exports["default"] = MerkleTree; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const simpleHash_1 = __importDefault(__webpack_require__(5319)); +const BaseTree_1 = __webpack_require__(7736); +class MerkleTree extends BaseTree_1.BaseTree { + constructor(levels, elements = [], { hashFunction = simpleHash_1.default, zeroElement = 0, } = {}) { + super(); + this.levels = levels; + if (elements.length > this.capacity) { + throw new Error('Tree is full'); + } + this._hashFn = hashFunction; + this.zeroElement = zeroElement; + this._layers = []; + const leaves = elements.slice(); + this._layers = [leaves]; + this._buildZeros(); + this._buildHashes(); + } + _buildHashes() { + for (let layerIndex = 1; layerIndex <= this.levels; layerIndex++) { + const nodes = this._layers[layerIndex - 1]; + this._layers[layerIndex] = this._processNodes(nodes, layerIndex); + } + } + /** + * Insert multiple elements into the tree. + * @param {Array} elements Elements to insert + */ + bulkInsert(elements) { + if (!elements.length) { + return; + } + if (this._layers[0].length + elements.length > this.capacity) { + throw new Error('Tree is full'); + } + // First we insert all elements except the last one + // updating only full subtree hashes (all layers where inserted element has odd index) + // the last element will update the full path to the root making the tree consistent again + for (let i = 0; i < elements.length - 1; i++) { + this._layers[0].push(elements[i]); + let level = 0; + let index = this._layers[0].length - 1; + while (index % 2 === 1) { + level++; + index >>= 1; + this._layers[level][index] = this._hashFn(this._layers[level - 1][index * 2], this._layers[level - 1][index * 2 + 1]); + } + } + this.insert(elements[elements.length - 1]); + } + indexOf(element, comparator) { + return BaseTree_1.BaseTree.indexOf(this._layers[0], element, 0, comparator); + } + proof(element) { + const index = this.indexOf(element); + return this.path(index); + } + getTreeEdge(edgeIndex) { + const edgeElement = this._layers[0][edgeIndex]; + if (edgeElement === undefined) { + throw new Error('Element not found'); + } + const edgePath = this.path(edgeIndex); + return { edgePath, edgeElement, edgeIndex, edgeElementsCount: this._layers[0].length }; + } + /** + * 🪓 + * @param count + */ + getTreeSlices(count = 4) { + const length = this._layers[0].length; + let size = Math.ceil(length / count); + if (size % 2) + size++; + const slices = []; + for (let i = 0; i < length; i += size) { + const edgeLeft = i; + const edgeRight = i + size; + slices.push({ edge: this.getTreeEdge(edgeLeft), elements: this.elements.slice(edgeLeft, edgeRight) }); + } + return slices; + } + /** + * Serialize entire tree state including intermediate layers into a plain object + * Deserializing it back will not require to recompute any hashes + * Elements are not converted to a plain type, this is responsibility of the caller + */ + serialize() { + return { + levels: this.levels, + _zeros: this._zeros, + _layers: this._layers, + }; + } + /** + * Deserialize data into a MerkleTree instance + * Make sure to provide the same hashFunction as was used in the source tree, + * otherwise the tree state will be invalid + */ + static deserialize(data, hashFunction) { + const instance = Object.assign(Object.create(this.prototype), data); + instance._hashFn = hashFunction || simpleHash_1.default; + instance.zeroElement = instance._zeros[0]; + return instance; + } + toString() { + return JSON.stringify(this.serialize()); + } +} +exports["default"] = MerkleTree; /***/ }), @@ -299,165 +299,165 @@ exports["default"] = MerkleTree; /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PartialMerkleTree = void 0; -const simpleHash_1 = __importDefault(__webpack_require__(5319)); -const BaseTree_1 = __webpack_require__(7736); -class PartialMerkleTree extends BaseTree_1.BaseTree { - constructor(levels, { edgePath, edgeElement, edgeIndex, edgeElementsCount, }, leaves, { hashFunction, zeroElement } = {}) { - super(); - if (edgeIndex + leaves.length !== edgeElementsCount) - throw new Error('Invalid number of elements'); - this._edgeLeafProof = edgePath; - this._initialRoot = edgePath.pathRoot; - this.zeroElement = zeroElement !== null && zeroElement !== void 0 ? zeroElement : 0; - this._edgeLeaf = { data: edgeElement, index: edgeIndex }; - this._leavesAfterEdge = leaves; - this.levels = levels; - this._hashFn = hashFunction || simpleHash_1.default; - this._createProofMap(); - this._buildTree(); - } - get edgeIndex() { - return this._edgeLeaf.index; - } - get edgeElement() { - return this._edgeLeaf.data; - } - get edgeLeafProof() { - return this._edgeLeafProof; - } - _createProofMap() { - this._proofMap = this.edgeLeafProof.pathPositions.reduce((p, c, i) => { - p.set(i, [c, this.edgeLeafProof.pathElements[i]]); - return p; - }, new Map()); - this._proofMap.set(this.levels, [0, this.edgeLeafProof.pathRoot]); - } - _buildTree() { - const edgeLeafIndex = this._edgeLeaf.index; - this._leaves = Array(edgeLeafIndex).concat(this._leavesAfterEdge); - if (this._proofMap.has(0)) { - const [proofPos, proofEl] = this._proofMap.get(0); - this._leaves[proofPos] = proofEl; - } - this._layers = [this._leaves]; - this._buildZeros(); - this._buildHashes(); - } - _buildHashes() { - for (let layerIndex = 1; layerIndex <= this.levels; layerIndex++) { - const nodes = this._layers[layerIndex - 1]; - const currentLayer = this._processNodes(nodes, layerIndex); - if (this._proofMap.has(layerIndex)) { - const [proofPos, proofEl] = this._proofMap.get(layerIndex); - if (!currentLayer[proofPos]) - currentLayer[proofPos] = proofEl; - } - this._layers[layerIndex] = currentLayer; - } - } - /** - * Change an element in the tree - * @param {number} index Index of element to change - * @param element Updated element value - */ - update(index, element) { - if (isNaN(Number(index)) || index < 0 || index > this._layers[0].length || index >= this.capacity) { - throw new Error('Insert index out of bounds: ' + index); - } - if (index < this._edgeLeaf.index) { - throw new Error(`Index ${index} is below the edge: ${this._edgeLeaf.index}`); - } - this._layers[0][index] = element; - this._processUpdate(index); - } - path(index) { - var _a; - if (isNaN(Number(index)) || index < 0 || index >= this._layers[0].length) { - throw new Error('Index out of bounds: ' + index); - } - if (index < this._edgeLeaf.index) { - throw new Error(`Index ${index} is below the edge: ${this._edgeLeaf.index}`); - } - let elIndex = Number(index); - const pathElements = []; - const pathIndices = []; - const pathPositions = []; - for (let level = 0; level < this.levels; level++) { - pathIndices[level] = elIndex % 2; - const leafIndex = elIndex ^ 1; - if (leafIndex < this._layers[level].length) { - pathElements[level] = this._layers[level][leafIndex]; - pathPositions[level] = leafIndex; - } - else { - pathElements[level] = this._zeros[level]; - pathPositions[level] = 0; - } - const [proofPos, proofEl] = this._proofMap.get(level); - pathElements[level] = (_a = pathElements[level]) !== null && _a !== void 0 ? _a : (proofPos === leafIndex ? proofEl : this._zeros[level]); - elIndex >>= 1; - } - return { - pathElements, - pathIndices, - pathPositions, - pathRoot: this.root, - }; - } - indexOf(element, comparator) { - return BaseTree_1.BaseTree.indexOf(this._layers[0], element, this.edgeIndex, comparator); - } - proof(element) { - const index = this.indexOf(element); - return this.path(index); - } - /** - * Shifts edge of tree to left - * @param edge new TreeEdge below current edge - * @param elements leaves between old and new edge - */ - shiftEdge(edge, elements) { - if (this._edgeLeaf.index <= edge.edgeIndex) { - throw new Error(`New edgeIndex should be smaller then ${this._edgeLeaf.index}`); - } - if (elements.length !== (this._edgeLeaf.index - edge.edgeIndex)) { - throw new Error(`Elements length should be ${this._edgeLeaf.index - edge.edgeIndex}`); - } - this._edgeLeafProof = edge.edgePath; - this._edgeLeaf = { index: edge.edgeIndex, data: edge.edgeElement }; - this._leavesAfterEdge = [...elements, ...this._leavesAfterEdge]; - this._createProofMap(); - this._buildTree(); - } - serialize() { - return { - _edgeLeafProof: this._edgeLeafProof, - _edgeLeaf: this._edgeLeaf, - _layers: this._layers, - _zeros: this._zeros, - levels: this.levels, - }; - } - static deserialize(data, hashFunction) { - const instance = Object.assign(Object.create(this.prototype), data); - instance._hashFn = hashFunction || simpleHash_1.default; - instance._initialRoot = data._edgeLeafProof.pathRoot; - instance.zeroElement = instance._zeros[0]; - instance._leavesAfterEdge = instance._layers[0].slice(data._edgeLeaf.index); - instance._createProofMap(); - return instance; - } - toString() { - return JSON.stringify(this.serialize()); - } -} -exports.PartialMerkleTree = PartialMerkleTree; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PartialMerkleTree = void 0; +const simpleHash_1 = __importDefault(__webpack_require__(5319)); +const BaseTree_1 = __webpack_require__(7736); +class PartialMerkleTree extends BaseTree_1.BaseTree { + constructor(levels, { edgePath, edgeElement, edgeIndex, edgeElementsCount, }, leaves, { hashFunction, zeroElement } = {}) { + super(); + if (edgeIndex + leaves.length !== edgeElementsCount) + throw new Error('Invalid number of elements'); + this._edgeLeafProof = edgePath; + this._initialRoot = edgePath.pathRoot; + this.zeroElement = zeroElement !== null && zeroElement !== void 0 ? zeroElement : 0; + this._edgeLeaf = { data: edgeElement, index: edgeIndex }; + this._leavesAfterEdge = leaves; + this.levels = levels; + this._hashFn = hashFunction || simpleHash_1.default; + this._createProofMap(); + this._buildTree(); + } + get edgeIndex() { + return this._edgeLeaf.index; + } + get edgeElement() { + return this._edgeLeaf.data; + } + get edgeLeafProof() { + return this._edgeLeafProof; + } + _createProofMap() { + this._proofMap = this.edgeLeafProof.pathPositions.reduce((p, c, i) => { + p.set(i, [c, this.edgeLeafProof.pathElements[i]]); + return p; + }, new Map()); + this._proofMap.set(this.levels, [0, this.edgeLeafProof.pathRoot]); + } + _buildTree() { + const edgeLeafIndex = this._edgeLeaf.index; + this._leaves = Array(edgeLeafIndex).concat(this._leavesAfterEdge); + if (this._proofMap.has(0)) { + const [proofPos, proofEl] = this._proofMap.get(0); + this._leaves[proofPos] = proofEl; + } + this._layers = [this._leaves]; + this._buildZeros(); + this._buildHashes(); + } + _buildHashes() { + for (let layerIndex = 1; layerIndex <= this.levels; layerIndex++) { + const nodes = this._layers[layerIndex - 1]; + const currentLayer = this._processNodes(nodes, layerIndex); + if (this._proofMap.has(layerIndex)) { + const [proofPos, proofEl] = this._proofMap.get(layerIndex); + if (!currentLayer[proofPos]) + currentLayer[proofPos] = proofEl; + } + this._layers[layerIndex] = currentLayer; + } + } + /** + * Change an element in the tree + * @param {number} index Index of element to change + * @param element Updated element value + */ + update(index, element) { + if (isNaN(Number(index)) || index < 0 || index > this._layers[0].length || index >= this.capacity) { + throw new Error('Insert index out of bounds: ' + index); + } + if (index < this._edgeLeaf.index) { + throw new Error(`Index ${index} is below the edge: ${this._edgeLeaf.index}`); + } + this._layers[0][index] = element; + this._processUpdate(index); + } + path(index) { + var _a; + if (isNaN(Number(index)) || index < 0 || index >= this._layers[0].length) { + throw new Error('Index out of bounds: ' + index); + } + if (index < this._edgeLeaf.index) { + throw new Error(`Index ${index} is below the edge: ${this._edgeLeaf.index}`); + } + let elIndex = Number(index); + const pathElements = []; + const pathIndices = []; + const pathPositions = []; + for (let level = 0; level < this.levels; level++) { + pathIndices[level] = elIndex % 2; + const leafIndex = elIndex ^ 1; + if (leafIndex < this._layers[level].length) { + pathElements[level] = this._layers[level][leafIndex]; + pathPositions[level] = leafIndex; + } + else { + pathElements[level] = this._zeros[level]; + pathPositions[level] = 0; + } + const [proofPos, proofEl] = this._proofMap.get(level); + pathElements[level] = (_a = pathElements[level]) !== null && _a !== void 0 ? _a : (proofPos === leafIndex ? proofEl : this._zeros[level]); + elIndex >>= 1; + } + return { + pathElements, + pathIndices, + pathPositions, + pathRoot: this.root, + }; + } + indexOf(element, comparator) { + return BaseTree_1.BaseTree.indexOf(this._layers[0], element, this.edgeIndex, comparator); + } + proof(element) { + const index = this.indexOf(element); + return this.path(index); + } + /** + * Shifts edge of tree to left + * @param edge new TreeEdge below current edge + * @param elements leaves between old and new edge + */ + shiftEdge(edge, elements) { + if (this._edgeLeaf.index <= edge.edgeIndex) { + throw new Error(`New edgeIndex should be smaller then ${this._edgeLeaf.index}`); + } + if (elements.length !== (this._edgeLeaf.index - edge.edgeIndex)) { + throw new Error(`Elements length should be ${this._edgeLeaf.index - edge.edgeIndex}`); + } + this._edgeLeafProof = edge.edgePath; + this._edgeLeaf = { index: edge.edgeIndex, data: edge.edgeElement }; + this._leavesAfterEdge = [...elements, ...this._leavesAfterEdge]; + this._createProofMap(); + this._buildTree(); + } + serialize() { + return { + _edgeLeafProof: this._edgeLeafProof, + _edgeLeaf: this._edgeLeaf, + _layers: this._layers, + _zeros: this._zeros, + levels: this.levels, + }; + } + static deserialize(data, hashFunction) { + const instance = Object.assign(Object.create(this.prototype), data); + instance._hashFn = hashFunction || simpleHash_1.default; + instance._initialRoot = data._edgeLeafProof.pathRoot; + instance.zeroElement = instance._zeros[0]; + instance._leavesAfterEdge = instance._layers[0].slice(data._edgeLeaf.index); + instance._createProofMap(); + return instance; + } + toString() { + return JSON.stringify(this.serialize()); + } +} +exports.PartialMerkleTree = PartialMerkleTree; /***/ }), @@ -466,19 +466,19 @@ exports.PartialMerkleTree = PartialMerkleTree; /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.MerkleTree = exports.simpleHash = exports.PartialMerkleTree = void 0; -const FixedMerkleTree_1 = __importDefault(__webpack_require__(9093)); -Object.defineProperty(exports, "MerkleTree", ({ enumerable: true, get: function () { return FixedMerkleTree_1.default; } })); -var PartialMerkleTree_1 = __webpack_require__(1230); -Object.defineProperty(exports, "PartialMerkleTree", ({ enumerable: true, get: function () { return PartialMerkleTree_1.PartialMerkleTree; } })); -var simpleHash_1 = __webpack_require__(5319); -Object.defineProperty(exports, "simpleHash", ({ enumerable: true, get: function () { return simpleHash_1.simpleHash; } })); -exports["default"] = FixedMerkleTree_1.default; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MerkleTree = exports.simpleHash = exports.PartialMerkleTree = void 0; +const FixedMerkleTree_1 = __importDefault(__webpack_require__(9093)); +Object.defineProperty(exports, "MerkleTree", ({ enumerable: true, get: function () { return FixedMerkleTree_1.default; } })); +var PartialMerkleTree_1 = __webpack_require__(1230); +Object.defineProperty(exports, "PartialMerkleTree", ({ enumerable: true, get: function () { return PartialMerkleTree_1.PartialMerkleTree; } })); +var simpleHash_1 = __webpack_require__(5319); +Object.defineProperty(exports, "simpleHash", ({ enumerable: true, get: function () { return simpleHash_1.simpleHash; } })); +exports["default"] = FixedMerkleTree_1.default; /***/ }), @@ -487,27 +487,27 @@ exports["default"] = FixedMerkleTree_1.default; /***/ ((__unused_webpack_module, exports) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.simpleHash = void 0; -/*** - * This is insecure hash function, just for example only - * @param data - * @param seed - * @param hashLength - */ -function simpleHash(data, seed, hashLength = 40) { - const str = data.join(''); - let i, l, hval = seed !== null && seed !== void 0 ? seed : 0x811c9dcc5; - for (i = 0, l = str.length; i < l; i++) { - hval ^= str.charCodeAt(i); - hval += (hval << 1) + (hval << 4) + (hval << 6) + (hval << 8) + (hval << 24); - } - const hash = (hval >>> 0).toString(16); - return BigInt('0x' + hash.padEnd(hashLength - (hash.length - 1), '0')).toString(10); -} -exports.simpleHash = simpleHash; -exports["default"] = (left, right) => simpleHash([left, right]); + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.simpleHash = void 0; +/*** + * This is insecure hash function, just for example only + * @param data + * @param seed + * @param hashLength + */ +function simpleHash(data, seed, hashLength = 40) { + const str = data.join(''); + let i, l, hval = seed !== null && seed !== void 0 ? seed : 0x811c9dcc5; + for (i = 0, l = str.length; i < l; i++) { + hval ^= str.charCodeAt(i); + hval += (hval << 1) + (hval << 4) + (hval << 6) + (hval << 8) + (hval << 24); + } + const hash = (hval >>> 0).toString(16); + return BigInt('0x' + hash.padEnd(hashLength - (hash.length - 1), '0')).toString(10); +} +exports.simpleHash = simpleHash; +exports["default"] = (left, right) => simpleHash([left, right]); /***/ }), @@ -5773,8 +5773,6 @@ PEMEncoder.prototype.encode = function encode(data, options) { /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(5606); -/* provided dependency */ var console = __webpack_require__(6763); // Currently in sync with Node.js lib/assert.js // https://github.com/nodejs/node/commit/2a51ae424a513ec9a6aa3466baa0cc1d55dd4f3b @@ -6372,7 +6370,6 @@ assert.strict.strict = assert.strict; /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(5606); // Currently in sync with Node.js lib/internal/assert/assertion_error.js // https://github.com/nodejs/node/commit/0817840f775032169ddd70c85ac059f18ffcc81c @@ -8610,1468 +8607,6 @@ function fromByteArray (uint8) { } -/***/ }), - -/***/ 2096: -/***/ ((module, exports, __webpack_require__) => { - -/* module decorator */ module = __webpack_require__.nmd(module); -var __WEBPACK_AMD_DEFINE_RESULT__;var bigInt = (function (undefined) { - "use strict"; - - var BASE = 1e7, - LOG_BASE = 7, - MAX_INT = 9007199254740992, - MAX_INT_ARR = smallToArray(MAX_INT), - DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"; - - var supportsNativeBigInt = typeof BigInt === "function"; - - function Integer(v, radix, alphabet, caseSensitive) { - if (typeof v === "undefined") return Integer[0]; - if (typeof radix !== "undefined") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive); - return parseValue(v); - } - - function BigInteger(value, sign) { - this.value = value; - this.sign = sign; - this.isSmall = false; - } - BigInteger.prototype = Object.create(Integer.prototype); - - function SmallInteger(value) { - this.value = value; - this.sign = value < 0; - this.isSmall = true; - } - SmallInteger.prototype = Object.create(Integer.prototype); - - function NativeBigInt(value) { - this.value = value; - } - NativeBigInt.prototype = Object.create(Integer.prototype); - - function isPrecise(n) { - return -MAX_INT < n && n < MAX_INT; - } - - function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes - if (n < 1e7) - return [n]; - if (n < 1e14) - return [n % 1e7, Math.floor(n / 1e7)]; - return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)]; - } - - function arrayToSmall(arr) { // If BASE changes this function may need to change - trim(arr); - var length = arr.length; - if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) { - switch (length) { - case 0: return 0; - case 1: return arr[0]; - case 2: return arr[0] + arr[1] * BASE; - default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE; - } - } - return arr; - } - - function trim(v) { - var i = v.length; - while (v[--i] === 0); - v.length = i + 1; - } - - function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger - var x = new Array(length); - var i = -1; - while (++i < length) { - x[i] = 0; - } - return x; - } - - function truncate(n) { - if (n > 0) return Math.floor(n); - return Math.ceil(n); - } - - function add(a, b) { // assumes a and b are arrays with a.length >= b.length - var l_a = a.length, - l_b = b.length, - r = new Array(l_a), - carry = 0, - base = BASE, - sum, i; - for (i = 0; i < l_b; i++) { - sum = a[i] + b[i] + carry; - carry = sum >= base ? 1 : 0; - r[i] = sum - carry * base; - } - while (i < l_a) { - sum = a[i] + carry; - carry = sum === base ? 1 : 0; - r[i++] = sum - carry * base; - } - if (carry > 0) r.push(carry); - return r; - } - - function addAny(a, b) { - if (a.length >= b.length) return add(a, b); - return add(b, a); - } - - function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT - var l = a.length, - r = new Array(l), - base = BASE, - sum, i; - for (i = 0; i < l; i++) { - sum = a[i] - base + carry; - carry = Math.floor(sum / base); - r[i] = sum - carry * base; - carry += 1; - } - while (carry > 0) { - r[i++] = carry % base; - carry = Math.floor(carry / base); - } - return r; - } - - BigInteger.prototype.add = function (v) { - var n = parseValue(v); - if (this.sign !== n.sign) { - return this.subtract(n.negate()); - } - var a = this.value, b = n.value; - if (n.isSmall) { - return new BigInteger(addSmall(a, Math.abs(b)), this.sign); - } - return new BigInteger(addAny(a, b), this.sign); - }; - BigInteger.prototype.plus = BigInteger.prototype.add; - - SmallInteger.prototype.add = function (v) { - var n = parseValue(v); - var a = this.value; - if (a < 0 !== n.sign) { - return this.subtract(n.negate()); - } - var b = n.value; - if (n.isSmall) { - if (isPrecise(a + b)) return new SmallInteger(a + b); - b = smallToArray(Math.abs(b)); - } - return new BigInteger(addSmall(b, Math.abs(a)), a < 0); - }; - SmallInteger.prototype.plus = SmallInteger.prototype.add; - - NativeBigInt.prototype.add = function (v) { - return new NativeBigInt(this.value + parseValue(v).value); - } - NativeBigInt.prototype.plus = NativeBigInt.prototype.add; - - function subtract(a, b) { // assumes a and b are arrays with a >= b - var a_l = a.length, - b_l = b.length, - r = new Array(a_l), - borrow = 0, - base = BASE, - i, difference; - for (i = 0; i < b_l; i++) { - difference = a[i] - borrow - b[i]; - if (difference < 0) { - difference += base; - borrow = 1; - } else borrow = 0; - r[i] = difference; - } - for (i = b_l; i < a_l; i++) { - difference = a[i] - borrow; - if (difference < 0) difference += base; - else { - r[i++] = difference; - break; - } - r[i] = difference; - } - for (; i < a_l; i++) { - r[i] = a[i]; - } - trim(r); - return r; - } - - function subtractAny(a, b, sign) { - var value; - if (compareAbs(a, b) >= 0) { - value = subtract(a, b); - } else { - value = subtract(b, a); - sign = !sign; - } - value = arrayToSmall(value); - if (typeof value === "number") { - if (sign) value = -value; - return new SmallInteger(value); - } - return new BigInteger(value, sign); - } - - function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT - var l = a.length, - r = new Array(l), - carry = -b, - base = BASE, - i, difference; - for (i = 0; i < l; i++) { - difference = a[i] + carry; - carry = Math.floor(difference / base); - difference %= base; - r[i] = difference < 0 ? difference + base : difference; - } - r = arrayToSmall(r); - if (typeof r === "number") { - if (sign) r = -r; - return new SmallInteger(r); - } return new BigInteger(r, sign); - } - - BigInteger.prototype.subtract = function (v) { - var n = parseValue(v); - if (this.sign !== n.sign) { - return this.add(n.negate()); - } - var a = this.value, b = n.value; - if (n.isSmall) - return subtractSmall(a, Math.abs(b), this.sign); - return subtractAny(a, b, this.sign); - }; - BigInteger.prototype.minus = BigInteger.prototype.subtract; - - SmallInteger.prototype.subtract = function (v) { - var n = parseValue(v); - var a = this.value; - if (a < 0 !== n.sign) { - return this.add(n.negate()); - } - var b = n.value; - if (n.isSmall) { - return new SmallInteger(a - b); - } - return subtractSmall(b, Math.abs(a), a >= 0); - }; - SmallInteger.prototype.minus = SmallInteger.prototype.subtract; - - NativeBigInt.prototype.subtract = function (v) { - return new NativeBigInt(this.value - parseValue(v).value); - } - NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract; - - BigInteger.prototype.negate = function () { - return new BigInteger(this.value, !this.sign); - }; - SmallInteger.prototype.negate = function () { - var sign = this.sign; - var small = new SmallInteger(-this.value); - small.sign = !sign; - return small; - }; - NativeBigInt.prototype.negate = function () { - return new NativeBigInt(-this.value); - } - - BigInteger.prototype.abs = function () { - return new BigInteger(this.value, false); - }; - SmallInteger.prototype.abs = function () { - return new SmallInteger(Math.abs(this.value)); - }; - NativeBigInt.prototype.abs = function () { - return new NativeBigInt(this.value >= 0 ? this.value : -this.value); - } - - - function multiplyLong(a, b) { - var a_l = a.length, - b_l = b.length, - l = a_l + b_l, - r = createArray(l), - base = BASE, - product, carry, i, a_i, b_j; - for (i = 0; i < a_l; ++i) { - a_i = a[i]; - for (var j = 0; j < b_l; ++j) { - b_j = b[j]; - product = a_i * b_j + r[i + j]; - carry = Math.floor(product / base); - r[i + j] = product - carry * base; - r[i + j + 1] += carry; - } - } - trim(r); - return r; - } - - function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE - var l = a.length, - r = new Array(l), - base = BASE, - carry = 0, - product, i; - for (i = 0; i < l; i++) { - product = a[i] * b + carry; - carry = Math.floor(product / base); - r[i] = product - carry * base; - } - while (carry > 0) { - r[i++] = carry % base; - carry = Math.floor(carry / base); - } - return r; - } - - function shiftLeft(x, n) { - var r = []; - while (n-- > 0) r.push(0); - return r.concat(x); - } - - function multiplyKaratsuba(x, y) { - var n = Math.max(x.length, y.length); - - if (n <= 30) return multiplyLong(x, y); - n = Math.ceil(n / 2); - - var b = x.slice(n), - a = x.slice(0, n), - d = y.slice(n), - c = y.slice(0, n); - - var ac = multiplyKaratsuba(a, c), - bd = multiplyKaratsuba(b, d), - abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d)); - - var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n)); - trim(product); - return product; - } - - // The following function is derived from a surface fit of a graph plotting the performance difference - // between long multiplication and karatsuba multiplication versus the lengths of the two arrays. - function useKaratsuba(l1, l2) { - return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0; - } - - BigInteger.prototype.multiply = function (v) { - var n = parseValue(v), - a = this.value, b = n.value, - sign = this.sign !== n.sign, - abs; - if (n.isSmall) { - if (b === 0) return Integer[0]; - if (b === 1) return this; - if (b === -1) return this.negate(); - abs = Math.abs(b); - if (abs < BASE) { - return new BigInteger(multiplySmall(a, abs), sign); - } - b = smallToArray(abs); - } - if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes - return new BigInteger(multiplyKaratsuba(a, b), sign); - return new BigInteger(multiplyLong(a, b), sign); - }; - - BigInteger.prototype.times = BigInteger.prototype.multiply; - - function multiplySmallAndArray(a, b, sign) { // a >= 0 - if (a < BASE) { - return new BigInteger(multiplySmall(b, a), sign); - } - return new BigInteger(multiplyLong(b, smallToArray(a)), sign); - } - SmallInteger.prototype._multiplyBySmall = function (a) { - if (isPrecise(a.value * this.value)) { - return new SmallInteger(a.value * this.value); - } - return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign); - }; - BigInteger.prototype._multiplyBySmall = function (a) { - if (a.value === 0) return Integer[0]; - if (a.value === 1) return this; - if (a.value === -1) return this.negate(); - return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign); - }; - SmallInteger.prototype.multiply = function (v) { - return parseValue(v)._multiplyBySmall(this); - }; - SmallInteger.prototype.times = SmallInteger.prototype.multiply; - - NativeBigInt.prototype.multiply = function (v) { - return new NativeBigInt(this.value * parseValue(v).value); - } - NativeBigInt.prototype.times = NativeBigInt.prototype.multiply; - - function square(a) { - //console.assert(2 * BASE * BASE < MAX_INT); - var l = a.length, - r = createArray(l + l), - base = BASE, - product, carry, i, a_i, a_j; - for (i = 0; i < l; i++) { - a_i = a[i]; - carry = 0 - a_i * a_i; - for (var j = i; j < l; j++) { - a_j = a[j]; - product = 2 * (a_i * a_j) + r[i + j] + carry; - carry = Math.floor(product / base); - r[i + j] = product - carry * base; - } - r[i + l] = carry; - } - trim(r); - return r; - } - - BigInteger.prototype.square = function () { - return new BigInteger(square(this.value), false); - }; - - SmallInteger.prototype.square = function () { - var value = this.value * this.value; - if (isPrecise(value)) return new SmallInteger(value); - return new BigInteger(square(smallToArray(Math.abs(this.value))), false); - }; - - NativeBigInt.prototype.square = function (v) { - return new NativeBigInt(this.value * this.value); - } - - function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes. - var a_l = a.length, - b_l = b.length, - base = BASE, - result = createArray(b.length), - divisorMostSignificantDigit = b[b_l - 1], - // normalization - lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)), - remainder = multiplySmall(a, lambda), - divisor = multiplySmall(b, lambda), - quotientDigit, shift, carry, borrow, i, l, q; - if (remainder.length <= a_l) remainder.push(0); - divisor.push(0); - divisorMostSignificantDigit = divisor[b_l - 1]; - for (shift = a_l - b_l; shift >= 0; shift--) { - quotientDigit = base - 1; - if (remainder[shift + b_l] !== divisorMostSignificantDigit) { - quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit); - } - // quotientDigit <= base - 1 - carry = 0; - borrow = 0; - l = divisor.length; - for (i = 0; i < l; i++) { - carry += quotientDigit * divisor[i]; - q = Math.floor(carry / base); - borrow += remainder[shift + i] - (carry - q * base); - carry = q; - if (borrow < 0) { - remainder[shift + i] = borrow + base; - borrow = -1; - } else { - remainder[shift + i] = borrow; - borrow = 0; - } - } - while (borrow !== 0) { - quotientDigit -= 1; - carry = 0; - for (i = 0; i < l; i++) { - carry += remainder[shift + i] - base + divisor[i]; - if (carry < 0) { - remainder[shift + i] = carry + base; - carry = 0; - } else { - remainder[shift + i] = carry; - carry = 1; - } - } - borrow += carry; - } - result[shift] = quotientDigit; - } - // denormalization - remainder = divModSmall(remainder, lambda)[0]; - return [arrayToSmall(result), arrayToSmall(remainder)]; - } - - function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/ - // Performs faster than divMod1 on larger input sizes. - var a_l = a.length, - b_l = b.length, - result = [], - part = [], - base = BASE, - guess, xlen, highx, highy, check; - while (a_l) { - part.unshift(a[--a_l]); - trim(part); - if (compareAbs(part, b) < 0) { - result.push(0); - continue; - } - xlen = part.length; - highx = part[xlen - 1] * base + part[xlen - 2]; - highy = b[b_l - 1] * base + b[b_l - 2]; - if (xlen > b_l) { - highx = (highx + 1) * base; - } - guess = Math.ceil(highx / highy); - do { - check = multiplySmall(b, guess); - if (compareAbs(check, part) <= 0) break; - guess--; - } while (guess); - result.push(guess); - part = subtract(part, check); - } - result.reverse(); - return [arrayToSmall(result), arrayToSmall(part)]; - } - - function divModSmall(value, lambda) { - var length = value.length, - quotient = createArray(length), - base = BASE, - i, q, remainder, divisor; - remainder = 0; - for (i = length - 1; i >= 0; --i) { - divisor = remainder * base + value[i]; - q = truncate(divisor / lambda); - remainder = divisor - q * lambda; - quotient[i] = q | 0; - } - return [quotient, remainder | 0]; - } - - function divModAny(self, v) { - var value, n = parseValue(v); - if (supportsNativeBigInt) { - return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)]; - } - var a = self.value, b = n.value; - var quotient; - if (b === 0) throw new Error("Cannot divide by zero"); - if (self.isSmall) { - if (n.isSmall) { - return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)]; - } - return [Integer[0], self]; - } - if (n.isSmall) { - if (b === 1) return [self, Integer[0]]; - if (b == -1) return [self.negate(), Integer[0]]; - var abs = Math.abs(b); - if (abs < BASE) { - value = divModSmall(a, abs); - quotient = arrayToSmall(value[0]); - var remainder = value[1]; - if (self.sign) remainder = -remainder; - if (typeof quotient === "number") { - if (self.sign !== n.sign) quotient = -quotient; - return [new SmallInteger(quotient), new SmallInteger(remainder)]; - } - return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)]; - } - b = smallToArray(abs); - } - var comparison = compareAbs(a, b); - if (comparison === -1) return [Integer[0], self]; - if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]]; - - // divMod1 is faster on smaller input sizes - if (a.length + b.length <= 200) - value = divMod1(a, b); - else value = divMod2(a, b); - - quotient = value[0]; - var qSign = self.sign !== n.sign, - mod = value[1], - mSign = self.sign; - if (typeof quotient === "number") { - if (qSign) quotient = -quotient; - quotient = new SmallInteger(quotient); - } else quotient = new BigInteger(quotient, qSign); - if (typeof mod === "number") { - if (mSign) mod = -mod; - mod = new SmallInteger(mod); - } else mod = new BigInteger(mod, mSign); - return [quotient, mod]; - } - - BigInteger.prototype.divmod = function (v) { - var result = divModAny(this, v); - return { - quotient: result[0], - remainder: result[1] - }; - }; - NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod; - - - BigInteger.prototype.divide = function (v) { - return divModAny(this, v)[0]; - }; - NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) { - return new NativeBigInt(this.value / parseValue(v).value); - }; - SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide; - - BigInteger.prototype.mod = function (v) { - return divModAny(this, v)[1]; - }; - NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) { - return new NativeBigInt(this.value % parseValue(v).value); - }; - SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod; - - BigInteger.prototype.pow = function (v) { - var n = parseValue(v), - a = this.value, - b = n.value, - value, x, y; - if (b === 0) return Integer[1]; - if (a === 0) return Integer[0]; - if (a === 1) return Integer[1]; - if (a === -1) return n.isEven() ? Integer[1] : Integer[-1]; - if (n.sign) { - return Integer[0]; - } - if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large."); - if (this.isSmall) { - if (isPrecise(value = Math.pow(a, b))) - return new SmallInteger(truncate(value)); - } - x = this; - y = Integer[1]; - while (true) { - if (b & 1 === 1) { - y = y.times(x); - --b; - } - if (b === 0) break; - b /= 2; - x = x.square(); - } - return y; - }; - SmallInteger.prototype.pow = BigInteger.prototype.pow; - - NativeBigInt.prototype.pow = function (v) { - var n = parseValue(v); - var a = this.value, b = n.value; - var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2); - if (b === _0) return Integer[1]; - if (a === _0) return Integer[0]; - if (a === _1) return Integer[1]; - if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1]; - if (n.isNegative()) return new NativeBigInt(_0); - var x = this; - var y = Integer[1]; - while (true) { - if ((b & _1) === _1) { - y = y.times(x); - --b; - } - if (b === _0) break; - b /= _2; - x = x.square(); - } - return y; - } - - BigInteger.prototype.modPow = function (exp, mod) { - exp = parseValue(exp); - mod = parseValue(mod); - if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0"); - var r = Integer[1], - base = this.mod(mod); - if (exp.isNegative()) { - exp = exp.multiply(Integer[-1]); - base = base.modInv(mod); - } - while (exp.isPositive()) { - if (base.isZero()) return Integer[0]; - if (exp.isOdd()) r = r.multiply(base).mod(mod); - exp = exp.divide(2); - base = base.square().mod(mod); - } - return r; - }; - NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow; - - function compareAbs(a, b) { - if (a.length !== b.length) { - return a.length > b.length ? 1 : -1; - } - for (var i = a.length - 1; i >= 0; i--) { - if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1; - } - return 0; - } - - BigInteger.prototype.compareAbs = function (v) { - var n = parseValue(v), - a = this.value, - b = n.value; - if (n.isSmall) return 1; - return compareAbs(a, b); - }; - SmallInteger.prototype.compareAbs = function (v) { - var n = parseValue(v), - a = Math.abs(this.value), - b = n.value; - if (n.isSmall) { - b = Math.abs(b); - return a === b ? 0 : a > b ? 1 : -1; - } - return -1; - }; - NativeBigInt.prototype.compareAbs = function (v) { - var a = this.value; - var b = parseValue(v).value; - a = a >= 0 ? a : -a; - b = b >= 0 ? b : -b; - return a === b ? 0 : a > b ? 1 : -1; - } - - BigInteger.prototype.compare = function (v) { - // See discussion about comparison with Infinity: - // https://github.com/peterolson/BigInteger.js/issues/61 - if (v === Infinity) { - return -1; - } - if (v === -Infinity) { - return 1; - } - - var n = parseValue(v), - a = this.value, - b = n.value; - if (this.sign !== n.sign) { - return n.sign ? 1 : -1; - } - if (n.isSmall) { - return this.sign ? -1 : 1; - } - return compareAbs(a, b) * (this.sign ? -1 : 1); - }; - BigInteger.prototype.compareTo = BigInteger.prototype.compare; - - SmallInteger.prototype.compare = function (v) { - if (v === Infinity) { - return -1; - } - if (v === -Infinity) { - return 1; - } - - var n = parseValue(v), - a = this.value, - b = n.value; - if (n.isSmall) { - return a == b ? 0 : a > b ? 1 : -1; - } - if (a < 0 !== n.sign) { - return a < 0 ? -1 : 1; - } - return a < 0 ? 1 : -1; - }; - SmallInteger.prototype.compareTo = SmallInteger.prototype.compare; - - NativeBigInt.prototype.compare = function (v) { - if (v === Infinity) { - return -1; - } - if (v === -Infinity) { - return 1; - } - var a = this.value; - var b = parseValue(v).value; - return a === b ? 0 : a > b ? 1 : -1; - } - NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare; - - BigInteger.prototype.equals = function (v) { - return this.compare(v) === 0; - }; - NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals; - - BigInteger.prototype.notEquals = function (v) { - return this.compare(v) !== 0; - }; - NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals; - - BigInteger.prototype.greater = function (v) { - return this.compare(v) > 0; - }; - NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater; - - BigInteger.prototype.lesser = function (v) { - return this.compare(v) < 0; - }; - NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser; - - BigInteger.prototype.greaterOrEquals = function (v) { - return this.compare(v) >= 0; - }; - NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals; - - BigInteger.prototype.lesserOrEquals = function (v) { - return this.compare(v) <= 0; - }; - NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals; - - BigInteger.prototype.isEven = function () { - return (this.value[0] & 1) === 0; - }; - SmallInteger.prototype.isEven = function () { - return (this.value & 1) === 0; - }; - NativeBigInt.prototype.isEven = function () { - return (this.value & BigInt(1)) === BigInt(0); - } - - BigInteger.prototype.isOdd = function () { - return (this.value[0] & 1) === 1; - }; - SmallInteger.prototype.isOdd = function () { - return (this.value & 1) === 1; - }; - NativeBigInt.prototype.isOdd = function () { - return (this.value & BigInt(1)) === BigInt(1); - } - - BigInteger.prototype.isPositive = function () { - return !this.sign; - }; - SmallInteger.prototype.isPositive = function () { - return this.value > 0; - }; - NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive; - - BigInteger.prototype.isNegative = function () { - return this.sign; - }; - SmallInteger.prototype.isNegative = function () { - return this.value < 0; - }; - NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative; - - BigInteger.prototype.isUnit = function () { - return false; - }; - SmallInteger.prototype.isUnit = function () { - return Math.abs(this.value) === 1; - }; - NativeBigInt.prototype.isUnit = function () { - return this.abs().value === BigInt(1); - } - - BigInteger.prototype.isZero = function () { - return false; - }; - SmallInteger.prototype.isZero = function () { - return this.value === 0; - }; - NativeBigInt.prototype.isZero = function () { - return this.value === BigInt(0); - } - - BigInteger.prototype.isDivisibleBy = function (v) { - var n = parseValue(v); - if (n.isZero()) return false; - if (n.isUnit()) return true; - if (n.compareAbs(2) === 0) return this.isEven(); - return this.mod(n).isZero(); - }; - NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy; - - function isBasicPrime(v) { - var n = v.abs(); - if (n.isUnit()) return false; - if (n.equals(2) || n.equals(3) || n.equals(5)) return true; - if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false; - if (n.lesser(49)) return true; - // we don't know if it's prime: let the other functions figure it out - } - - function millerRabinTest(n, a) { - var nPrev = n.prev(), - b = nPrev, - r = 0, - d, t, i, x; - while (b.isEven()) b = b.divide(2), r++; - next: for (i = 0; i < a.length; i++) { - if (n.lesser(a[i])) continue; - x = bigInt(a[i]).modPow(b, n); - if (x.isUnit() || x.equals(nPrev)) continue; - for (d = r - 1; d != 0; d--) { - x = x.square().mod(n); - if (x.isUnit()) return false; - if (x.equals(nPrev)) continue next; - } - return false; - } - return true; - } - - // Set "strict" to true to force GRH-supported lower bound of 2*log(N)^2 - BigInteger.prototype.isPrime = function (strict) { - var isPrime = isBasicPrime(this); - if (isPrime !== undefined) return isPrime; - var n = this.abs(); - var bits = n.bitLength(); - if (bits <= 64) - return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]); - var logN = Math.log(2) * bits.toJSNumber(); - var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN); - for (var a = [], i = 0; i < t; i++) { - a.push(bigInt(i + 2)); - } - return millerRabinTest(n, a); - }; - NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime; - - BigInteger.prototype.isProbablePrime = function (iterations, rng) { - var isPrime = isBasicPrime(this); - if (isPrime !== undefined) return isPrime; - var n = this.abs(); - var t = iterations === undefined ? 5 : iterations; - for (var a = [], i = 0; i < t; i++) { - a.push(bigInt.randBetween(2, n.minus(2), rng)); - } - return millerRabinTest(n, a); - }; - NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime; - - BigInteger.prototype.modInv = function (n) { - var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR; - while (!newR.isZero()) { - q = r.divide(newR); - lastT = t; - lastR = r; - t = newT; - r = newR; - newT = lastT.subtract(q.multiply(newT)); - newR = lastR.subtract(q.multiply(newR)); - } - if (!r.isUnit()) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime"); - if (t.compare(0) === -1) { - t = t.add(n); - } - if (this.isNegative()) { - return t.negate(); - } - return t; - }; - - NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv; - - BigInteger.prototype.next = function () { - var value = this.value; - if (this.sign) { - return subtractSmall(value, 1, this.sign); - } - return new BigInteger(addSmall(value, 1), this.sign); - }; - SmallInteger.prototype.next = function () { - var value = this.value; - if (value + 1 < MAX_INT) return new SmallInteger(value + 1); - return new BigInteger(MAX_INT_ARR, false); - }; - NativeBigInt.prototype.next = function () { - return new NativeBigInt(this.value + BigInt(1)); - } - - BigInteger.prototype.prev = function () { - var value = this.value; - if (this.sign) { - return new BigInteger(addSmall(value, 1), true); - } - return subtractSmall(value, 1, this.sign); - }; - SmallInteger.prototype.prev = function () { - var value = this.value; - if (value - 1 > -MAX_INT) return new SmallInteger(value - 1); - return new BigInteger(MAX_INT_ARR, true); - }; - NativeBigInt.prototype.prev = function () { - return new NativeBigInt(this.value - BigInt(1)); - } - - var powersOfTwo = [1]; - while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]); - var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1]; - - function shift_isSmall(n) { - return Math.abs(n) <= BASE; - } - - BigInteger.prototype.shiftLeft = function (v) { - var n = parseValue(v).toJSNumber(); - if (!shift_isSmall(n)) { - throw new Error(String(n) + " is too large for shifting."); - } - if (n < 0) return this.shiftRight(-n); - var result = this; - if (result.isZero()) return result; - while (n >= powers2Length) { - result = result.multiply(highestPower2); - n -= powers2Length - 1; - } - return result.multiply(powersOfTwo[n]); - }; - NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft; - - BigInteger.prototype.shiftRight = function (v) { - var remQuo; - var n = parseValue(v).toJSNumber(); - if (!shift_isSmall(n)) { - throw new Error(String(n) + " is too large for shifting."); - } - if (n < 0) return this.shiftLeft(-n); - var result = this; - while (n >= powers2Length) { - if (result.isZero() || (result.isNegative() && result.isUnit())) return result; - remQuo = divModAny(result, highestPower2); - result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; - n -= powers2Length - 1; - } - remQuo = divModAny(result, powersOfTwo[n]); - return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; - }; - NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight; - - function bitwise(x, y, fn) { - y = parseValue(y); - var xSign = x.isNegative(), ySign = y.isNegative(); - var xRem = xSign ? x.not() : x, - yRem = ySign ? y.not() : y; - var xDigit = 0, yDigit = 0; - var xDivMod = null, yDivMod = null; - var result = []; - while (!xRem.isZero() || !yRem.isZero()) { - xDivMod = divModAny(xRem, highestPower2); - xDigit = xDivMod[1].toJSNumber(); - if (xSign) { - xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers - } - - yDivMod = divModAny(yRem, highestPower2); - yDigit = yDivMod[1].toJSNumber(); - if (ySign) { - yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers - } - - xRem = xDivMod[0]; - yRem = yDivMod[0]; - result.push(fn(xDigit, yDigit)); - } - var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0); - for (var i = result.length - 1; i >= 0; i -= 1) { - sum = sum.multiply(highestPower2).add(bigInt(result[i])); - } - return sum; - } - - BigInteger.prototype.not = function () { - return this.negate().prev(); - }; - NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not; - - BigInteger.prototype.and = function (n) { - return bitwise(this, n, function (a, b) { return a & b; }); - }; - NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and; - - BigInteger.prototype.or = function (n) { - return bitwise(this, n, function (a, b) { return a | b; }); - }; - NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or; - - BigInteger.prototype.xor = function (n) { - return bitwise(this, n, function (a, b) { return a ^ b; }); - }; - NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor; - - var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I; - function roughLOB(n) { // get lowestOneBit (rough) - // SmallInteger: return Min(lowestOneBit(n), 1 << 30) - // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7] - var v = n.value, - x = typeof v === "number" ? v | LOBMASK_I : - typeof v === "bigint" ? v | BigInt(LOBMASK_I) : - v[0] + v[1] * BASE | LOBMASK_BI; - return x & -x; - } - - function integerLogarithm(value, base) { - if (base.compareTo(value) <= 0) { - var tmp = integerLogarithm(value, base.square(base)); - var p = tmp.p; - var e = tmp.e; - var t = p.multiply(base); - return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 }; - } - return { p: bigInt(1), e: 0 }; - } - - BigInteger.prototype.bitLength = function () { - var n = this; - if (n.compareTo(bigInt(0)) < 0) { - n = n.negate().subtract(bigInt(1)); - } - if (n.compareTo(bigInt(0)) === 0) { - return bigInt(0); - } - return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1)); - } - NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength; - - function max(a, b) { - a = parseValue(a); - b = parseValue(b); - return a.greater(b) ? a : b; - } - function min(a, b) { - a = parseValue(a); - b = parseValue(b); - return a.lesser(b) ? a : b; - } - function gcd(a, b) { - a = parseValue(a).abs(); - b = parseValue(b).abs(); - if (a.equals(b)) return a; - if (a.isZero()) return b; - if (b.isZero()) return a; - var c = Integer[1], d, t; - while (a.isEven() && b.isEven()) { - d = min(roughLOB(a), roughLOB(b)); - a = a.divide(d); - b = b.divide(d); - c = c.multiply(d); - } - while (a.isEven()) { - a = a.divide(roughLOB(a)); - } - do { - while (b.isEven()) { - b = b.divide(roughLOB(b)); - } - if (a.greater(b)) { - t = b; b = a; a = t; - } - b = b.subtract(a); - } while (!b.isZero()); - return c.isUnit() ? a : a.multiply(c); - } - function lcm(a, b) { - a = parseValue(a).abs(); - b = parseValue(b).abs(); - return a.divide(gcd(a, b)).multiply(b); - } - function randBetween(a, b, rng) { - a = parseValue(a); - b = parseValue(b); - var usedRNG = rng || Math.random; - var low = min(a, b), high = max(a, b); - var range = high.subtract(low).add(1); - if (range.isSmall) return low.add(Math.floor(usedRNG() * range)); - var digits = toBase(range, BASE).value; - var result = [], restricted = true; - for (var i = 0; i < digits.length; i++) { - var top = restricted ? digits[i] + (i + 1 < digits.length ? digits[i + 1] / BASE : 0) : BASE; - var digit = truncate(usedRNG() * top); - result.push(digit); - if (digit < digits[i]) restricted = false; - } - return low.add(Integer.fromArray(result, BASE, false)); - } - - var parseBase = function (text, base, alphabet, caseSensitive) { - alphabet = alphabet || DEFAULT_ALPHABET; - text = String(text); - if (!caseSensitive) { - text = text.toLowerCase(); - alphabet = alphabet.toLowerCase(); - } - var length = text.length; - var i; - var absBase = Math.abs(base); - var alphabetValues = {}; - for (i = 0; i < alphabet.length; i++) { - alphabetValues[alphabet[i]] = i; - } - for (i = 0; i < length; i++) { - var c = text[i]; - if (c === "-") continue; - if (c in alphabetValues) { - if (alphabetValues[c] >= absBase) { - if (c === "1" && absBase === 1) continue; - throw new Error(c + " is not a valid digit in base " + base + "."); - } - } - } - base = parseValue(base); - var digits = []; - var isNegative = text[0] === "-"; - for (i = isNegative ? 1 : 0; i < text.length; i++) { - var c = text[i]; - if (c in alphabetValues) digits.push(parseValue(alphabetValues[c])); - else if (c === "<") { - var start = i; - do { i++; } while (text[i] !== ">" && i < text.length); - digits.push(parseValue(text.slice(start + 1, i))); - } - else throw new Error(c + " is not a valid character"); - } - return parseBaseFromArray(digits, base, isNegative); - }; - - function parseBaseFromArray(digits, base, isNegative) { - var val = Integer[0], pow = Integer[1], i; - for (i = digits.length - 1; i >= 0; i--) { - val = val.add(digits[i].times(pow)); - pow = pow.times(base); - } - return isNegative ? val.negate() : val; - } - - function stringify(digit, alphabet) { - alphabet = alphabet || DEFAULT_ALPHABET; - if (digit < alphabet.length) { - return alphabet[digit]; - } - return "<" + digit + ">"; - } - - function toBase(n, base) { - base = bigInt(base); - if (base.isZero()) { - if (n.isZero()) return { value: [0], isNegative: false }; - throw new Error("Cannot convert nonzero numbers to base 0."); - } - if (base.equals(-1)) { - if (n.isZero()) return { value: [0], isNegative: false }; - if (n.isNegative()) - return { - value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber())) - .map(Array.prototype.valueOf, [1, 0]) - ), - isNegative: false - }; - - var arr = Array.apply(null, Array(n.toJSNumber() - 1)) - .map(Array.prototype.valueOf, [0, 1]); - arr.unshift([1]); - return { - value: [].concat.apply([], arr), - isNegative: false - }; - } - - var neg = false; - if (n.isNegative() && base.isPositive()) { - neg = true; - n = n.abs(); - } - if (base.isUnit()) { - if (n.isZero()) return { value: [0], isNegative: false }; - - return { - value: Array.apply(null, Array(n.toJSNumber())) - .map(Number.prototype.valueOf, 1), - isNegative: neg - }; - } - var out = []; - var left = n, divmod; - while (left.isNegative() || left.compareAbs(base) >= 0) { - divmod = left.divmod(base); - left = divmod.quotient; - var digit = divmod.remainder; - if (digit.isNegative()) { - digit = base.minus(digit).abs(); - left = left.next(); - } - out.push(digit.toJSNumber()); - } - out.push(left.toJSNumber()); - return { value: out.reverse(), isNegative: neg }; - } - - function toBaseString(n, base, alphabet) { - var arr = toBase(n, base); - return (arr.isNegative ? "-" : "") + arr.value.map(function (x) { - return stringify(x, alphabet); - }).join(''); - } - - BigInteger.prototype.toArray = function (radix) { - return toBase(this, radix); - }; - - SmallInteger.prototype.toArray = function (radix) { - return toBase(this, radix); - }; - - NativeBigInt.prototype.toArray = function (radix) { - return toBase(this, radix); - }; - - BigInteger.prototype.toString = function (radix, alphabet) { - if (radix === undefined) radix = 10; - if (radix !== 10 || alphabet) return toBaseString(this, radix, alphabet); - var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit; - while (--l >= 0) { - digit = String(v[l]); - str += zeros.slice(digit.length) + digit; - } - var sign = this.sign ? "-" : ""; - return sign + str; - }; - - SmallInteger.prototype.toString = function (radix, alphabet) { - if (radix === undefined) radix = 10; - if (radix != 10 || alphabet) return toBaseString(this, radix, alphabet); - return String(this.value); - }; - - NativeBigInt.prototype.toString = SmallInteger.prototype.toString; - - NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); } - - BigInteger.prototype.valueOf = function () { - return parseInt(this.toString(), 10); - }; - BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf; - - SmallInteger.prototype.valueOf = function () { - return this.value; - }; - SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf; - NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () { - return parseInt(this.toString(), 10); - } - - function parseStringValue(v) { - if (isPrecise(+v)) { - var x = +v; - if (x === truncate(x)) - return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x); - throw new Error("Invalid integer: " + v); - } - var sign = v[0] === "-"; - if (sign) v = v.slice(1); - var split = v.split(/e/i); - if (split.length > 2) throw new Error("Invalid integer: " + split.join("e")); - if (split.length === 2) { - var exp = split[1]; - if (exp[0] === "+") exp = exp.slice(1); - exp = +exp; - if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent."); - var text = split[0]; - var decimalPlace = text.indexOf("."); - if (decimalPlace >= 0) { - exp -= text.length - decimalPlace - 1; - text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1); - } - if (exp < 0) throw new Error("Cannot include negative exponent part for integers"); - text += (new Array(exp + 1)).join("0"); - v = text; - } - var isValid = /^([0-9][0-9]*)$/.test(v); - if (!isValid) throw new Error("Invalid integer: " + v); - if (supportsNativeBigInt) { - return new NativeBigInt(BigInt(sign ? "-" + v : v)); - } - var r = [], max = v.length, l = LOG_BASE, min = max - l; - while (max > 0) { - r.push(+v.slice(min, max)); - min -= l; - if (min < 0) min = 0; - max -= l; - } - trim(r); - return new BigInteger(r, sign); - } - - function parseNumberValue(v) { - if (supportsNativeBigInt) { - return new NativeBigInt(BigInt(v)); - } - if (isPrecise(v)) { - if (v !== truncate(v)) throw new Error(v + " is not an integer."); - return new SmallInteger(v); - } - return parseStringValue(v.toString()); - } - - function parseValue(v) { - if (typeof v === "number") { - return parseNumberValue(v); - } - if (typeof v === "string") { - return parseStringValue(v); - } - if (typeof v === "bigint") { - return new NativeBigInt(v); - } - return v; - } - // Pre-define numbers in range [-999,999] - for (var i = 0; i < 1000; i++) { - Integer[i] = parseValue(i); - if (i > 0) Integer[-i] = parseValue(-i); - } - // Backwards compatibility - Integer.one = Integer[1]; - Integer.zero = Integer[0]; - Integer.minusOne = Integer[-1]; - Integer.max = max; - Integer.min = min; - Integer.gcd = gcd; - Integer.lcm = lcm; - Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; }; - Integer.randBetween = randBetween; - - Integer.fromArray = function (digits, base, isNegative) { - return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative); - }; - - return Integer; -})(); - -// Node.js check -if ( true && module.hasOwnProperty("exports")) { - module.exports = bigInt; -} - -//amd check -if (true) { - !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { - return bigInt; - }).call(exports, __webpack_require__, exports, module), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); -} - - /***/ }), /***/ 654: @@ -16588,7 +15123,6 @@ PassThrough.prototype._transform = function (chunk, encoding, cb) { /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(5606); // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -17836,7 +16370,6 @@ function done(stream, er, data) { /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(5606); // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -19186,7 +17719,6 @@ module.exports = function xor (a, b) { /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var console = __webpack_require__(6763); /*! * The buffer module from node.js, for the browser. * @@ -21467,100 +19999,6 @@ CipherBase.prototype._toString = function (value, enc, fin) { module.exports = CipherBase -/***/ }), - -/***/ 6763: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/*global window, global*/ -var util = __webpack_require__(537) -var assert = __webpack_require__(4148) -function now() { return new Date().getTime() } - -var slice = Array.prototype.slice -var console -var times = {} - -if (typeof __webpack_require__.g !== "undefined" && __webpack_require__.g.console) { - console = __webpack_require__.g.console -} else if (typeof window !== "undefined" && window.console) { - console = window.console -} else { - console = {} -} - -var functions = [ - [log, "log"], - [info, "info"], - [warn, "warn"], - [error, "error"], - [time, "time"], - [timeEnd, "timeEnd"], - [trace, "trace"], - [dir, "dir"], - [consoleAssert, "assert"] -] - -for (var i = 0; i < functions.length; i++) { - var tuple = functions[i] - var f = tuple[0] - var name = tuple[1] - - if (!console[name]) { - console[name] = f - } -} - -module.exports = console - -function log() {} - -function info() { - console.log.apply(console, arguments) -} - -function warn() { - console.log.apply(console, arguments) -} - -function error() { - console.warn.apply(console, arguments) -} - -function time(label) { - times[label] = now() -} - -function timeEnd(label) { - var time = times[label] - if (!time) { - throw new Error("No such label: " + label) - } - - delete times[label] - var duration = now() - time - console.log(label + ": " + duration + "ms") -} - -function trace() { - var err = new Error() - err.name = "Trace" - err.message = util.format.apply(null, arguments) - console.error(err.stack) -} - -function dir(object) { - console.log(util.inspect(object) + "\n") -} - -function consoleAssert(expression) { - if (!expression) { - var arr = slice.call(arguments, 1) - assert.ok(false, util.format.apply(null, arr)) - } -} - - /***/ }), /***/ 5622: @@ -25441,59 +23879,60 @@ module.exports = Hmac /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; +var __webpack_unused_export__; -exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = __webpack_require__(3209) -exports.createHash = exports.Hash = __webpack_require__(7108) -exports.createHmac = exports.Hmac = __webpack_require__(3507) +__webpack_unused_export__ = __webpack_unused_export__ = __webpack_unused_export__ = /* unused reexport */ __webpack_require__(3209) +__webpack_unused_export__ = /* unused reexport */ __webpack_require__(7108) +__webpack_unused_export__ = /* unused reexport */ __webpack_require__(3507) var algos = __webpack_require__(5715) var algoKeys = Object.keys(algos) var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys) -exports.getHashes = function () { +__webpack_unused_export__ = function () { return hashes } var p = __webpack_require__(8396) -exports.pbkdf2 = p.pbkdf2 -exports.pbkdf2Sync = p.pbkdf2Sync +__webpack_unused_export__ = p.pbkdf2 +__webpack_unused_export__ = p.pbkdf2Sync var aes = __webpack_require__(125) -exports.Cipher = aes.Cipher -exports.createCipher = aes.createCipher -exports.Cipheriv = aes.Cipheriv -exports.createCipheriv = aes.createCipheriv -exports.Decipher = aes.Decipher -exports.createDecipher = aes.createDecipher -exports.Decipheriv = aes.Decipheriv -exports.createDecipheriv = aes.createDecipheriv -exports.getCiphers = aes.getCiphers -exports.listCiphers = aes.listCiphers +__webpack_unused_export__ = aes.Cipher +__webpack_unused_export__ = aes.createCipher +__webpack_unused_export__ = aes.Cipheriv +__webpack_unused_export__ = aes.createCipheriv +__webpack_unused_export__ = aes.Decipher +__webpack_unused_export__ = aes.createDecipher +__webpack_unused_export__ = aes.Decipheriv +__webpack_unused_export__ = aes.createDecipheriv +__webpack_unused_export__ = aes.getCiphers +__webpack_unused_export__ = aes.listCiphers var dh = __webpack_require__(5380) -exports.DiffieHellmanGroup = dh.DiffieHellmanGroup -exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup -exports.getDiffieHellman = dh.getDiffieHellman -exports.createDiffieHellman = dh.createDiffieHellman -exports.DiffieHellman = dh.DiffieHellman +__webpack_unused_export__ = dh.DiffieHellmanGroup +__webpack_unused_export__ = dh.createDiffieHellmanGroup +__webpack_unused_export__ = dh.getDiffieHellman +__webpack_unused_export__ = dh.createDiffieHellman +__webpack_unused_export__ = dh.DiffieHellman var sign = __webpack_require__(20) -exports.createSign = sign.createSign -exports.Sign = sign.Sign -exports.createVerify = sign.createVerify -exports.Verify = sign.Verify +__webpack_unused_export__ = sign.createSign +__webpack_unused_export__ = sign.Sign +__webpack_unused_export__ = sign.createVerify +__webpack_unused_export__ = sign.Verify -exports.createECDH = __webpack_require__(1324) +/* unused reexport */ __webpack_require__(1324) var publicEncrypt = __webpack_require__(7168) -exports.publicEncrypt = publicEncrypt.publicEncrypt -exports.privateEncrypt = publicEncrypt.privateEncrypt -exports.publicDecrypt = publicEncrypt.publicDecrypt -exports.privateDecrypt = publicEncrypt.privateDecrypt +__webpack_unused_export__ = publicEncrypt.publicEncrypt +__webpack_unused_export__ = publicEncrypt.privateEncrypt +__webpack_unused_export__ = publicEncrypt.publicDecrypt +__webpack_unused_export__ = publicEncrypt.privateDecrypt // the least I can do is make error messages for the rest of the node.js/crypto api. // ;[ @@ -25510,10 +23949,10 @@ exports.privateDecrypt = publicEncrypt.privateDecrypt var rf = __webpack_require__(6983) -exports.randomFill = rf.randomFill -exports.randomFillSync = rf.randomFillSync +__webpack_unused_export__ = rf.randomFill +__webpack_unused_export__ = rf.randomFillSync -exports.createCredentials = function () { +__webpack_unused_export__ = function () { throw new Error([ 'sorry, createCredentials is not implemented yet', 'we accept pull requests', @@ -25521,7 +23960,7 @@ exports.createCredentials = function () { ].join('\n')) } -exports.constants = { +__webpack_unused_export__ = { 'DH_CHECK_P_NOT_SAFE_PRIME': 2, 'DH_CHECK_P_NOT_PRIME': 1, 'DH_UNABLE_TO_CHECK_GENERATOR': 4, @@ -32810,6 +31249,10 @@ function getLength(buf, p) { return false; } + if(buf[p.place] === 0x00) { + return false; + } + var val = 0; for (var i = 0, off = p.place; i < octetLen; i++, off++) { val <<= 8; @@ -32858,6 +31301,9 @@ Signature.prototype._importDER = function _importDER(data, enc) { if (rlen === false) { return false; } + if ((data[p.place] & 128) !== 0) { + return false; + } var r = data.slice(p.place, rlen + p.place); p.place += rlen; if (data[p.place++] !== 0x02) { @@ -32870,6 +31316,9 @@ Signature.prototype._importDER = function _importDER(data, enc) { if (data.length !== slen + p.place) { return false; } + if ((data[p.place] & 128) !== 0) { + return false; + } var s = data.slice(p.place, slen + p.place); if (r[0] === 0) { if (r[1] & 0x80) { @@ -32998,6 +31447,9 @@ EDDSA.prototype.sign = function sign(message, secret) { EDDSA.prototype.verify = function verify(message, sig, pub) { message = parseBytes(message); sig = this.makeSignature(sig); + if (sig.S().gte(sig.eddsa.curve.n) || sig.S().isNeg()) { + return false; + } var key = this.keyFromPublic(pub); var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); var SG = this.g.mul(sig.S()); @@ -33196,6 +31648,7 @@ function Signature(eddsa, sig) { sig = parseBytes(sig); if (Array.isArray(sig)) { + assert(sig.length === eddsa.encodingLength * 2, 'Signature has invalid size'); sig = { R: sig.slice(0, eddsa.encodingLength), S: sig.slice(eddsa.encodingLength), @@ -37722,10 +36175,9 @@ module.exports = URIError; /***/ }), /***/ 7007: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ ((module) => { "use strict"; -/* provided dependency */ var console = __webpack_require__(6763); // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -40851,7 +39303,6 @@ module.exports = function isTypedArray(value) { /***/ 1176: /***/ ((module, exports, __webpack_require__) => { -/* provided dependency */ var process = __webpack_require__(5606); var __WEBPACK_AMD_DEFINE_RESULT__;/** * [js-sha3]{@link https://github.com/emn178/js-sha3} * @@ -45855,62 +44306,6 @@ module.exports = function getPolyfill() { }; -/***/ }), - -/***/ 1072: -/***/ ((__unused_webpack_module, exports) => { - -exports.endianness = function () { return 'LE' }; - -exports.hostname = function () { - if (typeof location !== 'undefined') { - return location.hostname - } - else return ''; -}; - -exports.loadavg = function () { return [] }; - -exports.uptime = function () { return 0 }; - -exports.freemem = function () { - return Number.MAX_VALUE; -}; - -exports.totalmem = function () { - return Number.MAX_VALUE; -}; - -exports.cpus = function () { return [] }; - -exports.type = function () { return 'Browser' }; - -exports.release = function () { - if (typeof navigator !== 'undefined') { - return navigator.appVersion; - } - return ''; -}; - -exports.networkInterfaces -= exports.getNetworkInterfaces -= function () { return {} }; - -exports.arch = function () { return 'javascript' }; - -exports.platform = function () { return 'browser' }; - -exports.tmpdir = exports.tmpDir = function () { - return '/tmp'; -}; - -exports.EOL = '\n'; - -exports.homedir = function () { - return '/' -}; - - /***/ }), /***/ 1137: @@ -46438,7 +44833,6 @@ module.exports = function (password, salt, iterations, keylen, digest, callback) /***/ 2455: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/* provided dependency */ var process = __webpack_require__(5606); var defaultEncoding /* istanbul ignore next */ if (__webpack_require__.g.process && __webpack_require__.g.process.browser) { @@ -46638,10 +45032,9 @@ module.exports = [ /***/ }), /***/ 3225: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ ((module) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(5606); if (typeof process === 'undefined' || @@ -46689,197 +45082,6 @@ function nextTick(fn, arg1, arg2, arg3) { -/***/ }), - -/***/ 5606: -/***/ ((module) => { - -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - - /***/ }), /***/ 7168: @@ -50624,7 +48826,6 @@ module.exports = function xor (a, b) { /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(5606); // limit of Crypto.getRandomValues() @@ -50683,7 +48884,6 @@ function randomBytes (size, cb) { /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(5606); function oldBrowser () { @@ -50935,7 +49135,6 @@ module.exports.F = codes; /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(5606); // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -51113,7 +49312,6 @@ PassThrough.prototype._transform = function (chunk, encoding, cb) { /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(5606); // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -52345,7 +50543,6 @@ function done(stream, er, data) { /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(5606); // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -52994,7 +51191,6 @@ Writable.prototype._destroy = function (err, cb) { /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(5606); var _Object$setPrototypeO; @@ -53369,10 +51565,9 @@ module.exports = /*#__PURE__*/function () { /***/ }), /***/ 5896: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ ((module) => { "use strict"; -/* provided dependency */ var process = __webpack_require__(5606); // undocumented cb() API, needed for core, not for public API @@ -55409,7 +53604,6 @@ function simpleEnd(buf) { /***/ 4643: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/* provided dependency */ var console = __webpack_require__(6763); /** * Module exports. @@ -55838,8 +54032,6 @@ exports.isAnyArrayBuffer = isAnyArrayBuffer; /***/ 537: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { -/* provided dependency */ var process = __webpack_require__(5606); -/* provided dependency */ var console = __webpack_require__(6763); // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -56715,1908 +54907,4285 @@ exports.createContext = Script.createContext = function (context) { /***/ }), -/***/ 4400: +/***/ 5767: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/* - Copyright 2019 0KIMS association. - - This file is part of wasmbuilder - - wasmbuilder is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmbuilder is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmbuilder. If not, see . -*/ - -module.exports.ModuleBuilder = __webpack_require__(442); -/* unused reexport */ __webpack_require__(8269); -/* unused reexport */ __webpack_require__(7831); +"use strict"; -/***/ }), +var forEach = __webpack_require__(2682); +var availableTypedArrays = __webpack_require__(9209); +var callBind = __webpack_require__(487); +var callBound = __webpack_require__(8075); +var gOPD = __webpack_require__(5795); -/***/ 5705: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/** @type {(O: object) => string} */ +var $toString = callBound('Object.prototype.toString'); +var hasToStringTag = __webpack_require__(9092)(); -/* - Copyright 2019 0KIMS association. +var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; +var typedArrays = availableTypedArrays(); - This file is part of wasmbuilder +var $slice = callBound('String.prototype.slice'); +var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); - wasmbuilder is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. +/** @type {(array: readonly T[], value: unknown) => number} */ +var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) { + for (var i = 0; i < array.length; i += 1) { + if (array[i] === value) { + return i; + } + } + return -1; +}; - wasmbuilder is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmbuilder. If not, see . -*/ - -const utils = __webpack_require__(484); - -class CodeBuilder { - constructor(func) { - this.func = func; - this.functionName = func.functionName; - this.module = func.module; - } - - setLocal(localName, valCode) { - const idx = this.func.localIdxByName[localName]; - if (idx === undefined) - throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); - return [...valCode, 0x21, ...utils.varuint32( idx )]; - } - - teeLocal(localName, valCode) { - const idx = this.func.localIdxByName[localName]; - if (idx === undefined) - throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); - return [...valCode, 0x22, ...utils.varuint32( idx )]; - } - - getLocal(localName) { - const idx = this.func.localIdxByName[localName]; - if (idx === undefined) - throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); - return [0x20, ...utils.varuint32( idx )]; - } - - i64_load8_s(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 0 : _align; // 8 bits alignment by default - return [...idxCode, 0x30, align, ...utils.varuint32(offset)]; - } - - i64_load8_u(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 0 : _align; // 8 bits alignment by default - return [...idxCode, 0x31, align, ...utils.varuint32(offset)]; - } - - i64_load16_s(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 1 : _align; // 16 bits alignment by default - return [...idxCode, 0x32, align, ...utils.varuint32(offset)]; - } - - i64_load16_u(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 1 : _align; // 16 bits alignment by default - return [...idxCode, 0x33, align, ...utils.varuint32(offset)]; - } - - i64_load32_s(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default - return [...idxCode, 0x34, align, ...utils.varuint32(offset)]; - } - - i64_load32_u(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default - return [...idxCode, 0x35, align, ...utils.varuint32(offset)]; - } - - i64_load(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 3 : _align; // 64 bits alignment by default - return [...idxCode, 0x29, align, ...utils.varuint32(offset)]; - } - - - i64_store(idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (Array.isArray(_offset)) { - offset = 0; - align = 3; - codeVal = _offset; - } else if (Array.isArray(_align)) { - offset = _offset; - align = 3; - codeVal = _align; - } else if (Array.isArray(_codeVal)) { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - return [...idxCode, ...codeVal, 0x37, align, ...utils.varuint32(offset)]; - } - - i64_store32(idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (Array.isArray(_offset)) { - offset = 0; - align = 2; - codeVal = _offset; - } else if (Array.isArray(_align)) { - offset = _offset; - align = 2; - codeVal = _align; - } else if (Array.isArray(_codeVal)) { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - return [...idxCode, ...codeVal, 0x3e, align, ...utils.varuint32(offset)]; - } - - - i64_store16(idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (Array.isArray(_offset)) { - offset = 0; - align = 1; - codeVal = _offset; - } else if (Array.isArray(_align)) { - offset = _offset; - align = 1; - codeVal = _align; - } else if (Array.isArray(_codeVal)) { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - return [...idxCode, ...codeVal, 0x3d, align, ...utils.varuint32(offset)]; - } - - - i64_store8(idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (Array.isArray(_offset)) { - offset = 0; - align = 0; - codeVal = _offset; - } else if (Array.isArray(_align)) { - offset = _offset; - align = 0; - codeVal = _align; - } else if (Array.isArray(_codeVal)) { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - return [...idxCode, ...codeVal, 0x3c, align, ...utils.varuint32(offset)]; - } - - i32_load8_s(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default - return [...idxCode, 0x2c, align, ...utils.varuint32(offset)]; - } - - i32_load8_u(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default - return [...idxCode, 0x2d, align, ...utils.varuint32(offset)]; - } - - i32_load16_s(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default - return [...idxCode, 0x2e, align, ...utils.varuint32(offset)]; - } - - i32_load16_u(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default - return [...idxCode, 0x2f, align, ...utils.varuint32(offset)]; - } - - i32_load(idxCode, _offset, _align) { - const offset = _offset || 0; - const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default - return [...idxCode, 0x28, align, ...utils.varuint32(offset)]; - } - - i32_store(idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (Array.isArray(_offset)) { - offset = 0; - align = 2; - codeVal = _offset; - } else if (Array.isArray(_align)) { - offset = _offset; - align = 2; - codeVal = _align; - } else if (Array.isArray(_codeVal)) { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - return [...idxCode, ...codeVal, 0x36, align, ...utils.varuint32(offset)]; - } - - - i32_store16(idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (Array.isArray(_offset)) { - offset = 0; - align = 1; - codeVal = _offset; - } else if (Array.isArray(_align)) { - offset = _offset; - align = 1; - codeVal = _align; - } else if (Array.isArray(_codeVal)) { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - return [...idxCode, ...codeVal, 0x3b, align, ...utils.varuint32(offset)]; - } - - i32_store8(idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (Array.isArray(_offset)) { - offset = 0; - align = 0; - codeVal = _offset; - } else if (Array.isArray(_align)) { - offset = _offset; - align = 0; - codeVal = _align; - } else if (Array.isArray(_codeVal)) { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - return [...idxCode, ...codeVal, 0x3a, align, ...utils.varuint32(offset)]; - } - - call(fnName, ...args) { - const idx = this.module.functionIdxByName[fnName]; - if (idx === undefined) - throw new Error(`Function not defined: Function: ${fnName}`); - return [...[].concat(...args), 0x10, ...utils.varuint32(idx)]; - } - - call_indirect(fnIdx, ...args) { - return [...[].concat(...args), ...fnIdx, 0x11, 0, 0]; - } - - if(condCode, thenCode, elseCode) { - if (elseCode) { - return [...condCode, 0x04, 0x40, ...thenCode, 0x05, ...elseCode, 0x0b]; - } else { - return [...condCode, 0x04, 0x40, ...thenCode, 0x0b]; - } - } - - block(bCode) { return [0x02, 0x40, ...bCode, 0x0b]; } - loop(...args) { - return [0x03, 0x40, ...[].concat(...[...args]), 0x0b]; - } - br_if(relPath, condCode) { return [...condCode, 0x0d, ...utils.varuint32(relPath)]; } - br(relPath) { return [0x0c, ...utils.varuint32(relPath)]; } - ret(rCode) { return [...rCode, 0x0f]; } - drop(dCode) { return [...dCode, 0x1a]; } - - i64_const(num) { return [0x42, ...utils.varint64(num)]; } - i32_const(num) { return [0x41, ...utils.varint32(num)]; } - - - i64_eqz(opcode) { return [...opcode, 0x50]; } - i64_eq(op1code, op2code) { return [...op1code, ...op2code, 0x51]; } - i64_ne(op1code, op2code) { return [...op1code, ...op2code, 0x52]; } - i64_lt_s(op1code, op2code) { return [...op1code, ...op2code, 0x53]; } - i64_lt_u(op1code, op2code) { return [...op1code, ...op2code, 0x54]; } - i64_gt_s(op1code, op2code) { return [...op1code, ...op2code, 0x55]; } - i64_gt_u(op1code, op2code) { return [...op1code, ...op2code, 0x56]; } - i64_le_s(op1code, op2code) { return [...op1code, ...op2code, 0x57]; } - i64_le_u(op1code, op2code) { return [...op1code, ...op2code, 0x58]; } - i64_ge_s(op1code, op2code) { return [...op1code, ...op2code, 0x59]; } - i64_ge_u(op1code, op2code) { return [...op1code, ...op2code, 0x5a]; } - i64_add(op1code, op2code) { return [...op1code, ...op2code, 0x7c]; } - i64_sub(op1code, op2code) { return [...op1code, ...op2code, 0x7d]; } - i64_mul(op1code, op2code) { return [...op1code, ...op2code, 0x7e]; } - i64_div_s(op1code, op2code) { return [...op1code, ...op2code, 0x7f]; } - i64_div_u(op1code, op2code) { return [...op1code, ...op2code, 0x80]; } - i64_rem_s(op1code, op2code) { return [...op1code, ...op2code, 0x81]; } - i64_rem_u(op1code, op2code) { return [...op1code, ...op2code, 0x82]; } - i64_and(op1code, op2code) { return [...op1code, ...op2code, 0x83]; } - i64_or(op1code, op2code) { return [...op1code, ...op2code, 0x84]; } - i64_xor(op1code, op2code) { return [...op1code, ...op2code, 0x85]; } - i64_shl(op1code, op2code) { return [...op1code, ...op2code, 0x86]; } - i64_shr_s(op1code, op2code) { return [...op1code, ...op2code, 0x87]; } - i64_shr_u(op1code, op2code) { return [...op1code, ...op2code, 0x88]; } - i64_extend_i32_s(op1code) { return [...op1code, 0xac]; } - i64_extend_i32_u(op1code) { return [...op1code, 0xad]; } - i64_clz(op1code) { return [...op1code, 0x79]; } - i64_ctz(op1code) { return [...op1code, 0x7a]; } - - i32_eqz(op1code) { return [...op1code, 0x45]; } - i32_eq(op1code, op2code) { return [...op1code, ...op2code, 0x46]; } - i32_ne(op1code, op2code) { return [...op1code, ...op2code, 0x47]; } - i32_lt_s(op1code, op2code) { return [...op1code, ...op2code, 0x48]; } - i32_lt_u(op1code, op2code) { return [...op1code, ...op2code, 0x49]; } - i32_gt_s(op1code, op2code) { return [...op1code, ...op2code, 0x4a]; } - i32_gt_u(op1code, op2code) { return [...op1code, ...op2code, 0x4b]; } - i32_le_s(op1code, op2code) { return [...op1code, ...op2code, 0x4c]; } - i32_le_u(op1code, op2code) { return [...op1code, ...op2code, 0x4d]; } - i32_ge_s(op1code, op2code) { return [...op1code, ...op2code, 0x4e]; } - i32_ge_u(op1code, op2code) { return [...op1code, ...op2code, 0x4f]; } - i32_add(op1code, op2code) { return [...op1code, ...op2code, 0x6a]; } - i32_sub(op1code, op2code) { return [...op1code, ...op2code, 0x6b]; } - i32_mul(op1code, op2code) { return [...op1code, ...op2code, 0x6c]; } - i32_div_s(op1code, op2code) { return [...op1code, ...op2code, 0x6d]; } - i32_div_u(op1code, op2code) { return [...op1code, ...op2code, 0x6e]; } - i32_rem_s(op1code, op2code) { return [...op1code, ...op2code, 0x6f]; } - i32_rem_u(op1code, op2code) { return [...op1code, ...op2code, 0x70]; } - i32_and(op1code, op2code) { return [...op1code, ...op2code, 0x71]; } - i32_or(op1code, op2code) { return [...op1code, ...op2code, 0x72]; } - i32_xor(op1code, op2code) { return [...op1code, ...op2code, 0x73]; } - i32_shl(op1code, op2code) { return [...op1code, ...op2code, 0x74]; } - i32_shr_s(op1code, op2code) { return [...op1code, ...op2code, 0x75]; } - i32_shr_u(op1code, op2code) { return [...op1code, ...op2code, 0x76]; } - i32_rotl(op1code, op2code) { return [...op1code, ...op2code, 0x77]; } - i32_rotr(op1code, op2code) { return [...op1code, ...op2code, 0x78]; } - i32_wrap_i64(op1code) { return [...op1code, 0xa7]; } - i32_clz(op1code) { return [...op1code, 0x67]; } - i32_ctz(op1code) { return [...op1code, 0x68]; } - - unreachable() { return [ 0x0 ]; } - - current_memory() { return [ 0x3f, 0]; } - - comment() { return []; } +/** @typedef {(receiver: import('.').TypedArray) => string | typeof Uint8Array.prototype.slice.call | typeof Uint8Array.prototype.set.call} Getter */ +/** @type {{ [k in `\$${import('.').TypedArrayName}`]?: Getter } & { __proto__: null }} */ +var cache = { __proto__: null }; +if (hasToStringTag && gOPD && getPrototypeOf) { + forEach(typedArrays, function (typedArray) { + var arr = new g[typedArray](); + if (Symbol.toStringTag in arr) { + var proto = getPrototypeOf(arr); + // @ts-expect-error TS won't narrow inside a closure + var descriptor = gOPD(proto, Symbol.toStringTag); + if (!descriptor) { + var superProto = getPrototypeOf(proto); + // @ts-expect-error TS won't narrow inside a closure + descriptor = gOPD(superProto, Symbol.toStringTag); + } + // @ts-expect-error TODO: fix + cache['$' + typedArray] = callBind(descriptor.get); + } + }); +} else { + forEach(typedArrays, function (typedArray) { + var arr = new g[typedArray](); + var fn = arr.slice || arr.set; + if (fn) { + // @ts-expect-error TODO: fix + cache['$' + typedArray] = callBind(fn); + } + }); } -module.exports = CodeBuilder; +/** @type {(value: object) => false | import('.').TypedArrayName} */ +var tryTypedArrays = function tryAllTypedArrays(value) { + /** @type {ReturnType} */ var found = false; + forEach( + // eslint-disable-next-line no-extra-parens + /** @type {Record<`\$${TypedArrayName}`, Getter>} */ /** @type {any} */ (cache), + /** @type {(getter: Getter, name: `\$${import('.').TypedArrayName}`) => void} */ + function (getter, typedArray) { + if (!found) { + try { + // @ts-expect-error TODO: fix + if ('$' + getter(value) === typedArray) { + found = $slice(typedArray, 1); + } + } catch (e) { /**/ } + } + } + ); + return found; +}; +/** @type {(value: object) => false | import('.').TypedArrayName} */ +var trySlices = function tryAllSlices(value) { + /** @type {ReturnType} */ var found = false; + forEach( + // eslint-disable-next-line no-extra-parens + /** @type {Record<`\$${TypedArrayName}`, Getter>} */ /** @type {any} */ (cache), + /** @type {(getter: typeof cache, name: `\$${import('.').TypedArrayName}`) => void} */ function (getter, name) { + if (!found) { + try { + // @ts-expect-error TODO: fix + getter(value); + found = $slice(name, 1); + } catch (e) { /**/ } + } + } + ); + return found; +}; -/***/ }), - -/***/ 4010: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmbuilder - - wasmbuilder is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmbuilder is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmbuilder. If not, see . -*/ - -const utils = __webpack_require__(484); - -class CodeBuilderWat { - constructor(func) { - this.func = func; - this.functionName = func.functionName; - this.module = func.module; - } - - setLocal(localName, valCode) { - const idx = this.func.localIdxByName[localName]; - if (idx === undefined) - throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); - return [valCode, `set_local $${localName}`]; - } - - teeLocal(localName, valCode) { - const idx = this.func.localIdxByName[localName]; - if (idx === undefined) - throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); - return [valCode, `tee_local $${localName}`]; - } - - getLocal(localName) { - const idx = this.func.localIdxByName[localName]; - if (idx === undefined) - throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); - return `get_local $${localName}`; - } - - genLoad(inst, def_align, idxCode, _offset, _align) { - let S = inst; - const offset = _offset || 0; - if (offset>0) S += ` offset=${offset}`; - const align = (_align === undefined) ? def_align : _align; // 8 bits alignment by default - if (align!=def_align) S += ` align=${1 << align}`; - return [idxCode, S]; - } - - - genStore(inst, def_align, idxCode, _offset, _align, _codeVal) { - let offset, align, codeVal; - if (typeof _align === "undefined") { - offset = 0; - align = def_align; - codeVal = _offset; - } else if (typeof _codeVal === "undefined") { - offset = _offset; - align = def_align; - codeVal = _align; - } else { - offset = _offset; - align = _align; - codeVal = _codeVal; - } - let S = inst; - if (offset>0) S += ` offset=${offset}`; - if (align!=def_align) S += ` align=${1 << align}`; - return [idxCode, codeVal, S]; - } - - i64_load8_s(idxCode, _offset, _align) { - return this.genLoad("i64.load8_s", 0, idxCode, _offset, _align); - } - - i64_load8_u(idxCode, _offset, _align) { - return this.genLoad("i64.load8_u", 0, idxCode, _offset, _align); - } - - i64_load16_s(idxCode, _offset, _align) { - return this.genLoad("i64.load16_s", 1,idxCode, _offset, _align); - } - - i64_load16_u(idxCode, _offset, _align) { - return this.genLoad("i64.load16_u", 1, idxCode, _offset, _align); - } - - i64_load32_s(idxCode, _offset, _align) { - return this.genLoad("i64.load32_s", 2, idxCode, _offset, _align); - } - - i64_load32_u(idxCode, _offset, _align) { - return this.genLoad("i64.load32_u", 2, idxCode, _offset, _align); - } - - i64_load(idxCode, _offset, _align) { - return this.genLoad("i64.load", 3, idxCode, _offset, _align); - } - - - i64_store(idxCode, _offset, _align, _codeVal) { - return this.genStore("i64.store", 3, idxCode, _offset, _align, _codeVal); - } - - i64_store32(idxCode, _offset, _align, _codeVal) { - return this.genStore("i64.store32", 2, idxCode, _offset, _align, _codeVal); - } - - i64_store16(idxCode, _offset, _align, _codeVal) { - return this.genStore("i64.store16", 1, idxCode, _offset, _align, _codeVal); - } - - i64_store8(idxCode, _offset, _align, _codeVal) { - return this.genStore("i64.store8", 0, idxCode, _offset, _align, _codeVal); - } - - i32_load8_s(idxCode, _offset, _align) { - return this.genLoad("i32.load8_s", 0, idxCode, _offset, _align); - } - - i32_load8_u(idxCode, _offset, _align) { - return this.genLoad("i32.load8_u", 0, idxCode, _offset, _align); - } - - i32_load16_s(idxCode, _offset, _align) { - return this.genLoad("i32.load16_s", 1, idxCode, _offset, _align); - } - - i32_load16_u(idxCode, _offset, _align) { - return this.genLoad("i32.load16_u", 1, idxCode, _offset, _align); - } - - i32_load(idxCode, _offset, _align) { - return this.genLoad("i32.load", 2, idxCode, _offset, _align); - } - - i32_store(idxCode, _offset, _align, _codeVal) { - return this.genStore("i32.store", 2, idxCode, _offset, _align, _codeVal); - } - - i32_store16(idxCode, _offset, _align, _codeVal) { - return this.genStore("i32.store16", 1, idxCode, _offset, _align, _codeVal); - } - - i32_store8(idxCode, _offset, _align, _codeVal) { - return this.genStore("i32.store8", 0, idxCode, _offset, _align, _codeVal); - } - - call(fnName, ...args) { - const idx = this.module.functionIdxByName[fnName]; - if (idx === undefined) - throw new Error(`Function not defined: Function: ${fnName}`); - return [args, `call $${fnName}`]; - } - - call_indirect(fnIdx, ...args) { - return [args, fnIdx, "call_indirect (type 0)"]; - } - - if(condCode, thenCode, elseCode) { - if (elseCode) { - return [condCode, "if", utils.ident(thenCode), "else", utils.ident(elseCode), "end"]; - } else { - return [condCode, "if", utils.ident(thenCode), "end"]; - } - } - - block(bCode) { return ["block", utils.ident(bCode), "end"]; } - loop(...args) { return ["loop", utils.ident(args), "end"]; } - br_if(relPath, condCode) { return [condCode, `br_if ${relPath}`]; } - br(relPath) { return `br ${relPath}`; } - ret(rCode) { return [rCode, "return"]; } - drop(dCode) { return [dCode, "drop"]; } - - i64_const(num) { return `i64.const ${num}`; } - i32_const(num) { return `i32.const ${num}`; } - - i64_eqz(opcode) { return [opcode, "i64.eqz"]; } - i64_eq(op1code, op2code) { return [op1code, op2code, "i64.eq"]; } - i64_ne(op1code, op2code) { return [op1code, op2code, "i64.ne"]; } - i64_lt_s(op1code, op2code) { return [op1code, op2code, "i64.lt_s"]; } - i64_lt_u(op1code, op2code) { return [op1code, op2code, "i64.lt_u"]; } - i64_gt_s(op1code, op2code) { return [op1code, op2code, "i64.gt_s"]; } - i64_gt_u(op1code, op2code) { return [op1code, op2code, "i64.gt_u"]; } - i64_le_s(op1code, op2code) { return [op1code, op2code, "i64.le_s"]; } - i64_le_u(op1code, op2code) { return [op1code, op2code, "i64.le_u"]; } - i64_ge_s(op1code, op2code) { return [op1code, op2code, "i64.ge_s"]; } - i64_ge_u(op1code, op2code) { return [op1code, op2code, "i64.ge_u"]; } - i64_add(op1code, op2code) { return [op1code, op2code, "i64.add"]; } - i64_sub(op1code, op2code) { return [op1code, op2code, "i64.sub"]; } - i64_mul(op1code, op2code) { return [op1code, op2code, "i64.mul"]; } - i64_div_s(op1code, op2code) { return [op1code, op2code, "i64.div_s"]; } - i64_div_u(op1code, op2code) { return [op1code, op2code, "i64.div_u"]; } - i64_rem_s(op1code, op2code) { return [op1code, op2code, "i64.rem_s"]; } - i64_rem_u(op1code, op2code) { return [op1code, op2code, "i64.rem_u"]; } - i64_and(op1code, op2code) { return [op1code, op2code, "i64.and"]; } - i64_or(op1code, op2code) { return [op1code, op2code, "i64.or"]; } - i64_xor(op1code, op2code) { return [op1code, op2code, "i64.xor"]; } - i64_shl(op1code, op2code) { return [op1code, op2code, "i64.shl"]; } - i64_shr_s(op1code, op2code) { return [op1code, op2code, "i64.shr_s"]; } - i64_shr_u(op1code, op2code) { return [op1code, op2code, "i64.shr_u"]; } - i64_extend_i32_s(op1code) { return [op1code, "i64.extend_s/i32"]; } - i64_extend_i32_u(op1code) { return [op1code, "i64.extend_u/i32"]; } - - - i32_eqz(op1code) { return [op1code, "i32.eqz"]; } - i32_eq(op1code, op2code) { return [op1code, op2code, "i32.eq"]; } - i32_ne(op1code, op2code) { return [op1code, op2code, "i32.ne"]; } - i32_lt_s(op1code, op2code) { return [op1code, op2code, "i32.lt_s"]; } - i32_lt_u(op1code, op2code) { return [op1code, op2code, "i32.lt_u"]; } - i32_gt_s(op1code, op2code) { return [op1code, op2code, "i32.gt_s"]; } - i32_gt_u(op1code, op2code) { return [op1code, op2code, "i32.gt_u"]; } - i32_le_s(op1code, op2code) { return [op1code, op2code, "i32.le_s"]; } - i32_le_u(op1code, op2code) { return [op1code, op2code, "i32.le_u"]; } - i32_ge_s(op1code, op2code) { return [op1code, op2code, "i32.ge_s"]; } - i32_ge_u(op1code, op2code) { return [op1code, op2code, "i32.ge_u"]; } - i32_add(op1code, op2code) { return [op1code, op2code, "i32.add"]; } - i32_sub(op1code, op2code) { return [op1code, op2code, "i32.sub"]; } - i32_mul(op1code, op2code) { return [op1code, op2code, "i32.mul"]; } - i32_div_s(op1code, op2code) { return [op1code, op2code, "i32.div_s"]; } - i32_div_u(op1code, op2code) { return [op1code, op2code, "i32.div_u"]; } - i32_rem_s(op1code, op2code) { return [op1code, op2code, "i32.rem_s"]; } - i32_rem_u(op1code, op2code) { return [op1code, op2code, "i32.rem_u"]; } - i32_and(op1code, op2code) { return [op1code, op2code, "i32.and"]; } - i32_or(op1code, op2code) { return [op1code, op2code, "i32.or"]; } - i32_xor(op1code, op2code) { return [op1code, op2code, "i32.xor"]; } - i32_shl(op1code, op2code) { return [op1code, op2code, "i32.shl"]; } - i32_shr_s(op1code, op2code) { return [op1code, op2code, "i32.shr_s"]; } - i32_shr_u(op1code, op2code) { return [op1code, op2code, "i32.shr_u"]; } - i32_rotl(op1code, op2code) { return [op1code, op2code, "i32.rotl"]; } - i32_rotr(op1code, op2code) { return [op1code, op2code, "i32.rotr"]; } - i32_wrap_i64(op1code) { return [op1code, "i32.wrap/i64"]; } - - ureachable() { return "unreachable"; } - - current_memory() { return "current_memory"; } - - comment(c) { return ";; " + c; } - -} - -module.exports = CodeBuilderWat; - - -/***/ }), - -/***/ 5986: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmbuilder - - wasmbuilder is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmbuilder is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmbuilder. If not, see . -*/ - -const CodeBuilder = __webpack_require__(5705); -const utils = __webpack_require__(484); - -const typeCodes = { - "i32": 0x7f, - "i64": 0x7e, - "f32": 0x7d, - "f64": 0x7c, - "anyfunc": 0x70, - "func": 0x60, - "emptyblock": 0x40 +/** @type {import('.')} */ +module.exports = function whichTypedArray(value) { + if (!value || typeof value !== 'object') { return false; } + if (!hasToStringTag) { + /** @type {string} */ + var tag = $slice($toString(value), 8, -1); + if ($indexOf(typedArrays, tag) > -1) { + return tag; + } + if (tag !== 'Object') { + return false; + } + // node < 0.6 hits here on real Typed Arrays + return trySlices(value); + } + if (!gOPD) { return null; } // unknown engine + return tryTypedArrays(value); }; -class FunctionBuilder { +/***/ }), - constructor (module, fnName, fnType, moduleName, fieldName) { - if (fnType == "import") { - this.fnType = "import"; - this.moduleName = moduleName; - this.fieldName = fieldName; - } else if (fnType == "internal") { - this.fnType = "internal"; - } else { - throw new Error("Invalid function fnType: " + fnType); - } - this.module = module; - this.fnName = fnName; - this.params = []; - this.locals = []; - this.localIdxByName = {}; - this.code = []; - this.returnType = null; - this.nextLocal =0; - } +/***/ 8982: +/***/ (() => { - addParam(paramName, paramType) { - if (this.localIdxByName[paramName]) - throw new Error(`param already exists. Function: ${this.fnName}, Param: ${paramName} `); - const idx = this.nextLocal++; - this.localIdxByName[paramName] = idx; - this.params.push({ - type: paramType - }); - } +/* (ignored) */ - addLocal(localName, localType, _length) { - const length = _length || 1; - if (this.localIdxByName[localName]) - throw new Error(`local already exists. Function: ${this.fnName}, Param: ${localName} `); - const idx = this.nextLocal++; - this.localIdxByName[localName] = idx; - this.locals.push({ - type: localType, - length: length - }); - } +/***/ }), - setReturnType(returnType) { - if (this.returnType) - throw new Error(`returnType already defined. Function: ${this.fnName}`); - this.returnType = returnType; - } +/***/ 7790: +/***/ (() => { - getSignature() { - const params = [...utils.varuint32(this.params.length), ...this.params.map((p) => typeCodes[p.type])]; - const returns = this.returnType ? [0x01, typeCodes[this.returnType]] : [0]; - return [0x60, ...params, ...returns]; - } +/* (ignored) */ - getBody() { - const locals = this.locals.map((l) => [ - ...utils.varuint32(l.length), - typeCodes[l.type] - ]); +/***/ }), - const body = [ - ...utils.varuint32(this.locals.length), - ...[].concat(...locals), - ...this.code, - 0x0b - ]; - return [ - ...utils.varuint32(body.length), - ...body - ]; - } +/***/ 3776: +/***/ (() => { - addCode(...code) { - this.code.push(...[].concat(...[...code])); - } +/* (ignored) */ - getCodeBuilder() { - return new CodeBuilder(this); - } -} +/***/ }), -module.exports = FunctionBuilder; +/***/ 1638: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 2668: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 7965: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 6089: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 9368: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 4688: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 1069: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 5340: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 9838: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 7882: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 9209: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var possibleNames = __webpack_require__(6578); + +var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; + +/** @type {import('.')} */ +module.exports = function availableTypedArrays() { + var /** @type {ReturnType} */ out = []; + for (var i = 0; i < possibleNames.length; i++) { + if (typeof g[possibleNames[i]] === 'function') { + // @ts-expect-error + out[out.length] = possibleNames[i]; + } + } + return out; +}; /***/ }), -/***/ 2341: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmbuilder - - wasmbuilder is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmbuilder is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmbuilder. If not, see . -*/ - -const CodeBuilderWat = __webpack_require__(4010); -const utils = __webpack_require__(484); - -class FunctionBuilderWat { - - constructor (module, fnName, fnType, moduleName, fieldName) { - if (fnType == "import") { - this.fnType = "import"; - this.moduleName = moduleName; - this.fieldName = fieldName; - } else if (fnType == "internal") { - this.fnType = "internal"; - this.comment = moduleName; - } else { - throw new Error("Invalid function fnType: " + fnType); - } - this.module = module; - this.fnName = fnName; - this.params = []; - this.locals = []; - this.localIdxByName = {}; - this.code = []; - this.returnType = null; - this.nextLocal =0; - } - - addParam(paramName, paramType) { - if (this.localIdxByName[paramName]) - throw new Error(`param already exists. Function: ${this.fnName}, Param: ${paramName} `); - const idx = this.nextLocal++; - this.localIdxByName[paramName] = idx; - this.params.push({ - type: paramType, - name: paramName - }); - } - - addLocal(localName, localType, _length) { - if ((typeof _length != "undefined") && (_length != 1)) { - throw new Error("Locals greater than 1 not implemented"); - } - if (this.localIdxByName[localName]) - throw new Error(`local already exists. Function: ${this.fnName}, Param: ${localName} `); - const idx = this.nextLocal++; - this.localIdxByName[localName] = idx; - this.locals.push({ - type: localType, - name: localName, - }); - } - - setReturnType(returnType) { - if (this.returnType) - throw new Error(`returnType already defined. Function: ${this.fnName}`); - this.returnType = returnType; - } - - getSignature() { - let p = ""; - for (let i=0; i { +"use strict"; +module.exports = /*#__PURE__*/JSON.parse('{"aes-128-ecb":{"cipher":"AES","key":128,"iv":0,"mode":"ECB","type":"block"},"aes-192-ecb":{"cipher":"AES","key":192,"iv":0,"mode":"ECB","type":"block"},"aes-256-ecb":{"cipher":"AES","key":256,"iv":0,"mode":"ECB","type":"block"},"aes-128-cbc":{"cipher":"AES","key":128,"iv":16,"mode":"CBC","type":"block"},"aes-192-cbc":{"cipher":"AES","key":192,"iv":16,"mode":"CBC","type":"block"},"aes-256-cbc":{"cipher":"AES","key":256,"iv":16,"mode":"CBC","type":"block"},"aes128":{"cipher":"AES","key":128,"iv":16,"mode":"CBC","type":"block"},"aes192":{"cipher":"AES","key":192,"iv":16,"mode":"CBC","type":"block"},"aes256":{"cipher":"AES","key":256,"iv":16,"mode":"CBC","type":"block"},"aes-128-cfb":{"cipher":"AES","key":128,"iv":16,"mode":"CFB","type":"stream"},"aes-192-cfb":{"cipher":"AES","key":192,"iv":16,"mode":"CFB","type":"stream"},"aes-256-cfb":{"cipher":"AES","key":256,"iv":16,"mode":"CFB","type":"stream"},"aes-128-cfb8":{"cipher":"AES","key":128,"iv":16,"mode":"CFB8","type":"stream"},"aes-192-cfb8":{"cipher":"AES","key":192,"iv":16,"mode":"CFB8","type":"stream"},"aes-256-cfb8":{"cipher":"AES","key":256,"iv":16,"mode":"CFB8","type":"stream"},"aes-128-cfb1":{"cipher":"AES","key":128,"iv":16,"mode":"CFB1","type":"stream"},"aes-192-cfb1":{"cipher":"AES","key":192,"iv":16,"mode":"CFB1","type":"stream"},"aes-256-cfb1":{"cipher":"AES","key":256,"iv":16,"mode":"CFB1","type":"stream"},"aes-128-ofb":{"cipher":"AES","key":128,"iv":16,"mode":"OFB","type":"stream"},"aes-192-ofb":{"cipher":"AES","key":192,"iv":16,"mode":"OFB","type":"stream"},"aes-256-ofb":{"cipher":"AES","key":256,"iv":16,"mode":"OFB","type":"stream"},"aes-128-ctr":{"cipher":"AES","key":128,"iv":16,"mode":"CTR","type":"stream"},"aes-192-ctr":{"cipher":"AES","key":192,"iv":16,"mode":"CTR","type":"stream"},"aes-256-ctr":{"cipher":"AES","key":256,"iv":16,"mode":"CTR","type":"stream"},"aes-128-gcm":{"cipher":"AES","key":128,"iv":12,"mode":"GCM","type":"auth"},"aes-192-gcm":{"cipher":"AES","key":192,"iv":12,"mode":"GCM","type":"auth"},"aes-256-gcm":{"cipher":"AES","key":256,"iv":12,"mode":"GCM","type":"auth"}}'); /***/ }), -/***/ 442: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmbuilder - - wasmbuilder is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmbuilder is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmbuilder. If not, see . -*/ - - -const FunctionBuilder = __webpack_require__(5986); -const utils = __webpack_require__(484); - -class ModuleBuilder { - - constructor() { - this.functions = []; - this.functionIdxByName = {}; - this.nImportFunctions = 0; - this.nInternalFunctions =0; - this.memory = { - pagesSize: 1, - moduleName: "env", - fieldName: "memory" - }; - this.free = 8; - this.datas = []; - this.modules = {}; - this.exports = []; - this.functionsTable = []; - } - - build() { - this._setSignatures(); - return new Uint8Array([ - ...utils.u32(0x6d736100), - ...utils.u32(1), - ...this._buildType(), - ...this._buildImport(), - ...this._buildFunctionDeclarations(), - ...this._buildFunctionsTable(), - ...this._buildExports(), - ...this._buildElements(), - ...this._buildCode(), - ...this._buildData() - ]); - } - - addFunction(fnName) { - if (typeof(this.functionIdxByName[fnName]) !== "undefined") - throw new Error(`Function already defined: ${fnName}`); - - const idx = this.functions.length; - this.functionIdxByName[fnName] = idx; - - this.functions.push(new FunctionBuilder(this, fnName, "internal")); - - this.nInternalFunctions++; - return this.functions[idx]; - } - - addIimportFunction(fnName, moduleName, _fieldName) { - if (typeof(this.functionIdxByName[fnName]) !== "undefined") - throw new Error(`Function already defined: ${fnName}`); - - if ( (this.functions.length>0) - &&(this.functions[this.functions.length-1].type == "internal")) - throw new Error(`Import functions must be declared before internal: ${fnName}`); - - let fieldName = _fieldName || fnName; - - const idx = this.functions.length; - this.functionIdxByName[fnName] = idx; - - this.functions.push(new FunctionBuilder(this, fnName, "import", moduleName, fieldName)); - - this.nImportFunctions ++; - return this.functions[idx]; - } - - setMemory(pagesSize, moduleName, fieldName) { - this.memory = { - pagesSize: pagesSize, - moduleName: moduleName || "env", - fieldName: fieldName || "memory" - }; - } - - exportFunction(fnName, _exportName) { - const exportName = _exportName || fnName; - if (typeof(this.functionIdxByName[fnName]) === "undefined") - throw new Error(`Function not defined: ${fnName}`); - const idx = this.functionIdxByName[fnName]; - if (exportName != fnName) { - this.functionIdxByName[exportName] = idx; - } - this.exports.push({ - exportName: exportName, - idx: idx - }); - } - - addFunctionToTable(fnName) { - const idx = this.functionIdxByName[fnName]; - this.functionsTable.push(idx); - } - - addData(offset, bytes) { - this.datas.push({ - offset: offset, - bytes: bytes - }); - } - - alloc(a, b) { - let size; - let bytes; - if ((Array.isArray(a) || ArrayBuffer.isView(a)) && (typeof(b) === "undefined")) { - size = a.length; - bytes = a; - } else { - size = a; - bytes = b; - } - size = (((size-1)>>3) +1)<<3; // Align to 64 bits. - const p = this.free; - this.free += size; - if (bytes) { - this.addData(p, bytes); - } - return p; - } - - allocString(s) { - const encoder = new globalThis.TextEncoder(); - const uint8array = encoder.encode(s); - return this.alloc([...uint8array, 0]); - } - - _setSignatures() { - this.signatures = []; - const signatureIdxByName = {}; - if (this.functionsTable.length>0) { - const signature = this.functions[this.functionsTable[0]].getSignature(); - const signatureName = "s_"+utils.toHexString(signature); - signatureIdxByName[signatureName] = 0; - this.signatures.push(signature); - } - for (let i=0; i { +"use strict"; +module.exports = /*#__PURE__*/JSON.parse('{"sha224WithRSAEncryption":{"sign":"rsa","hash":"sha224","id":"302d300d06096086480165030402040500041c"},"RSA-SHA224":{"sign":"ecdsa/rsa","hash":"sha224","id":"302d300d06096086480165030402040500041c"},"sha256WithRSAEncryption":{"sign":"rsa","hash":"sha256","id":"3031300d060960864801650304020105000420"},"RSA-SHA256":{"sign":"ecdsa/rsa","hash":"sha256","id":"3031300d060960864801650304020105000420"},"sha384WithRSAEncryption":{"sign":"rsa","hash":"sha384","id":"3041300d060960864801650304020205000430"},"RSA-SHA384":{"sign":"ecdsa/rsa","hash":"sha384","id":"3041300d060960864801650304020205000430"},"sha512WithRSAEncryption":{"sign":"rsa","hash":"sha512","id":"3051300d060960864801650304020305000440"},"RSA-SHA512":{"sign":"ecdsa/rsa","hash":"sha512","id":"3051300d060960864801650304020305000440"},"RSA-SHA1":{"sign":"rsa","hash":"sha1","id":"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{"sign":"ecdsa","hash":"sha1","id":""},"sha256":{"sign":"ecdsa","hash":"sha256","id":""},"sha224":{"sign":"ecdsa","hash":"sha224","id":""},"sha384":{"sign":"ecdsa","hash":"sha384","id":""},"sha512":{"sign":"ecdsa","hash":"sha512","id":""},"DSA-SHA":{"sign":"dsa","hash":"sha1","id":""},"DSA-SHA1":{"sign":"dsa","hash":"sha1","id":""},"DSA":{"sign":"dsa","hash":"sha1","id":""},"DSA-WITH-SHA224":{"sign":"dsa","hash":"sha224","id":""},"DSA-SHA224":{"sign":"dsa","hash":"sha224","id":""},"DSA-WITH-SHA256":{"sign":"dsa","hash":"sha256","id":""},"DSA-SHA256":{"sign":"dsa","hash":"sha256","id":""},"DSA-WITH-SHA384":{"sign":"dsa","hash":"sha384","id":""},"DSA-SHA384":{"sign":"dsa","hash":"sha384","id":""},"DSA-WITH-SHA512":{"sign":"dsa","hash":"sha512","id":""},"DSA-SHA512":{"sign":"dsa","hash":"sha512","id":""},"DSA-RIPEMD160":{"sign":"dsa","hash":"rmd160","id":""},"ripemd160WithRSA":{"sign":"rsa","hash":"rmd160","id":"3021300906052b2403020105000414"},"RSA-RIPEMD160":{"sign":"rsa","hash":"rmd160","id":"3021300906052b2403020105000414"},"md5WithRSAEncryption":{"sign":"rsa","hash":"md5","id":"3020300c06082a864886f70d020505000410"},"RSA-MD5":{"sign":"rsa","hash":"md5","id":"3020300c06082a864886f70d020505000410"}}'); /***/ }), -/***/ 8269: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ 4589: +/***/ ((module) => { + +"use strict"; +module.exports = /*#__PURE__*/JSON.parse('{"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}'); + +/***/ }), + +/***/ 3241: +/***/ ((module) => { + +"use strict"; +module.exports = /*#__PURE__*/JSON.parse('{"modp1":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},"modp2":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},"modp5":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},"modp14":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},"modp15":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},"modp16":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},"modp17":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},"modp18":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}}'); + +/***/ }), + +/***/ 1636: +/***/ ((module) => { + +"use strict"; +module.exports = {"rE":"6.5.7"}; + +/***/ }), + +/***/ 5579: +/***/ ((module) => { + +"use strict"; +module.exports = /*#__PURE__*/JSON.parse('{"2.16.840.1.101.3.4.1.1":"aes-128-ecb","2.16.840.1.101.3.4.1.2":"aes-128-cbc","2.16.840.1.101.3.4.1.3":"aes-128-ofb","2.16.840.1.101.3.4.1.4":"aes-128-cfb","2.16.840.1.101.3.4.1.21":"aes-192-ecb","2.16.840.1.101.3.4.1.22":"aes-192-cbc","2.16.840.1.101.3.4.1.23":"aes-192-ofb","2.16.840.1.101.3.4.1.24":"aes-192-cfb","2.16.840.1.101.3.4.1.41":"aes-256-ecb","2.16.840.1.101.3.4.1.42":"aes-256-cbc","2.16.840.1.101.3.4.1.43":"aes-256-ofb","2.16.840.1.101.3.4.1.44":"aes-256-cfb"}'); + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ id: moduleId, +/******/ loaded: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/amd options */ +/******/ (() => { +/******/ __webpack_require__.amdO = {}; +/******/ })(); +/******/ +/******/ /* webpack/runtime/compat get default export */ +/******/ (() => { +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = (module) => { +/******/ var getter = module && module.__esModule ? +/******/ () => (module['default']) : +/******/ () => (module); +/******/ __webpack_require__.d(getter, { a: getter }); +/******/ return getter; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/define property getters */ +/******/ (() => { +/******/ // define getter functions for harmony exports +/******/ __webpack_require__.d = (exports, definition) => { +/******/ for(var key in definition) { +/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { +/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); +/******/ } +/******/ } +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/global */ +/******/ (() => { +/******/ __webpack_require__.g = (function() { +/******/ if (typeof globalThis === 'object') return globalThis; +/******/ try { +/******/ return this || new Function('return this')(); +/******/ } catch (e) { +/******/ if (typeof window === 'object') return window; +/******/ } +/******/ })(); +/******/ })(); +/******/ +/******/ /* webpack/runtime/hasOwnProperty shorthand */ +/******/ (() => { +/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +/******/ })(); +/******/ +/******/ /* webpack/runtime/node module decorator */ +/******/ (() => { +/******/ __webpack_require__.nmd = (module) => { +/******/ module.paths = []; +/******/ if (!module.children) module.children = []; +/******/ return module; +/******/ }; +/******/ })(); +/******/ +/************************************************************************/ +var __webpack_exports__ = {}; +// This entry need to be wrapped in an IIFE because it need to be in strict mode. +(() => { +"use strict"; + +// EXTERNAL MODULE: worker_threads (ignored) +var worker_threads_ignored_ = __webpack_require__(7882); +var worker_threads_ignored_default = /*#__PURE__*/__webpack_require__.n(worker_threads_ignored_); +// EXTERNAL MODULE: ./node_modules/@tornado/fixed-merkle-tree/lib/index.js +var lib = __webpack_require__(1217); +;// CONCATENATED MODULE: ./node_modules/circomlibjs/node_modules/ffjavascript/build/browser.esm.js +/* global BigInt */ +const hexLen = [ 0, 1, 2, 2, 3, 3, 3, 3, 4 ,4 ,4 ,4 ,4 ,4 ,4 ,4]; + +function fromString(s, radix) { + if ((!radix)||(radix==10)) { + return BigInt(s); + } else if (radix==16) { + if (s.slice(0,2) == "0x") { + return BigInt(s); + } else { + return BigInt("0x"+s); + } + } +} + +const e = fromString; + +function fromArray(a, radix) { + let acc =BigInt(0); + radix = BigInt(radix); + for (let i=0; i> BigInt(n); +} + +const shl = shiftLeft; +const shr = shiftRight; + +function isOdd$5(a) { + return (BigInt(a) & BigInt(1)) == BigInt(1); +} + + +function naf(n) { + let E = BigInt(n); + const res = []; + while (E) { + if (E & BigInt(1)) { + const z = 2 - Number(E % BigInt(4)); + res.push( z ); + E = E - BigInt(z); + } else { + res.push( 0 ); + } + E = E >> BigInt(1); + } + return res; +} + + +function bits(n) { + let E = BigInt(n); + const res = []; + while (E) { + if (E & BigInt(1)) { + res.push(1); + } else { + res.push( 0 ); + } + E = E >> BigInt(1); + } + return res; +} + +function toNumber$1(s) { + if (s>BigInt(Number.MAX_SAFE_INTEGER )) { + throw new Error("Number too big"); + } + return Number(s); +} + +function toArray(s, radix) { + const res = []; + let rem = BigInt(s); + radix = BigInt(radix); + while (rem) { + res.unshift( Number(rem % radix)); + rem = rem / radix; + } + return res; +} + + +function add(a, b) { + return BigInt(a) + BigInt(b); +} + +function sub(a, b) { + return BigInt(a) - BigInt(b); +} + +function neg(a) { + return -BigInt(a); +} + +function mul(a, b) { + return BigInt(a) * BigInt(b); +} + +function square$2(a) { + return BigInt(a) * BigInt(a); +} + +function pow(a, b) { + return BigInt(a) ** BigInt(b); +} + +function exp$1(a, b) { + return BigInt(a) ** BigInt(b); +} + +function abs$1(a) { + return BigInt(a) >= 0 ? BigInt(a) : -BigInt(a); +} + +function div(a, b) { + return BigInt(a) / BigInt(b); +} + +function mod(a, b) { + return BigInt(a) % BigInt(b); +} + +function eq(a, b) { + return BigInt(a) == BigInt(b); +} + +function neq(a, b) { + return BigInt(a) != BigInt(b); +} + +function lt(a, b) { + return BigInt(a) < BigInt(b); +} + +function gt(a, b) { + return BigInt(a) > BigInt(b); +} + +function leq(a, b) { + return BigInt(a) <= BigInt(b); +} + +function geq(a, b) { + return BigInt(a) >= BigInt(b); +} + +function band(a, b) { + return BigInt(a) & BigInt(b); +} + +function bor(a, b) { + return BigInt(a) | BigInt(b); +} + +function bxor(a, b) { + return BigInt(a) ^ BigInt(b); +} + +function land(a, b) { + return BigInt(a) && BigInt(b); +} + +function lor(a, b) { + return BigInt(a) || BigInt(b); +} + +function lnot(a) { + return !BigInt(a); +} + +// Returns a buffer with Little Endian Representation +function toRprLE(buff, o, e, n8) { + const s = "0000000" + e.toString(16); + const v = new Uint32Array(buff.buffer, buff.byteOffset + o, n8/4); + const l = (((s.length-7)*4 - 1) >> 5)+1; // Number of 32bit words; + for (let i=0; i> 5)+1; // Number of 32bit words; + for (let i=0; i a[a.length-i-1] = ch.toString(16).padStart(8,"0") ); + return fromString(a.join(""), 16); +} + +// Pases a buffer with Big Endian Representation +function fromRprBE(buff, o, n8) { + n8 = n8 || buff.byteLength; + o = o || 0; + const v = new DataView(buff.buffer, buff.byteOffset + o, n8); + const a = new Array(n8/4); + for (let i=0; i. + You should have received a copy of the GNU General Public License along with + snarkjs. If not, see . */ +/* + This library does operations on polynomials with coefficients in a field F. -const FunctionBuilderWat = __webpack_require__(2341); -const utils = __webpack_require__(484); + A polynomial P(x) = p0 + p1 * x + p2 * x^2 + ... + pn * x^n is represented + by the array [ p0, p1, p2, ... , pn ]. + */ -class ModuleBuilderWat { +class PolField { + constructor (F) { + this.F = F; - constructor() { - this.functions = []; - this.functionIdxByName = {}; - this.nImportFunctions = 0; - this.nInternalFunctions =0; - this.memory = { - pagesSize: 1, - moduleName: "env", - fieldName: "memory" - }; - this.free = 8; - this.datas = []; - this.modules = {}; - this.exports = []; - this.functionsTable = []; - } + let rem = F.sqrt_t; + let s = F.sqrt_s; - build() { - const src = []; - this._setSignatures(); - src.push(this._buildType()); - src.push(this._buildImport()); - if (this.functionsTable.length>0) { - src.push(this._buildFunctionsTable()); + const five = this.F.add(this.F.add(this.F.two, this.F.two), this.F.one); + + this.w = new Array(s+1); + this.wi = new Array(s+1); + this.w[s] = this.F.pow(five, rem); + this.wi[s] = this.F.inv(this.w[s]); + + let n=s-1; + while (n>=0) { + this.w[n] = this.F.square(this.w[n+1]); + this.wi[n] = this.F.square(this.wi[n+1]); + n--; } - if (this.exports.length > 0) { - src.push(this._buildExports()); - } - if (this.functionsTable.length>0) { - src.push(this._buildElements()); - } - if (this.nInternalFunctions>0) { - src.push(this._buildFunctions()); - } - src.push(this._buildData()); - return [ - "(module", - utils.ident(src), - ")" - ]; - } - addFunction(fnName, comment) { - if (typeof(this.functionIdxByName[fnName]) !== "undefined") - throw new Error(`Function already defined: ${fnName}`); - const idx = this.functions.length; - this.functionIdxByName[fnName] = idx; - - this.functions.push(new FunctionBuilderWat(this, fnName, "internal", comment)); - - this.nInternalFunctions++; - return this.functions[idx]; - } - - addIimportFunction(fnName, moduleName, _fieldName) { - if (typeof(this.functionIdxByName[fnName]) !== "undefined") - throw new Error(`Function already defined: ${fnName}`); - - if ( (this.functions.length>0) - &&(this.functions[this.functions.length-1].type == "internal")) - throw new Error(`Import functions must be declared before internal: ${fnName}`); - - let fieldName = _fieldName || fnName; - - const idx = this.functions.length; - this.functionIdxByName[fnName] = idx; - - this.functions.push(new FunctionBuilderWat(this, fnName, "import", moduleName, fieldName)); - - this.nImportFunctions ++; - return this.functions[idx]; - } - - setMemory(pagesSize, moduleName, fieldName) { - this.memory = { - pagesSize: pagesSize, - moduleName: moduleName || "env", - fieldName: fieldName || "memory" - }; - } - - exportFunction(fnName, _exportName) { - const exportName = _exportName || fnName; - if (typeof(this.functionIdxByName[fnName]) === "undefined") - throw new Error(`Function not defined: ${fnName}`); - const idx = this.functionIdxByName[fnName]; - if (exportName != fnName) { - this.functionIdxByName[exportName] = idx; - } - this.exports.push({ - exportName: exportName, - idx: idx - }); - } - - addFunctionToTable(fnName) { - const idx = this.functionIdxByName[fnName]; - this.functionsTable.push(idx); - } - - addData(offset, bytes) { - this.datas.push({ - offset: offset, - bytes: bytes - }); - } - - alloc(a, b) { - let size; - let bytes; - if ((Array.isArray(a) || ArrayBuffer.isView(a)) && (typeof(b) === "undefined")) { - size = a.length; - bytes = a; - } else { - size = a; - bytes = b; - } - size = (((size-1)>>3) +1)<<3; // Align to 64 bits. - const p = this.free; - this.free += size; - if (bytes) { - this.addData(p, bytes); - } - return p; - } - - allocString(s) { - const encoder = new TextEncoder(); - const uint8array = encoder.encode(s); - return this.alloc([...uint8array, 0]); - } - - _setSignatures() { - this.signatures = []; - const signatureIdxByName = {}; - if (this.functionsTable.length>0) { - const signature = this.functions[this.functionsTable[0]].getSignature(); - const signatureName = this.functions[this.functionsTable[0]].getSignatureName(); - signatureIdxByName[signatureName] = 0; - this.signatures.push(signature); - } - for (let i=0; i this.F.sqrt_s) n = this.s; + for (let i=n; (i>=0) && (!this.roots[i]); i--) { + let r = this.F.one; + const nroots = 1 << i; + const rootsi = new Array(nroots); + for (let j=0; j a.length) { + [b, a] = [a, b]; } - } - - _buildType() { - return this.signatures; - } - - _buildImport() { - const src = []; - src.push(`(import "${this.memory.moduleName}" "${this.memory.fieldName}" (memory ${this.memory.pagesSize}))`); - for (let i=0; i< this.nImportFunctions; i++) { - src.push(`(import "${this.functions[i].moduleName}" "${this.functions[i].fieldName}" (func $${this.functions[i].fnName} (type $${this.functions[i].getSignatureName()})))`); + if ((b.length <= 2) || (b.length < log2$2(a.length))) { + return this.mulNormal(a,b); + } else { + return this.mulFFT(a,b); } - return src; } - _buildFunctionsTable() { - return `(table ${this.functionsTable.length} anyfunc)`; - } - - _buildElements() { - let funcs=""; - for (let i=0; i0) { + const z = new Array(n).fill(this.F.zero); + return z.concat(p); + } else { + if (-n >= p.length) return []; + return p.slice(-n); } - return src; + } - function bytes2string(b) { - let S = "\""; - for (let i=0; i126 || b[i] == 34 || b[i]==92) { - let h=b[i].toString(16); - while (h.length<2) h = "0"+h; - S += "\\" + h; - } else { - S += String.fromCharCode(b[i]); + eval2(p, x) { + let v = this.F.zero; + let ix = this.F.one; + for (let i=0; i> 1), + F.mul( + x, + _eval(p, newX, offset+step , step << 1, n >> 1))); + return res; + } + } + + lagrange(points) { + let roots = [this.F.one]; + for (let i=0; i> 1; + const p1 = this._fft(pall, bits-1, offset, step*2); + const p2 = this._fft(pall, bits-1, offset+step, step*2); + + const out = new Array(n); + + let m= this.F.one; + for (let i=0; i0 && this.F.eq(p[i], this.F.zero) ) i--; + return p.slice(0, i+1); + } + + eq(a, b) { + const pa = this.reduce(a); + const pb = this.reduce(b); + + if (pa.length != pb.length) return false; + for (let i=0; i=0; i--) { + res[i] = this.F.add(this.F.mul(res[i+1], r), p[i+1]); + } + return res; + } + + _next2Power(v) { + v--; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + v++; + return v; + } + + toString(p) { + const ap = this.normalize(p); + let S = ""; + for (let i=ap.length-1; i>=0; i--) { + if (!this.F.eq(p[i], this.F.zero)) { + if (S!="") S += " + "; + S = S + p[i].toString(10); + if (i>0) { + S = S + "x"; + if (i>1) { + S = S + "^" +i; + } } } - S += "\""; - return S; + } + return S; + } + + normalize(p) { + const res = new Array(p.length); + for (let i=0; i + // rec = x^(k-2-scaleV)/ v + // + // res = x^m/v = x^(m + (2*k-2 - scaleV) - (2*k-2 - scaleV)) /v => + // res = rec * x^(m - (2*k-2 - scaleV)) => + // res = rec * x^(m - 2*k + 2 + scaleV) + + const rec = this._reciprocal(this.scaleX(v, scaleV), kbits); + const res = this.scaleX(rec, m - 2*k + 2 + scaleV); + + return res; + } + + div(_u, _v) { + if (_u.length < _v.length) return []; + const kbits = log2$2(_v.length-1)+1; + const k = 1 << kbits; + + const u = this.scaleX(_u, k-_v.length); + const v = this.scaleX(_v, k-_v.length); + + const n = v.length-1; + let m = u.length-1; + + const s = this._reciprocal(v, kbits); + let t; + if (m>2*n) { + t = this.sub(this.scaleX([this.F.one], 2*n), this.mul(s, v)); + } + + let q = []; + let rem = u; + let us, ut; + let finish = false; + + while (!finish) { + us = this.mul(rem, s); + q = this.add(q, this.scaleX(us, -2*n)); + + if ( m > 2*n ) { + ut = this.mul(rem, t); + rem = this.scaleX(ut, -2*n); + m = rem.length-1; + } else { + finish = true; + } + } + + return q; + } + + + // returns the ith nth-root of one + oneRoot(n, i) { + let nbits = log2$2(n-1)+1; + let res = this.F.one; + let r = i; + + if(i>=n) { + throw new Error("Given 'i' should be lower than 'n'"); + } + else if (1<0) { + if (r & 1 == 1) { + res = this.F.mul(res, this.w[nbits]); + } + r = r >> 1; + nbits --; + } + return res; + } + + computeVanishingPolinomial(bits, t) { + const m = 1 << bits; + return this.F.sub(this.F.pow(t, m), this.F.one); + } + + evaluateLagrangePolynomials(bits, t) { + const m= 1 << bits; + const tm = this.F.pow(t, m); + const u= new Array(m).fill(this.F.zero); + this._setRoots(bits); + const omega = this.w[bits]; + + if (this.F.eq(tm, this.F.one)) { + for (let i = 0; i < m; i++) { + if (this.F.eq(this.roots[bits][0],t)) { // i.e., t equals omega^i + u[i] = this.F.one; + return u; + } + } + } + + const z = this.F.sub(tm, this.F.one); + // let l = this.F.mul(z, this.F.pow(this.F.twoinv, m)); + let l = this.F.mul(z, this.F.inv(this.F.e(m))); + for (let i = 0; i < m; i++) { + u[i] = this.F.mul(l, this.F.inv(this.F.sub(t,this.roots[bits][i]))); + l = this.F.mul(l, omega); + } + + return u; + } + + log2(V) { + return log2$2(V); + } +} + +function log2$2( V ) +{ + return( ( ( V & 0xFFFF0000 ) !== 0 ? ( V &= 0xFFFF0000, 16 ) : 0 ) | ( ( V & 0xFF00FF00 ) !== 0 ? ( V &= 0xFF00FF00, 8 ) : 0 ) | ( ( V & 0xF0F0F0F0 ) !== 0 ? ( V &= 0xF0F0F0F0, 4 ) : 0 ) | ( ( V & 0xCCCCCCCC ) !== 0 ? ( V &= 0xCCCCCCCC, 2 ) : 0 ) | ( ( V & 0xAAAAAAAA ) !== 0 ) ); +} + + +function __fft$1(PF, pall, bits, offset, step) { + + const n = 1 << bits; + if (n==1) { + return [ pall[offset] ]; + } else if (n==2) { + return [ + PF.F.add(pall[offset], pall[offset + step]), + PF.F.sub(pall[offset], pall[offset + step])]; + } + + const ndiv2 = n >> 1; + const p1 = __fft$1(PF, pall, bits-1, offset, step*2); + const p2 = __fft$1(PF, pall, bits-1, offset+step, step*2); + + const out = new Array(n); + + for (let i=0; i> 1; + const p1 = __fft2(PF, pall.slice(0, ndiv2), bits-1); + const p2 = __fft2(PF, pall.slice(ndiv2), bits-1); + + const out = new Array(n); + + for (let i=0; i>=1; + } + return res; +} + +function rev(idx, bits) { + return ( + _revTable$1[idx >>> 24] | + (_revTable$1[(idx >>> 16) & 0xFF] << 8) | + (_revTable$1[(idx >>> 8) & 0xFF] << 16) | + (_revTable$1[idx & 0xFF] << 24) + ) >>> (32-bits); +} + +function __bitReverse(p, bits) { + for (let k=0; kk) { + const tmp= p[k]; + p[k] = p[r]; + p[r] = tmp; } } } -module.exports = ModuleBuilderWat; +/* + Copyright 2018 0kims association. + + This file is part of snarkjs. + + snarkjs is a free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or (at your option) + any later version. + + snarkjs is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along with + snarkjs. If not, see . +*/ -/***/ }), -/***/ 7831: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +function mulScalar(F, base, e) { + let res; + + if (isZero$1(e)) return F.zero; + + const n = naf(e); + + if (n[n.length-1] == 1) { + res = base; + } else if (n[n.length-1] == -1) { + res = F.neg(base); + } else { + throw new Error("invlaud NAF"); + } + + for (let i=n.length-2; i>=0; i--) { + + res = F.double(res); + + if (n[i] == 1) { + res = F.add(res, base); + } else if (n[i] == -1) { + res = F.sub(res, base); + } + } + + return res; +} + + +/* +exports.mulScalar = (F, base, e) =>{ + let res = F.zero; + let rem = bigInt(e); + let exp = base; + + while (! rem.eq(bigInt.zero)) { + if (rem.and(bigInt.one).eq(bigInt.one)) { + res = F.add(res, exp); + } + exp = F.double(exp); + rem = rem.shiftRight(1); + } + + return res; +}; +*/ + + +function exp(F, base, e) { + + if (isZero$1(e)) return F.one; + + const n = bits(e); + + if (n.length==0) return F.one; + + let res = base; + + for (let i=n.length-2; i>=0; i--) { + + res = F.square(res); + + if (n[i]) { + res = F.mul(res, base); + } + } + + return res; +} + +// Check here: https://eprint.iacr.org/2012/685.pdf + +function buildSqrt (F) { + if ((F.m % 2) == 1) { + if (eq(mod(F.p, 4), 1 )) { + if (eq(mod(F.p, 8), 1 )) { + if (eq(mod(F.p, 16), 1 )) { + // alg7_muller(F); + alg5_tonelliShanks(F); + } else if (eq(mod(F.p, 16), 9 )) { + alg4_kong(F); + } else { + throw new Error("Field withot sqrt"); + } + } else if (eq(mod(F.p, 8), 5 )) { + alg3_atkin(F); + } else { + throw new Error("Field withot sqrt"); + } + } else if (eq(mod(F.p, 4), 3 )) { + alg2_shanks(F); + } + } else { + const pm2mod4 = mod(pow(F.p, F.m/2), 4); + if (pm2mod4 == 1) { + alg10_adj(F); + } else if (pm2mod4 == 3) { + alg9_adj(F); + } else { + alg8_complex(F); + } + + } +} + + +function alg5_tonelliShanks(F) { + F.sqrt_q = pow(F.p, F.m); + + F.sqrt_s = 0; + F.sqrt_t = sub(F.sqrt_q, 1); + + while (!isOdd$5(F.sqrt_t)) { + F.sqrt_s = F.sqrt_s + 1; + F.sqrt_t = div(F.sqrt_t, 2); + } + + let c0 = F.one; + + while (F.eq(c0, F.one)) { + const c = F.random(); + F.sqrt_z = F.pow(c, F.sqrt_t); + c0 = F.pow(F.sqrt_z, 2 ** (F.sqrt_s-1) ); + } + + F.sqrt_tm1d2 = div(sub(F.sqrt_t, 1),2); + + F.sqrt = function(a) { + const F=this; + if (F.isZero(a)) return F.zero; + let w = F.pow(a, F.sqrt_tm1d2); + const a0 = F.pow( F.mul(F.square(w), a), 2 ** (F.sqrt_s-1) ); + if (F.eq(a0, F.negone)) return null; + + let v = F.sqrt_s; + let x = F.mul(a, w); + let b = F.mul(x, w); + let z = F.sqrt_z; + while (!F.eq(b, F.one)) { + let b2k = F.square(b); + let k=1; + while (!F.eq(b2k, F.one)) { + b2k = F.square(b2k); + k++; + } + + w = z; + for (let i=0; i>> 0; + st[d] = (st[d] ^ st[a]) >>> 0; + st[d] = ((st[d] << 16) | ((st[d]>>>16) & 0xFFFF)) >>> 0; + + st[c] = (st[c] + st[d]) >>> 0; + st[b] = (st[b] ^ st[c]) >>> 0; + st[b] = ((st[b] << 12) | ((st[b]>>>20) & 0xFFF)) >>> 0; + + st[a] = (st[a] + st[b]) >>> 0; + st[d] = (st[d] ^ st[a]) >>> 0; + st[d] = ((st[d] << 8) | ((st[d]>>>24) & 0xFF)) >>> 0; + + st[c] = (st[c] + st[d]) >>> 0; + st[b] = (st[b] ^ st[c]) >>> 0; + st[b] = ((st[b] << 7) | ((st[b]>>>25) & 0x7F)) >>> 0; +} + +function doubleRound(st) { + quarterRound(st, 0, 4, 8,12); + quarterRound(st, 1, 5, 9,13); + quarterRound(st, 2, 6,10,14); + quarterRound(st, 3, 7,11,15); + + quarterRound(st, 0, 5,10,15); + quarterRound(st, 1, 6,11,12); + quarterRound(st, 2, 7, 8,13); + quarterRound(st, 3, 4, 9,14); +} + +class ChaCha { + + constructor(seed) { + seed = seed || [0,0,0,0,0,0,0,0]; + this.state = [ + 0x61707865, + 0x3320646E, + 0x79622D32, + 0x6B206574, + seed[0], + seed[1], + seed[2], + seed[3], + seed[4], + seed[5], + seed[6], + seed[7], + 0, + 0, + 0, + 0 + ]; + this.idx = 16; + this.buff = new Array(16); + } + + nextU32() { + if (this.idx == 16) this.update(); + return this.buff[this.idx++]; + } + + nextU64() { + return add(mul(this.nextU32(), 0x100000000), this.nextU32()); + } + + nextBool() { + return (this.nextU32() & 1) == 1; + } + + update() { + // Copy the state + for (let i=0; i<16; i++) this.buff[i] = this.state[i]; + + // Apply the rounds + for (let i=0; i<10; i++) doubleRound(this.buff); + + // Add to the initial + for (let i=0; i<16; i++) this.buff[i] = (this.buff[i] + this.state[i]) >>> 0; + + this.idx = 0; + + this.state[12] = (this.state[12] + 1) >>> 0; + if (this.state[12] != 0) return; + this.state[13] = (this.state[13] + 1) >>> 0; + if (this.state[13] != 0) return; + this.state[14] = (this.state[14] + 1) >>> 0; + if (this.state[14] != 0) return; + this.state[15] = (this.state[15] + 1) >>> 0; + } +} + +function getRandomBytes(n) { + let array = new Uint8Array(n); + { // Browser + if (typeof globalThis.crypto !== "undefined") { // Supported + globalThis.crypto.getRandomValues(array); + } else { // fallback + for (let i=0; i>>0; + } + } + } + return array; +} + +function getRandomSeed() { + const arr = getRandomBytes(32); + const arrV = new Uint32Array(arr.buffer); + const seed = []; + for (let i=0; i<8; i++) { + seed.push(arrV[i]); + } + return seed; +} + +let threadRng = null; + +function getThreadRng() { + if (threadRng) return threadRng; + threadRng = new ChaCha(getRandomSeed()); + return threadRng; +} + +/* + Copyright 2018 0kims association. + + This file is part of snarkjs. + + snarkjs is a free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or (at your option) + any later version. + + snarkjs is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along with + snarkjs. If not, see . +*/ + +/* + This library does operations on polynomials with coefficients in a field F. + + A polynomial P(x) = p0 + p1 * x + p2 * x^2 + ... + pn * x^n is represented + by the array [ p0, p1, p2, ... , pn ]. + */ + +class FFT { + constructor (G, F, opMulGF) { + this.F = F; + this.G = G; + this.opMulGF = opMulGF; + + let rem = F.sqrt_t || F.t; + let s = F.sqrt_s || F.s; + + let nqr = F.one; + while (F.eq(F.pow(nqr, F.half), F.one)) nqr = F.add(nqr, F.one); + + this.w = new Array(s+1); + this.wi = new Array(s+1); + this.w[s] = this.F.pow(nqr, rem); + this.wi[s] = this.F.inv(this.w[s]); + + let n=s-1; + while (n>=0) { + this.w[n] = this.F.square(this.w[n+1]); + this.wi[n] = this.F.square(this.wi[n+1]); + n--; + } + + + this.roots = []; + /* + for (let i=0; i<16; i++) { + let r = this.F.one; + n = 1 << i; + const rootsi = new Array(n); + for (let j=0; j=0) && (!this.roots[i]); i--) { + let r = this.F.one; + const nroots = 1 << i; + const rootsi = new Array(nroots); + for (let j=0; j> 1; + const p1 = __fft(PF, pall, bits-1, offset, step*2); + const p2 = __fft(PF, pall, bits-1, offset+step, step*2); + + const out = new Array(n); + + for (let i=0; i> this.one; + this.bitLength = bitLength$6(this.p); + this.mask = (this.one << BigInt(this.bitLength)) - this.one; + + this.n64 = Math.floor((this.bitLength - 1) / 64)+1; + this.n32 = this.n64*2; + this.n8 = this.n64*8; + this.R = this.e(this.one << BigInt(this.n64*64)); + this.Ri = this.inv(this.R); + + const e = this.negone >> this.one; + this.nqr = this.two; + let r = this.pow(this.nqr, e); + while (!this.eq(r, this.negone)) { + this.nqr = this.nqr + this.one; + r = this.pow(this.nqr, e); + } + + + this.s = 0; + this.t = this.negone; + + while ((this.t & this.one) == this.zero) { + this.s = this.s + 1; + this.t = this.t >> this.one; + } + + this.nqr_to_t = this.pow(this.nqr, this.t); + + buildSqrt(this); + + this.FFT = new FFT(this, this, this.mul.bind(this)); + + this.fft = this.FFT.fft.bind(this.FFT); + this.ifft = this.FFT.ifft.bind(this.FFT); + this.w = this.FFT.w; + this.wi = this.FFT.wi; + + this.shift = this.square(this.nqr); + this.k = this.exp(this.nqr, 2**this.s); + } + + e(a,b) { + let res; + if (!b) { + res = BigInt(a); + } else if (b==16) { + res = BigInt("0x"+a); + } + if (res < 0) { + let nres = -res; + if (nres >= this.p) nres = nres % this.p; + return this.p - nres; + } else { + return (res>= this.p) ? res%this.p : res; + } + + } + + add(a, b) { + const res = a + b; + return res >= this.p ? res-this.p : res; + } + + sub(a, b) { + return (a >= b) ? a-b : this.p-b+a; + } + + neg(a) { + return a ? this.p-a : a; + } + + mul(a, b) { + return (a*b)%this.p; + } + + mulScalar(base, s) { + return (base * this.e(s)) % this.p; + } + + square(a) { + return (a*a) % this.p; + } + + eq(a, b) { + return a==b; + } + + neq(a, b) { + return a!=b; + } + + lt(a, b) { + const aa = (a > this.half) ? a - this.p : a; + const bb = (b > this.half) ? b - this.p : b; + return aa < bb; + } + + gt(a, b) { + const aa = (a > this.half) ? a - this.p : a; + const bb = (b > this.half) ? b - this.p : b; + return aa > bb; + } + + leq(a, b) { + const aa = (a > this.half) ? a - this.p : a; + const bb = (b > this.half) ? b - this.p : b; + return aa <= bb; + } + + geq(a, b) { + const aa = (a > this.half) ? a - this.p : a; + const bb = (b > this.half) ? b - this.p : b; + return aa >= bb; + } + + div(a, b) { + return this.mul(a, this.inv(b)); + } + + idiv(a, b) { + if (!b) throw new Error("Division by zero"); + return a / b; + } + + inv(a) { + if (!a) throw new Error("Division by zero"); + + let t = this.zero; + let r = this.p; + let newt = this.one; + let newr = a % this.p; + while (newr) { + let q = r/newr; + [t, newt] = [newt, t-q*newt]; + [r, newr] = [newr, r-q*newr]; + } + if (t= this.p ? res-this.p : res; + } + + bor(a, b) { + const res = ((a | b) & this.mask); + return res >= this.p ? res-this.p : res; + } + + bxor(a, b) { + const res = ((a ^ b) & this.mask); + return res >= this.p ? res-this.p : res; + } + + bnot(a) { + const res = a ^ this.mask; + return res >= this.p ? res-this.p : res; + } + + shl(a, b) { + if (Number(b) < this.bitLength) { + const res = (a << b) & this.mask; + return res >= this.p ? res-this.p : res; + } else { + const nb = this.p - b; + if (Number(nb) < this.bitLength) { + return a >> nb; + } else { + return this.zero; + } + } + } + + shr(a, b) { + if (Number(b) < this.bitLength) { + return a >> b; + } else { + const nb = this.p - b; + if (Number(nb) < this.bitLength) { + const res = (a << nb) & this.mask; + return res >= this.p ? res-this.p : res; + } else { + return 0; + } + } + } + + land(a, b) { + return (a && b) ? this.one : this.zero; + } + + lor(a, b) { + return (a || b) ? this.one : this.zero; + } + + lnot(a) { + return (a) ? this.zero : this.one; + } + + sqrt_old(n) { + + if (n == this.zero) return this.zero; + + // Test that have solution + const res = this.pow(n, this.negone >> this.one); + if ( res != this.one ) return null; + + let m = this.s; + let c = this.nqr_to_t; + let t = this.pow(n, this.t); + let r = this.pow(n, this.add(this.t, this.one) >> this.one ); + + while ( t != this.one ) { + let sq = this.square(t); + let i = 1; + while (sq != this.one ) { + i++; + sq = this.square(sq); + } + + // b = c ^ m-i-1 + let b = c; + for (let j=0; j< m-i-1; j ++) b = this.square(b); + + m = i; + c = this.square(b); + t = this.mul(t, c); + r = this.mul(r, b); + } + + if (r > (this.p >> this.one)) { + r = this.neg(r); + } + + return r; + } + + normalize(a, b) { + a = BigInt(a,b); + if (a < 0) { + let na = -a; + if (na >= this.p) na = na % this.p; + return this.p - na; + } else { + return (a>= this.p) ? a%this.p : a; + } + } + + random() { + const nBytes = (this.bitLength*2 / 8); + let res =this.zero; + for (let i=0; i this.half)&&(base == 10)) { + const v = this.p-a; + vs = "-"+v.toString(base); + } else { + vs = a.toString(base); + } + return vs; + } + + isZero(a) { + return a == this.zero; + } + + fromRng(rng) { + let v; + do { + v=this.zero; + for (let i=0; i= this.p); + v = (v * this.Ri) % this.p; // Convert from montgomery + return v; + } + + fft(a) { + return this.FFT.fft(a); + } + + ifft(a) { + return this.FFT.ifft(a); + } + + // Returns a buffer with Little Endian Representation + toRprLE(buff, o, e) { + toRprLE(buff, o, e, this.n64*8); + } + + // Returns a buffer with Big Endian Representation + toRprBE(buff, o, e) { + toRprBE(buff, o, e, this.n64*8); + } + + // Returns a buffer with Big Endian Montgomery Representation + toRprBEM(buff, o, e) { + return this.toRprBE(buff, o, this.mul(this.R, e)); + } + + toRprLEM(buff, o, e) { + return this.toRprLE(buff, o, this.mul(this.R, e)); + } + + + // Pases a buffer with Little Endian Representation + fromRprLE(buff, o) { + return fromRprLE(buff, o, this.n8); + } + + // Pases a buffer with Big Endian Representation + fromRprBE(buff, o) { + return fromRprBE(buff, o, this.n8); + } + + fromRprLEM(buff, o) { + return this.mul(this.fromRprLE(buff, o), this.Ri); + } + + fromRprBEM(buff, o) { + return this.mul(this.fromRprBE(buff, o), this.Ri); + } + + toObject(a) { + return a; + } +} + +/* + Copyright 2018 0kims association. + + This file is part of snarkjs. + + snarkjs is a free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or (at your option) + any later version. + + snarkjs is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along with + snarkjs. If not, see . +*/ + + +class F2Field { + constructor(F, nonResidue) { + this.type="F2"; + this.F = F; + this.zero = [this.F.zero, this.F.zero]; + this.one = [this.F.one, this.F.zero]; + this.negone = this.neg(this.one); + this.nonResidue = nonResidue; + this.m = F.m*2; + this.p = F.p; + this.n64 = F.n64*2; + this.n32 = this.n64*2; + this.n8 = this.n64*8; + + buildSqrt(this); + } + + _mulByNonResidue(a) { + return this.F.mul(this.nonResidue, a); + } + + copy(a) { + return [this.F.copy(a[0]), this.F.copy(a[1])]; + } + + add(a, b) { + return [ + this.F.add(a[0], b[0]), + this.F.add(a[1], b[1]) + ]; + } + + double(a) { + return this.add(a,a); + } + + sub(a, b) { + return [ + this.F.sub(a[0], b[0]), + this.F.sub(a[1], b[1]) + ]; + } + + neg(a) { + return this.sub(this.zero, a); + } + + conjugate(a) { + return [ + a[0], + this.F.neg(a[1]) + ]; + } + + mul(a, b) { + const aA = this.F.mul(a[0] , b[0]); + const bB = this.F.mul(a[1] , b[1]); + + return [ + this.F.add( aA , this._mulByNonResidue(bB)), + this.F.sub( + this.F.mul( + this.F.add(a[0], a[1]), + this.F.add(b[0], b[1])), + this.F.add(aA, bB))]; + } + + inv(a) { + const t0 = this.F.square(a[0]); + const t1 = this.F.square(a[1]); + const t2 = this.F.sub(t0, this._mulByNonResidue(t1)); + const t3 = this.F.inv(t2); + return [ + this.F.mul(a[0], t3), + this.F.neg(this.F.mul( a[1], t3)) ]; + } + + div(a, b) { + return this.mul(a, this.inv(b)); + } + + square(a) { + const ab = this.F.mul(a[0] , a[1]); + + /* + [ + (a + b) * (a + non_residue * b) - ab - non_residue * ab, + ab + ab + ]; + */ + + return [ + this.F.sub( + this.F.mul( + this.F.add(a[0], a[1]) , + this.F.add( + a[0] , + this._mulByNonResidue(a[1]))), + this.F.add( + ab, + this._mulByNonResidue(ab))), + this.F.add(ab, ab) + ]; + } + + isZero(a) { + return this.F.isZero(a[0]) && this.F.isZero(a[1]); + } + + eq(a, b) { + return this.F.eq(a[0], b[0]) && this.F.eq(a[1], b[1]); + } + + mulScalar(base, e) { + return mulScalar(this, base, e); + } + + pow(base, e) { + return exp(this, base, e); + } + + exp(base, e) { + return exp(this, base, e); + } + + toString(a) { + return `[ ${this.F.toString(a[0])} , ${this.F.toString(a[1])} ]`; + } + + fromRng(rng) { + const c0 = this.F.fromRng(rng); + const c1 = this.F.fromRng(rng); + return [c0, c1]; + } + + gt(a, b) { + if (this.F.gt(a[0], b[0])) return true; + if (this.F.gt(b[0], a[0])) return false; + if (this.F.gt(a[1], b[1])) return true; + return false; + } + + geq(a, b) { + return this.gt(a, b) || this.eq(a, b); + } + + lt(a, b) { + return !this.geq(a,b); + } + + leq(a, b) { + return !this.gt(a,b); + } + + neq(a, b) { + return !this.eq(a,b); + } + + random() { + return [this.F.random(), this.F.random()]; + } + + + toRprLE(buff, o, e) { + this.F.toRprLE(buff, o, e[0]); + this.F.toRprLE(buff, o+this.F.n8, e[1]); + } + + toRprBE(buff, o, e) { + this.F.toRprBE(buff, o, e[1]); + this.F.toRprBE(buff, o+this.F.n8, e[0]); + } + + toRprLEM(buff, o, e) { + this.F.toRprLEM(buff, o, e[0]); + this.F.toRprLEM(buff, o+this.F.n8, e[1]); + } + + + toRprBEM(buff, o, e) { + this.F.toRprBEM(buff, o, e[1]); + this.F.toRprBEM(buff, o+this.F.n8, e[0]); + } + + fromRprLE(buff, o) { + o = o || 0; + const c0 = this.F.fromRprLE(buff, o); + const c1 = this.F.fromRprLE(buff, o+this.F.n8); + return [c0, c1]; + } + + fromRprBE(buff, o) { + o = o || 0; + const c1 = this.F.fromRprBE(buff, o); + const c0 = this.F.fromRprBE(buff, o+this.F.n8); + return [c0, c1]; + } + + fromRprLEM(buff, o) { + o = o || 0; + const c0 = this.F.fromRprLEM(buff, o); + const c1 = this.F.fromRprLEM(buff, o+this.F.n8); + return [c0, c1]; + } + + fromRprBEM(buff, o) { + o = o || 0; + const c1 = this.F.fromRprBEM(buff, o); + const c0 = this.F.fromRprBEM(buff, o+this.F.n8); + return [c0, c1]; + } + + toObject(a) { + return a; + } + +} + +/* + Copyright 2018 0kims association. + + This file is part of snarkjs. + + snarkjs is a free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or (at your option) + any later version. + + snarkjs is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along with + snarkjs. If not, see . +*/ + + +class F3Field { + constructor(F, nonResidue) { + this.type="F3"; + this.F = F; + this.zero = [this.F.zero, this.F.zero, this.F.zero]; + this.one = [this.F.one, this.F.zero, this.F.zero]; + this.negone = this.neg(this.one); + this.nonResidue = nonResidue; + this.m = F.m*3; + this.p = F.p; + this.n64 = F.n64*3; + this.n32 = this.n64*2; + this.n8 = this.n64*8; + } + + _mulByNonResidue(a) { + return this.F.mul(this.nonResidue, a); + } + + copy(a) { + return [this.F.copy(a[0]), this.F.copy(a[1]), this.F.copy(a[2])]; + } + + add(a, b) { + return [ + this.F.add(a[0], b[0]), + this.F.add(a[1], b[1]), + this.F.add(a[2], b[2]) + ]; + } + + double(a) { + return this.add(a,a); + } + + sub(a, b) { + return [ + this.F.sub(a[0], b[0]), + this.F.sub(a[1], b[1]), + this.F.sub(a[2], b[2]) + ]; + } + + neg(a) { + return this.sub(this.zero, a); + } + + mul(a, b) { + + const aA = this.F.mul(a[0] , b[0]); + const bB = this.F.mul(a[1] , b[1]); + const cC = this.F.mul(a[2] , b[2]); + + return [ + this.F.add( + aA, + this._mulByNonResidue( + this.F.sub( + this.F.mul( + this.F.add(a[1], a[2]), + this.F.add(b[1], b[2])), + this.F.add(bB, cC)))), // aA + non_residue*((b+c)*(B+C)-bB-cC), + + this.F.add( + this.F.sub( + this.F.mul( + this.F.add(a[0], a[1]), + this.F.add(b[0], b[1])), + this.F.add(aA, bB)), + this._mulByNonResidue( cC)), // (a+b)*(A+B)-aA-bB+non_residue*cC + + this.F.add( + this.F.sub( + this.F.mul( + this.F.add(a[0], a[2]), + this.F.add(b[0], b[2])), + this.F.add(aA, cC)), + bB)]; // (a+c)*(A+C)-aA+bB-cC) + } + + inv(a) { + const t0 = this.F.square(a[0]); // t0 = a^2 ; + const t1 = this.F.square(a[1]); // t1 = b^2 ; + const t2 = this.F.square(a[2]); // t2 = c^2; + const t3 = this.F.mul(a[0],a[1]); // t3 = ab + const t4 = this.F.mul(a[0],a[2]); // t4 = ac + const t5 = this.F.mul(a[1],a[2]); // t5 = bc; + // c0 = t0 - non_residue * t5; + const c0 = this.F.sub(t0, this._mulByNonResidue(t5)); + // c1 = non_residue * t2 - t3; + const c1 = this.F.sub(this._mulByNonResidue(t2), t3); + const c2 = this.F.sub(t1, t4); // c2 = t1-t4 + + // t6 = (a * c0 + non_residue * (c * c1 + b * c2)).inv(); + const t6 = + this.F.inv( + this.F.add( + this.F.mul(a[0], c0), + this._mulByNonResidue( + this.F.add( + this.F.mul(a[2], c1), + this.F.mul(a[1], c2))))); + + return [ + this.F.mul(t6, c0), // t6*c0 + this.F.mul(t6, c1), // t6*c1 + this.F.mul(t6, c2)]; // t6*c2 + } + + div(a, b) { + return this.mul(a, this.inv(b)); + } + + square(a) { + const s0 = this.F.square(a[0]); // s0 = a^2 + const ab = this.F.mul(a[0], a[1]); // ab = a*b + const s1 = this.F.add(ab, ab); // s1 = 2ab; + const s2 = this.F.square( + this.F.add(this.F.sub(a[0],a[1]), a[2])); // s2 = (a - b + c)^2; + const bc = this.F.mul(a[1],a[2]); // bc = b*c + const s3 = this.F.add(bc, bc); // s3 = 2*bc + const s4 = this.F.square(a[2]); // s4 = c^2 + + + return [ + this.F.add( + s0, + this._mulByNonResidue(s3)), // s0 + non_residue * s3, + this.F.add( + s1, + this._mulByNonResidue(s4)), // s1 + non_residue * s4, + this.F.sub( + this.F.add( this.F.add(s1, s2) , s3 ), + this.F.add(s0, s4))]; // s1 + s2 + s3 - s0 - s4 + } + + isZero(a) { + return this.F.isZero(a[0]) && this.F.isZero(a[1]) && this.F.isZero(a[2]); + } + + eq(a, b) { + return this.F.eq(a[0], b[0]) && this.F.eq(a[1], b[1]) && this.F.eq(a[2], b[2]); + } + + affine(a) { + return [this.F.affine(a[0]), this.F.affine(a[1]), this.F.affine(a[2])]; + } + + mulScalar(base, e) { + return mulScalar(this, base, e); + } + + pow(base, e) { + return exp(this, base, e); + } + + exp(base, e) { + return exp(this, base, e); + } + + toString(a) { + return `[ ${this.F.toString(a[0])} , ${this.F.toString(a[1])}, ${this.F.toString(a[2])} ]`; + } + + fromRng(rng) { + const c0 = this.F.fromRng(rng); + const c1 = this.F.fromRng(rng); + const c2 = this.F.fromRng(rng); + return [c0, c1, c2]; + } + + gt(a, b) { + if (this.F.gt(a[0], b[0])) return true; + if (this.F.gt(b[0], a[0])) return false; + if (this.F.gt(a[1], b[1])) return true; + if (this.F.gt(b[1], a[1])) return false; + if (this.F.gt(a[2], b[2])) return true; + return false; + } + + + geq(a, b) { + return this.gt(a, b) || this.eq(a, b); + } + + lt(a, b) { + return !this.geq(a,b); + } + + leq(a, b) { + return !this.gt(a,b); + } + + neq(a, b) { + return !this.eq(a,b); + } + + random() { + return [this.F.random(), this.F.random(), this.F.random()]; + } + + + toRprLE(buff, o, e) { + this.F.toRprLE(buff, o, e[0]); + this.F.toRprLE(buff, o+this.F.n8, e[1]); + this.F.toRprLE(buff, o+this.F.n8*2, e[2]); + } + + toRprBE(buff, o, e) { + this.F.toRprBE(buff, o, e[2]); + this.F.toRprBE(buff, o+this.F.n8, e[1]); + this.F.toRprBE(buff, o+this.F.n8*2, e[0]); + } + + toRprLEM(buff, o, e) { + this.F.toRprLEM(buff, o, e[0]); + this.F.toRprLEM(buff, o+this.F.n8, e[1]); + this.F.toRprLEM(buff, o+this.F.n8*2, e[2]); + } + + + toRprBEM(buff, o, e) { + this.F.toRprBEM(buff, o, e[2]); + this.F.toRprBEM(buff, o+this.F.n8, e[1]); + this.F.toRprBEM(buff, o+this.F.n8*2, e[0]); + } + + fromRprLE(buff, o) { + o = o || 0; + const c0 = this.F.fromRprLE(buff, o); + const c1 = this.F.fromRprLE(buff, o+this.n8); + const c2 = this.F.fromRprLE(buff, o+this.n8*2); + return [c0, c1, c2]; + } + + fromRprBE(buff, o) { + o = o || 0; + const c2 = this.F.fromRprBE(buff, o); + const c1 = this.F.fromRprBE(buff, o+this.n8); + const c0 = this.F.fromRprBE(buff, o+this.n8*2); + return [c0, c1, c2]; + } + + fromRprLEM(buff, o) { + o = o || 0; + const c0 = this.F.fromRprLEM(buff, o); + const c1 = this.F.fromRprLEM(buff, o+this.n8); + const c2 = this.F.fromRprLEM(buff, o+this.n8*2); + return [c0, c1, c2]; + } + + fromRprBEM(buff, o) { + o = o || 0; + const c2 = this.F.fromRprBEM(buff, o); + const c1 = this.F.fromRprBEM(buff, o+this.n8); + const c0 = this.F.fromRprBEM(buff, o+this.n8*2); + return [c0, c1, c2]; + } + + toObject(a) { + return a; + } +} + +/* + Copyright 2018 0kims association. + + This file is part of snarkjs. + + snarkjs is a free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or (at your option) + any later version. + + snarkjs is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along with + snarkjs. If not, see . +*/ + + + +function isGreatest(F, a) { + if (Array.isArray(a)) { + for (let i=a.length-1; i>=0; i--) { + if (!F.F.isZero(a[i])) { + return isGreatest(F.F, a[i]); + } + } + return 0; + } else { + const na = F.neg(a); + return gt(a, na); + } +} + + +class EC { + + constructor(F, g) { + this.F = F; + this.g = g; + if (this.g.length == 2) this.g[2] = this.F.one; + this.zero = [this.F.zero, this.F.one, this.F.zero]; + } + + add(p1, p2) { + + const F = this.F; + + if (this.eq(p1, this.zero)) return p2; + if (this.eq(p2, this.zero)) return p1; + + const res = new Array(3); + + const Z1Z1 = F.square( p1[2] ); + const Z2Z2 = F.square( p2[2] ); + + const U1 = F.mul( p1[0] , Z2Z2 ); // U1 = X1 * Z2Z2 + const U2 = F.mul( p2[0] , Z1Z1 ); // U2 = X2 * Z1Z1 + + const Z1_cubed = F.mul( p1[2] , Z1Z1); + const Z2_cubed = F.mul( p2[2] , Z2Z2); + + const S1 = F.mul( p1[1] , Z2_cubed); // S1 = Y1 * Z2 * Z2Z2 + const S2 = F.mul( p2[1] , Z1_cubed); // S2 = Y2 * Z1 * Z1Z1 + + if (F.eq(U1,U2) && F.eq(S1,S2)) { + return this.double(p1); + } + + const H = F.sub( U2 , U1 ); // H = U2-U1 + + const S2_minus_S1 = F.sub( S2 , S1 ); + + const I = F.square( F.add(H,H) ); // I = (2 * H)^2 + const J = F.mul( H , I ); // J = H * I + + const r = F.add( S2_minus_S1 , S2_minus_S1 ); // r = 2 * (S2-S1) + const V = F.mul( U1 , I ); // V = U1 * I + + res[0] = + F.sub( + F.sub( F.square(r) , J ), + F.add( V , V )); // X3 = r^2 - J - 2 * V + + const S1_J = F.mul( S1 , J ); + + res[1] = + F.sub( + F.mul( r , F.sub(V,res[0])), + F.add( S1_J,S1_J )); // Y3 = r * (V-X3)-2 S1 J + + res[2] = + F.mul( + H, + F.sub( + F.square( F.add(p1[2],p2[2]) ), + F.add( Z1Z1 , Z2Z2 ))); // Z3 = ((Z1+Z2)^2-Z1Z1-Z2Z2) * H + + return res; + } + + neg(p) { + return [p[0], this.F.neg(p[1]), p[2]]; + } + + sub(a, b) { + return this.add(a, this.neg(b)); + } + + double(p) { + const F = this.F; + + const res = new Array(3); + + if (this.eq(p, this.zero)) return p; + + const A = F.square( p[0] ); // A = X1^2 + const B = F.square( p[1] ); // B = Y1^2 + const C = F.square( B ); // C = B^2 + + let D = + F.sub( + F.square( F.add(p[0] , B )), + F.add( A , C)); + D = F.add(D,D); // D = 2 * ((X1 + B)^2 - A - C) + + const E = F.add( F.add(A,A), A); // E = 3 * A + const FF =F.square( E ); // F = E^2 + + res[0] = F.sub( FF , F.add(D,D) ); // X3 = F - 2 D + + let eightC = F.add( C , C ); + eightC = F.add( eightC , eightC ); + eightC = F.add( eightC , eightC ); + + res[1] = + F.sub( + F.mul( + E, + F.sub( D, res[0] )), + eightC); // Y3 = E * (D - X3) - 8 * C + + const Y1Z1 = F.mul( p[1] , p[2] ); + res[2] = F.add( Y1Z1 , Y1Z1 ); // Z3 = 2 * Y1 * Z1 + + return res; + } + + timesScalar(base, e) { + return mulScalar(this, base, e); + } + + mulScalar(base, e) { + return mulScalar(this, base, e); + } + + affine(p) { + const F = this.F; + if (this.isZero(p)) { + return this.zero; + } else if (F.eq(p[2], F.one)) { + return p; + } else { + const Z_inv = F.inv(p[2]); + const Z2_inv = F.square(Z_inv); + const Z3_inv = F.mul(Z2_inv, Z_inv); + + const res = new Array(3); + res[0] = F.mul(p[0],Z2_inv); + res[1] = F.mul(p[1],Z3_inv); + res[2] = F.one; + + return res; + } + } + + multiAffine(arr) { + const keys = Object.keys(arr); + const F = this.F; + const accMul = new Array(keys.length+1); + accMul[0] = F.one; + for (let i = 0; i< keys.length; i++) { + if (F.eq(arr[keys[i]][2], F.zero)) { + accMul[i+1] = accMul[i]; + } else { + accMul[i+1] = F.mul(accMul[i], arr[keys[i]][2]); + } + } + + accMul[keys.length] = F.inv(accMul[keys.length]); + + for (let i = keys.length-1; i>=0; i--) { + if (F.eq(arr[keys[i]][2], F.zero)) { + accMul[i] = accMul[i+1]; + arr[keys[i]] = this.zero; + } else { + const Z_inv = F.mul(accMul[i], accMul[i+1]); + accMul[i] = F.mul(arr[keys[i]][2], accMul[i+1]); + + const Z2_inv = F.square(Z_inv); + const Z3_inv = F.mul(Z2_inv, Z_inv); + + arr[keys[i]][0] = F.mul(arr[keys[i]][0],Z2_inv); + arr[keys[i]][1] = F.mul(arr[keys[i]][1],Z3_inv); + arr[keys[i]][2] = F.one; + } + } + + } + + eq(p1, p2) { + const F = this.F; + + if (this.F.eq(p1[2], this.F.zero)) return this.F.eq(p2[2], this.F.zero); + if (this.F.eq(p2[2], this.F.zero)) return false; + + const Z1Z1 = F.square( p1[2] ); + const Z2Z2 = F.square( p2[2] ); + + const U1 = F.mul( p1[0] , Z2Z2 ); + const U2 = F.mul( p2[0] , Z1Z1 ); + + const Z1_cubed = F.mul( p1[2] , Z1Z1); + const Z2_cubed = F.mul( p2[2] , Z2Z2); + + const S1 = F.mul( p1[1] , Z2_cubed); + const S2 = F.mul( p2[1] , Z1_cubed); + + return (F.eq(U1,U2) && F.eq(S1,S2)); + } + + isZero(p) { + return this.F.isZero(p[2]); + } + + toString(p) { + const cp = this.affine(p); + return `[ ${this.F.toString(cp[0])} , ${this.F.toString(cp[1])} ]`; + } + + fromRng(rng) { + const F = this.F; + let P = []; + let greatest; + do { + P[0] = F.fromRng(rng); + greatest = rng.nextBool(); + const x3b = F.add(F.mul(F.square(P[0]), P[0]), this.b); + P[1] = F.sqrt(x3b); + } while ((P[1] == null)||(F.isZero[P])); + + const s = isGreatest(F, P[1]); + if (greatest ^ s) P[1] = F.neg(P[1]); + P[2] = F.one; + + if (this.cofactor) { + P = this.mulScalar(P, this.cofactor); + } + + P = this.affine(P); + + return P; + + } + + toRprLE(buff, o, p) { + p = this.affine(p); + if (this.isZero(p)) { + const BuffV = new Uint8Array(buff, o, this.F.n8*2); + BuffV.fill(0); + return; + } + this.F.toRprLE(buff, o, p[0]); + this.F.toRprLE(buff, o+this.F.n8, p[1]); + } + + toRprBE(buff, o, p) { + p = this.affine(p); + if (this.isZero(p)) { + const BuffV = new Uint8Array(buff, o, this.F.n8*2); + BuffV.fill(0); + return; + } + this.F.toRprBE(buff, o, p[0]); + this.F.toRprBE(buff, o+this.F.n8, p[1]); + } + + toRprLEM(buff, o, p) { + p = this.affine(p); + if (this.isZero(p)) { + const BuffV = new Uint8Array(buff, o, this.F.n8*2); + BuffV.fill(0); + return; + } + this.F.toRprLEM(buff, o, p[0]); + this.F.toRprLEM(buff, o+this.F.n8, p[1]); + } + + toRprLEJM(buff, o, p) { + p = this.affine(p); + if (this.isZero(p)) { + const BuffV = new Uint8Array(buff, o, this.F.n8*2); + BuffV.fill(0); + return; + } + this.F.toRprLEM(buff, o, p[0]); + this.F.toRprLEM(buff, o+this.F.n8, p[1]); + this.F.toRprLEM(buff, o+2*this.F.n8, p[2]); + } + + + toRprBEM(buff, o, p) { + p = this.affine(p); + if (this.isZero(p)) { + const BuffV = new Uint8Array(buff, o, this.F.n8*2); + BuffV.fill(0); + return; + } + this.F.toRprBEM(buff, o, p[0]); + this.F.toRprBEM(buff, o+this.F.n8, p[1]); + } + + fromRprLE(buff, o) { + o = o || 0; + const x = this.F.fromRprLE(buff, o); + const y = this.F.fromRprLE(buff, o+this.F.n8); + if (this.F.isZero(x) && this.F.isZero(y)) { + return this.zero; + } + return [x, y, this.F.one]; + } + + fromRprBE(buff, o) { + o = o || 0; + const x = this.F.fromRprBE(buff, o); + const y = this.F.fromRprBE(buff, o+this.F.n8); + if (this.F.isZero(x) && this.F.isZero(y)) { + return this.zero; + } + return [x, y, this.F.one]; + } + + fromRprLEM(buff, o) { + o = o || 0; + const x = this.F.fromRprLEM(buff, o); + const y = this.F.fromRprLEM(buff, o+this.F.n8); + if (this.F.isZero(x) && this.F.isZero(y)) { + return this.zero; + } + return [x, y, this.F.one]; + } + + fromRprLEJM(buff, o) { + o = o || 0; + const x = this.F.fromRprLEM(buff, o); + const y = this.F.fromRprLEM(buff, o+this.F.n8); + const z = this.F.fromRprLEM(buff, o+this.F.n8*2); + if (this.F.isZero(x) && this.F.isZero(y)) { + return this.zero; + } + return [x, y, z]; + } + + fromRprBEM(buff, o) { + o = o || 0; + const x = this.F.fromRprBEM(buff, o); + const y = this.F.fromRprBEM(buff, o+this.F.n8); + if (this.F.isZero(x) && this.F.isZero(y)) { + return this.zero; + } + return [x, y, this.F.one]; + } + + fromRprCompressed(buff, o) { + const F = this.F; + const v = new Uint8Array(buff.buffer, o, F.n8); + if (v[0] & 0x40) return this.zero; + const P = new Array(3); + + const greatest = ((v[0] & 0x80) != 0); + v[0] = v[0] & 0x7F; + P[0] = F.fromRprBE(buff, o); + if (greatest) v[0] = v[0] | 0x80; // set back again the old value + + const x3b = F.add(F.mul(F.square(P[0]), P[0]), this.b); + P[1] = F.sqrt(x3b); + + if (P[1] === null) { + throw new Error("Invalid Point!"); + } + + const s = isGreatest(F, P[1]); + if (greatest ^ s) P[1] = F.neg(P[1]); + P[2] = F.one; + + return P; + } + + toRprCompressed(buff, o, p) { + p = this.affine(p); + const v = new Uint8Array(buff.buffer, o, this.F.n8); + if (this.isZero(p)) { + v.fill(0); + v[0] = 0x40; + return; + } + this.F.toRprBE(buff, o, p[0]); + + if (isGreatest(this.F, p[1])) { + v[0] = v[0] | 0x80; + } + } + + + fromRprUncompressed(buff, o) { + if (buff[0] & 0x40) return this.zero; + + return this.fromRprBE(buff, o); + } + + toRprUncompressed(buff, o, p) { + this.toRprBE(buff, o, p); + + if (this.isZero(p)) { + buff[o] = buff[o] | 0x40; + } + } + + +} + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +var utils$6 = {}; -/* provided dependency */ var console = __webpack_require__(6763); /* Copyright 2019 0KIMS association. - This file is part of websnark (Web Assembly zkSnark Prover). + This file is part of wasmsnark (Web Assembly zkSnark Prover). - websnark is a free software: you can redistribute it and/or modify it + wasmsnark is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - websnark is distributed in the hope that it will be useful, but WITHOUT + wasmsnark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License - along with websnark. If not, see . + along with wasmsnark. If not, see . */ -/* globals WebAssembly */ -const bigInt = __webpack_require__(2096); -const ModuleBuilder = __webpack_require__(442); +utils$6.bigInt2BytesLE = function bigInt2BytesLE(_a, len) { + const b = Array(len); + let v = BigInt(_a); + for (let i=0; i> 8n; + } + return b; +}; -function buf2hex(buffer) { // buffer is an ArrayBuffer - return Array.prototype.map.call(new Uint8Array(buffer), x => ("00" + x.toString(16)).slice(-2)).join(""); -} +utils$6.bigInt2U32LE = function bigInt2BytesLE(_a, len) { + const b = Array(len); + let v = BigInt(_a); + for (let i=0; i> 32n; + } + return b; +}; +utils$6.isOcamNum = function(a) { + if (!Array.isArray(a)) return false; + if (a.length != 3) return false; + if (typeof a[0] !== "number") return false; + if (typeof a[1] !== "number") return false; + if (!Array.isArray(a[2])) return false; + return true; +}; -async function buildProtoboard(builder, defBytes, bitsPerBytes) { - const protoboard = new Protoboard(); +/* + Copyright 2019 0KIMS association. - protoboard.defBytes = defBytes; - protoboard.bitsPerBytes = bitsPerBytes || 32; + This file is part of wasmsnark (Web Assembly zkSnark Prover). - protoboard.memory = new WebAssembly.Memory({initial:20000}); - protoboard.i32 = new Uint32Array(protoboard.memory.buffer); - protoboard.i8 = new Uint8Array(protoboard.memory.buffer); + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - const moduleBuilder = new ModuleBuilder(); + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. - const fLog32 = moduleBuilder.addIimportFunction("debug_log32", "debug", "log32"); - fLog32.addParam("x", "i32"); - const fLog64 = moduleBuilder.addIimportFunction("debug_log64", "debug", "log64"); - fLog64.addParam("x", "i32"); - fLog64.addParam("y", "i32"); + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ - buildLog32(moduleBuilder); - buildLog64(moduleBuilder); +var build_int = function buildInt(module, n64, _prefix) { - builder(moduleBuilder, protoboard); + const prefix = _prefix || "int"; + if (module.modules[prefix]) return prefix; // already builded + module.modules[prefix] = {}; + const n32 = n64*2; + const n8 = n64*8; - const code = moduleBuilder.build(); - - const wasmModule = await WebAssembly.compile(code); - - protoboard.log = console.log; - - protoboard.instance = await WebAssembly.instantiate(wasmModule, { - env: { - "memory": protoboard.memory - }, - debug: { - log32: function (c1) { - if (c1<0) c1 = 0x100000000+c1; - let s=c1.toString(16); - while (s.length<8) s = "0"+s; - protoboard.log(s + ": " + c1.toString()); - }, - log64: function (c1, c2) { - if (c1<0) c1 = 0x100000000+c1; - if (c2<0) c2 = 0x100000000+c2; - const n = bigInt(c1) + bigInt(c2).shiftLeft(32); - let s=n.toString(16); - while (s.length<16) s = "0"+s; - protoboard.log(s + ": " + n.toString()); - } - } - }); - - Object.assign(protoboard, protoboard.instance.exports); - Object.assign(protoboard, moduleBuilder.modules); - - return protoboard; - - function buildLog32(module) { - - const f = module.addFunction("log32"); - f.addParam("x", "i32"); + function buildCopy() { + const f = module.addFunction(prefix+"_copy"); + f.addParam("px", "i32"); + f.addParam("pr", "i32"); const c = f.getCodeBuilder(); - f.addCode(c.call("debug_log32", c.getLocal("x"))); + + for (let i=0; i>1) )&&(i>1, k>>1) + ) + ) + ); + + f.addCode( + c.setLocal(c1, + c.i64_add( + c.getLocal(c1), + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ) + ) + ); + } + + // Add the old carry + + if (k>0) { + f.addCode( + c.setLocal(c0, + c.i64_add( + c.i64_and( + c.getLocal(c0), + c.i64_const(0xFFFFFFFF) + ), + c.i64_and( + c.getLocal(c0_old), + c.i64_const(0xFFFFFFFF) + ), + ) + ) + ); + + f.addCode( + c.setLocal(c1, + c.i64_add( + c.i64_add( + c.getLocal(c1), + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ), + c.getLocal(c1_old) + ) + ) + ); + } + + f.addCode( + c.i64_store32( + c.getLocal("r"), + k*4, + c.getLocal(c0) + ) + ); + + f.addCode( + c.setLocal( + c0_old, + c.getLocal(c1) + ), + c.setLocal( + c1_old, + c.i64_shr_u( + c.getLocal(c0_old), + c.i64_const(32) + ) + ) + ); + + } + f.addCode( + c.i64_store32( + c.getLocal("r"), + n32*4*2-4, + c.getLocal(c0_old) + ) + ); + + } + + + function buildSquareOld() { + const f = module.addFunction(prefix+"_squareOld"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); + } + + function _buildMul1() { + const f = module.addFunction(prefix+"__mul1"); + f.addParam("px", "i32"); + f.addParam("y", "i64"); + f.addParam("pr", "i32"); + f.addLocal("c", "i64"); + + const c = f.getCodeBuilder(); + + f.addCode(c.setLocal( + "c", + c.i64_mul( + c.i64_load32_u(c.getLocal("px"), 0, 0), + c.getLocal("y") + ) + )); + + f.addCode(c.i64_store32( + c.getLocal("pr"), + 0, + 0, + c.getLocal("c"), + )); + + for (let i=1; i3)&&(Y[eY]==0) ey--; + f.addCode(c.block(c.loop( + c.br_if( + 1, + c.i32_or( + c.i32_load8_u( + c.i32_add(Y , c.getLocal("eY")), + 0, + 0 + ), + c.i32_eq( + c.getLocal("eY"), + c.i32_const(3) + ) + ) + ), + c.setLocal("eY", c.i32_sub(c.getLocal("eY"), c.i32_const(1))), + c.br(0) + ))); + + f.addCode( + c.setLocal( + "sy", + c.i64_add( + c.i64_load32_u( + c.i32_sub( + c.i32_add( Y, c.getLocal("eY")), + c.i32_const(3) + ), + 0, + 0 + ), + c.i64_const(1) + ) ) + ); + + // Force a divide by 0 if quotien is 0 + f.addCode( + c.if( + c.i64_eq( + c.getLocal("sy"), + c.i64_const(1) + ), + c.drop(c.i64_div_u(c.i64_const(0), c.i64_const(0))) + ) + ); + + f.addCode(c.block(c.loop( + + // while (eX>7)&&(Y[eX]==0) ex--; + c.block(c.loop( + c.br_if( + 1, + c.i32_or( + c.i32_load8_u( + c.i32_add(R , c.getLocal("eX")), + 0, + 0 + ), + c.i32_eq( + c.getLocal("eX"), + c.i32_const(7) + ) + ) + ), + c.setLocal("eX", c.i32_sub(c.getLocal("eX"), c.i32_const(1))), + c.br(0) + )), + + c.setLocal( + "sx", + c.i64_load( + c.i32_sub( + c.i32_add( R, c.getLocal("eX")), + c.i32_const(7) + ), + 0, + 0 + ) + ), + + c.setLocal( + "sx", + c.i64_div_u( + c.getLocal("sx"), + c.getLocal("sy") + ) + ), + c.setLocal( + "ec", + c.i32_sub( + c.i32_sub( + c.getLocal("eX"), + c.getLocal("eY") + ), + c.i32_const(4) + ) + ), + + // While greater than 32 bits or ec is neg, shr and inc exp + c.block(c.loop( + c.br_if( + 1, + c.i32_and( + c.i64_eqz( + c.i64_and( + c.getLocal("sx"), + c.i64_const("0xFFFFFFFF00000000") + ) + ), + c.i32_ge_s( + c.getLocal("ec"), + c.i32_const(0) + ) + ) + ), + + c.setLocal( + "sx", + c.i64_shr_u( + c.getLocal("sx"), + c.i64_const(8) + ) + ), + + c.setLocal( + "ec", + c.i32_add( + c.getLocal("ec"), + c.i32_const(1) + ) + ), + c.br(0) + )), + + c.if( + c.i64_eqz(c.getLocal("sx")), + [ + ...c.br_if( + 2, + c.i32_eqz(c.call(prefix + "_gte", R, Y)) + ), + ...c.setLocal("sx", c.i64_const(1)), + ...c.setLocal("ec", c.i32_const(0)) + ] + ), + + c.call(prefix + "__mul1", Y, c.getLocal("sx"), R2), + c.drop(c.call( + prefix + "_sub", + R, + c.i32_sub(R2, c.getLocal("ec")), + R + )), + c.call( + prefix + "__add1", + c.i32_add(C, c.getLocal("ec")), + c.getLocal("sx") + ), + c.br(0) + ))); + } + + function buildInverseMod() { + + const f = module.addFunction(prefix+"_inverseMod"); + f.addParam("px", "i32"); + f.addParam("pm", "i32"); + f.addParam("pr", "i32"); + f.addLocal("t", "i32"); + f.addLocal("newt", "i32"); + f.addLocal("r", "i32"); + f.addLocal("qq", "i32"); + f.addLocal("qr", "i32"); + f.addLocal("newr", "i32"); + f.addLocal("swp", "i32"); + f.addLocal("x", "i32"); + f.addLocal("signt", "i32"); + f.addLocal("signnewt", "i32"); + f.addLocal("signx", "i32"); + + const c = f.getCodeBuilder(); + + const aux1 = c.i32_const(module.alloc(n8)); + const aux2 = c.i32_const(module.alloc(n8)); + const aux3 = c.i32_const(module.alloc(n8)); + const aux4 = c.i32_const(module.alloc(n8)); + const aux5 = c.i32_const(module.alloc(n8)); + const aux6 = c.i32_const(module.alloc(n8)); + const mulBuff = c.i32_const(module.alloc(n8*2)); + const aux7 = c.i32_const(module.alloc(n8)); + + f.addCode( + c.setLocal("t", aux1), + c.call(prefix + "_zero", aux1), + c.setLocal("signt", c.i32_const(0)), + ); + + f.addCode( + c.setLocal("r", aux2), + c.call(prefix + "_copy", c.getLocal("pm"), aux2) + ); + + f.addCode( + c.setLocal("newt", aux3), + c.call(prefix + "_one", aux3), + c.setLocal("signnewt", c.i32_const(0)), + ); + + f.addCode( + c.setLocal("newr", aux4), + c.call(prefix + "_copy", c.getLocal("px"), aux4) + ); + + + + + f.addCode(c.setLocal("qq", aux5)); + f.addCode(c.setLocal("qr", aux6)); + f.addCode(c.setLocal("x", aux7)); + + f.addCode(c.block(c.loop( + c.br_if( + 1, + c.call(prefix + "_isZero", c.getLocal("newr") ) + ), + c.call(prefix + "_div", c.getLocal("r"), c.getLocal("newr"), c.getLocal("qq"), c.getLocal("qr")), + + c.call(prefix + "_mul", c.getLocal("qq"), c.getLocal("newt"), mulBuff), + + c.if( + c.getLocal("signt"), + c.if( + c.getLocal("signnewt"), + c.if ( + c.call(prefix + "_gte", mulBuff, c.getLocal("t")), + [ + ...c.drop(c.call(prefix + "_sub", mulBuff, c.getLocal("t"), c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(0)) + ], + [ + ...c.drop(c.call(prefix + "_sub", c.getLocal("t"), mulBuff, c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(1)) + ], + ), + [ + ...c.drop(c.call(prefix + "_add", mulBuff, c.getLocal("t"), c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(1)) + ] + ), + c.if( + c.getLocal("signnewt"), + [ + ...c.drop(c.call(prefix + "_add", mulBuff, c.getLocal("t"), c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(0)) + ], + c.if ( + c.call(prefix + "_gte", c.getLocal("t"), mulBuff), + [ + ...c.drop(c.call(prefix + "_sub", c.getLocal("t"), mulBuff, c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(0)) + ], + [ + ...c.drop(c.call(prefix + "_sub", mulBuff, c.getLocal("t"), c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(1)) + ] + ) + ) + ), + + c.setLocal("swp", c.getLocal("t")), + c.setLocal("t", c.getLocal("newt")), + c.setLocal("newt", c.getLocal("x")), + c.setLocal("x", c.getLocal("swp")), + + c.setLocal("signt", c.getLocal("signnewt")), + c.setLocal("signnewt", c.getLocal("signx")), + + c.setLocal("swp", c.getLocal("r")), + c.setLocal("r", c.getLocal("newr")), + c.setLocal("newr", c.getLocal("qr")), + c.setLocal("qr", c.getLocal("swp")), + + c.br(0) + ))); + + f.addCode(c.if( + c.getLocal("signt"), + c.drop(c.call(prefix + "_sub", c.getLocal("pm"), c.getLocal("t"), c.getLocal("pr"))), + c.call(prefix + "_copy", c.getLocal("t"), c.getLocal("pr")) )); } -} -class Protoboard { + buildCopy(); + buildZero(); + buildIsZero(); + buildOne(); + buildEq(); + buildGte(); + buildAdd(); + buildSub(); + buildMul(); + buildSquare(); + buildSquareOld(); + buildDiv(); + buildInverseMod(); + module.exportFunction(prefix+"_copy"); + module.exportFunction(prefix+"_zero"); + module.exportFunction(prefix+"_one"); + module.exportFunction(prefix+"_isZero"); + module.exportFunction(prefix+"_eq"); + module.exportFunction(prefix+"_gte"); + module.exportFunction(prefix+"_add"); + module.exportFunction(prefix+"_sub"); + module.exportFunction(prefix+"_mul"); + module.exportFunction(prefix+"_square"); + module.exportFunction(prefix+"_squareOld"); + module.exportFunction(prefix+"_div"); + module.exportFunction(prefix+"_inverseMod"); - constructor() { - - } - - alloc(length) { - if (typeof length === "undefined") { - length = this.defBytes; - } - length = (((length-1)>>3) +1)<<3; // Align to 64 bits. - - const res = this.i32[0]; - this.i32[0] += length; - return res; - } - - set(pos, nums, nBytes) { - if (!Array.isArray(nums)) { - nums = [nums]; - } - if (typeof nBytes === "undefined") { - nBytes = this.defBytes; - } - - const words = Math.floor((nBytes -1)/4)+1; - let p = pos; - - const CHUNK = bigInt.one.shiftLeft(this.bitsPerBytes); - - for (let i=0; i>2] = rd.remainder.toJSNumber(); - v = rd.quotient; - p += 4; - } - if (!v.isZero()) { - throw new Error('Expected v to be 0'); - } -/* this.i32[p>>2] = bigInt(nums[i]).shiftRight( (words-1)*this.bitsPerBytes).toJSNumber(); - p += 4; -*/ } - - return pos; - } - - get(pos, nElements, nBytes) { - if (typeof nBytes == "undefined") { - if (typeof nElements == "undefined") { - nElements = 1; - nBytes = this.defBytes; - } else { - nElements = nBytes; - nBytes = this.defBytes; - } - } - - const words = Math.floor((nBytes -1)/4)+1; - - const CHUNK = bigInt.one.shiftLeft(this.bitsPerBytes); - - - const nums = []; - for (let i=0; i=0; j--) { - acc = acc.times(CHUNK); - let v = this.i32[(pos>>2)+j]; - if (this.bitsPerBytes <32) { - if (v&0x80000000) v = v-0x100000000; - } - acc = acc.add(v); - } - nums.push(acc); - pos += words*4; - } - - if (nums.length == 1) return nums[0]; - return nums; - } -} - -module.exports = buildProtoboard; - - -/***/ }), - -/***/ 484: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmbuilder - - wasmbuilder is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmbuilder is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmbuilder. If not, see . -*/ - -const bigInt = __webpack_require__(2096); - -function toNumber(n) { - let v; - if (typeof n=="string") { - if (n.slice(0,2).toLowerCase() == "0x") { - v = bigInt(n.slice(2),16); - } else { - v = bigInt(n); - } - } else { - v = bigInt(n); - } - return v; -} - -function u32(n) { - const b = []; - const v = toNumber(n); - b.push(v.and(0xFF).toJSNumber()); - b.push(v.shiftRight(8).and(0xFF).toJSNumber()); - b.push(v.shiftRight(16).and(0xFF).toJSNumber()); - b.push(v.shiftRight(24).and(0xFF).toJSNumber()); - return b; -} - -function u64(n) { - const b = []; - const v = toNumber(n); - b.push(v.and(0xFF).toJSNumber()); - b.push(v.shiftRight(8).and(0xFF).toJSNumber()); - b.push(v.shiftRight(16).and(0xFF).toJSNumber()); - b.push(v.shiftRight(24).and(0xFF).toJSNumber()); - b.push(v.shiftRight(32).and(0xFF).toJSNumber()); - b.push(v.shiftRight(40).and(0xFF).toJSNumber()); - b.push(v.shiftRight(48).and(0xFF).toJSNumber()); - b.push(v.shiftRight(56).and(0xFF).toJSNumber()); - return b; -} - -function toUTF8Array(str) { - var utf8 = []; - for (var i=0; i < str.length; i++) { - var charcode = str.charCodeAt(i); - if (charcode < 0x80) utf8.push(charcode); - else if (charcode < 0x800) { - utf8.push(0xc0 | (charcode >> 6), - 0x80 | (charcode & 0x3f)); - } - else if (charcode < 0xd800 || charcode >= 0xe000) { - utf8.push(0xe0 | (charcode >> 12), - 0x80 | ((charcode>>6) & 0x3f), - 0x80 | (charcode & 0x3f)); - } - // surrogate pair - else { - i++; - // UTF-16 encodes 0x10000-0x10FFFF by - // subtracting 0x10000 and splitting the - // 20 bits of 0x0-0xFFFFF into two halves - charcode = 0x10000 + (((charcode & 0x3ff)<<10) - | (str.charCodeAt(i) & 0x3ff)); - utf8.push(0xf0 | (charcode >>18), - 0x80 | ((charcode>>12) & 0x3f), - 0x80 | ((charcode>>6) & 0x3f), - 0x80 | (charcode & 0x3f)); - } - } - return utf8; -} - -function string(str) { - const bytes = toUTF8Array(str); - return [ ...varuint32(bytes.length), ...bytes ]; -} - -function varuint(n) { - const code = []; - let v = toNumber(n); - if (v.isNegative()) throw new Error("Number cannot be negative"); - while (!v.isZero()) { - code.push(v.and(0x7F).toJSNumber()); - v = v.shiftRight(7); - } - if (code.length==0) code.push(0); - for (let i=0; i { + return prefix; +}; /* Copyright 2019 0KIMS association. @@ -58637,3285 +59206,78 @@ module.exports.ident = ident; along with wasmsnark. If not, see . */ - -// module.exports.bn128_wasm = require("./build/bn128_wasm.js"); -// module.exports.bls12381_wasm = require("./build/bls12381_wasm.js"); -// module.exports.mnt6753_wasm = require("./build/mnt6753_wasm.js"); - -module.exports.buildBn128 = __webpack_require__(3584); -module.exports.buildBls12381 = __webpack_require__(6920); -// module.exports.buildMnt6753 = require("./src/mnt6753/build_mnt7.js"); - - -/***/ }), - -/***/ 6920: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -const bigInt = __webpack_require__(2096); -const utils = __webpack_require__(2333); - -const buildF1m =__webpack_require__(75); -const buildF1 =__webpack_require__(8138); -const buildF2m =__webpack_require__(5420); -const buildF3m =__webpack_require__(7173); -const buildCurve =__webpack_require__(5904); -const buildFFT = __webpack_require__(3911); -const buildPol = __webpack_require__(2896); -const buildQAP = __webpack_require__(637); -const buildApplyKey = __webpack_require__(3320); - -// Definition here: https://electriccoin.co/blog/new-snark-curve/ - -module.exports = function buildBLS12381(module, _prefix) { - - const prefix = _prefix || "bls12381"; - - if (module.modules[prefix]) return prefix; // already builded - - const q = bigInt("1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab", 16); - const r = bigInt("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001", 16); - - const n64q = Math.floor((q.minus(1).bitLength() - 1)/64) +1; - const n8q = n64q*8; - const f1size = n8q; - const f2size = f1size * 2; - const f6size = f1size * 6; - const ftsize = f1size * 12; - - const n64r = Math.floor((r.minus(1).bitLength() - 1)/64) +1; - const n8r = n64r*8; - const frsize = n8r; - - - const pr = module.alloc(utils.bigInt2BytesLE( r, frsize )); - - const f1mPrefix = buildF1m(module, q, "f1m", "intq"); - buildF1(module, r, "fr", "frm", "intr"); - const pG1b = module.alloc(utils.bigInt2BytesLE( toMontgomery(bigInt(4)), f1size )); - const g1mPrefix = buildCurve(module, "g1m", "f1m", pG1b); - - buildFFT(module, "frm", "frm", "frm", "frm_mul"); - - buildPol(module, "pol", "frm"); - buildQAP(module, "qap", "frm"); - - const f2mPrefix = buildF2m(module, "f1m_neg", "f2m", "f1m"); - const pG2b = module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery(bigInt("4")), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(bigInt("4")), f1size ) - ]); - const g2mPrefix = buildCurve(module, "g2m", "f2m", pG2b); - - - function buildGTimesFr(fnName, opMul) { - const f = module.addFunction(fnName); - f.addParam("pG", "i32"); - f.addParam("pFr", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - const AUX = c.i32_const(module.alloc(n8r)); - - f.addCode( - c.call("frm_fromMontgomery", c.getLocal("pFr"), AUX), - c.call( - opMul, - c.getLocal("pG"), - AUX, - c.i32_const(n8r), - c.getLocal("pr") - ) - ); - - module.exportFunction(fnName); - } - buildGTimesFr("g1m_timesFr", "g1m_timesScalar"); - buildFFT(module, "g1m", "g1m", "frm", "g1m_timesFr"); - - buildGTimesFr("g2m_timesFr", "g2m_timesScalar"); - buildFFT(module, "g2m", "g2m", "frm", "g2m_timesFr"); - - buildGTimesFr("g1m_timesFrAffine", "g1m_timesScalarAffine"); - buildGTimesFr("g2m_timesFrAffine", "g2m_timesScalarAffine"); - - buildApplyKey(module, "frm_batchApplyKey", "fmr", "frm", n8r, n8r, n8r, "frm_mul"); - buildApplyKey(module, "g1m_batchApplyKey", "g1m", "frm", n8q*3, n8q*3, n8r, "g1m_timesFr"); - buildApplyKey(module, "g1m_batchApplyKeyMixed", "g1m", "frm", n8q*2, n8q*3, n8r, "g1m_timesFrAffine"); - buildApplyKey(module, "g2m_batchApplyKey", "g2m", "frm", n8q*2*3, n8q*3*2, n8r, "g2m_timesFr"); - buildApplyKey(module, "g2m_batchApplyKeyMixed", "g2m", "frm", n8q*2*2, n8q*3*2, n8r, "g2m_timesFrAffine"); - - - function toMontgomery(a) { - return bigInt(a).times( bigInt.one.shiftLeft(f1size*8)).mod(q); - } - - const G1gen = [ - bigInt("3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507"), - bigInt("1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569"), - bigInt.one - ]; - - const pG1gen = module.alloc( - [ - ...utils.bigInt2BytesLE( toMontgomery(G1gen[0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G1gen[1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G1gen[2]), f1size ), - ] - ); - - const G1zero = [ - bigInt.zero, - bigInt.one, - bigInt.zero - ]; - - const pG1zero = module.alloc( - [ - ...utils.bigInt2BytesLE( toMontgomery(G1zero[0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G1zero[1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G1zero[2]), f1size ) - ] - ); - - const G2gen = [ - [ - bigInt("352701069587466618187139116011060144890029952792775240219908644239793785735715026873347600343865175952761926303160"), - bigInt("3059144344244213709971259814753781636986470325476647558659373206291635324768958432433509563104347017837885763365758"), - ],[ - bigInt("1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905"), - bigInt("927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582"), - ],[ - bigInt.one, - bigInt.zero, - ] - ]; - - const pG2gen = module.alloc( - [ - ...utils.bigInt2BytesLE( toMontgomery(G2gen[0][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2gen[0][1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2gen[1][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2gen[1][1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2gen[2][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2gen[2][1]), f1size ), - ] - ); - - const G2zero = [ - [ - bigInt.zero, - bigInt.zero, - ],[ - bigInt.one, - bigInt.zero, - ],[ - bigInt.zero, - bigInt.zero, - ] - ]; - - const pG2zero = module.alloc( - [ - ...utils.bigInt2BytesLE( toMontgomery(G2zero[0][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2zero[0][1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2zero[1][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2zero[1][1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2zero[2][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2zero[2][1]), f1size ), - ] - ); - - const pOneT = module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery(1), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ]); - - const pTwoInv = module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery( bigInt(2).modInv(q)), f1size ), - ...utils.bigInt2BytesLE( bigInt(0), f1size ) - ]); - - const pBls12381Twist = module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery(1), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(1), f1size ), - ]); - - const pTwistCoefB = module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery("4"), f1size ), - ...utils.bigInt2BytesLE( toMontgomery("4"), f1size ), - ]); - - function build_mulNR2() { - const f = module.addFunction(f2mPrefix + "_mulNR"); - f.addParam("x", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - const x0c = c.i32_const(module.alloc(f1size)); - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1size)); - const r0 = c.getLocal("pr"); - const r1 = c.i32_add(c.getLocal("pr"), c.i32_const(f1size)); - - f.addCode( - c.call(f1mPrefix+"_copy", x0, x0c), - c.call(f1mPrefix+"_sub", x0, x1, r0), - c.call(f1mPrefix+"_add", x0c, x1, r1), - ); - } - build_mulNR2(); - - const f6mPrefix = buildF3m(module, f2mPrefix+"_mulNR", "f6m", "f2m"); - - function build_mulNR6() { - const f = module.addFunction(f6mPrefix + "_mulNR"); - f.addParam("x", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - const c0copy = c.i32_const(module.alloc(f1size*2)); - - f.addCode( - c.call( - f2mPrefix + "_copy", - c.getLocal("x"), - c0copy - ), - c.call( - f2mPrefix + "_mulNR", - c.i32_add(c.getLocal("x"), c.i32_const(n8q*4)), - c.getLocal("pr") - ), - c.call( - f2mPrefix + "_copy", - c.i32_add(c.getLocal("x"), c.i32_const(n8q*2)), - c.i32_add(c.getLocal("pr"), c.i32_const(n8q*4)), - ), - c.call( - f2mPrefix + "_copy", - c0copy, - c.i32_add(c.getLocal("pr"), c.i32_const(n8q*2)), - ), - ); - } - build_mulNR6(); - - const ftmPrefix = buildF2m(module, f6mPrefix+"_mulNR", "ftm", f6mPrefix); - - const ateLoopCount = bigInt("d201000000010000", 16); - const ateLoopBitBytes = bits(ateLoopCount); - const pAteLoopBitBytes = module.alloc(ateLoopBitBytes); - const isLoopNegative = true; - - const ateCoefSize = 3 * f2size; - const ateNDblCoefs = ateLoopBitBytes.length-1; - const ateNAddCoefs = ateLoopBitBytes.reduce((acc, b) => acc + ( b!=0 ? 1 : 0) ,0); - const ateNCoefs = ateNAddCoefs + ateNDblCoefs + 1; - const prePSize = 3*2*n8q; - const preQSize = 3*n8q*2 + ateNCoefs*ateCoefSize; - const finalExpIsNegative = true; - - const finalExpZ = bigInt("15132376222941642752"); - - - module.modules[prefix] = { - n64q: n64q, - n64r: n64r, - n8q: n8q, - n8r: n8r, - pG1gen: pG1gen, - pG1zero: pG1zero, - pG1b: pG1b, - pG2gen: pG2gen, - pG2zero: pG2zero, - pG2b: pG2b, - pq: module.modules["f1m"].pq, - pr: pr, - pOneT: pOneT, - r: r, - q: q, - prePSize: prePSize, - preQSize: preQSize - }; - - - function naf(n) { - let E = n; - const res = []; - while (E.gt(bigInt.zero)) { - if (E.isOdd()) { - const z = 2 - E.mod(4).toJSNumber(); - res.push( z ); - E = E.minus(z); - } else { - res.push( 0 ); - } - E = E.shiftRight(1); - } - return res; - } - - function bits(n) { - let E = n; - const res = []; - while (E.gt(bigInt.zero)) { - if (E.isOdd()) { - res.push( 1 ); - } else { - res.push( 0 ); - } - E = E.shiftRight(1); - } - return res; - } - - function buildPrepareG1() { - const f = module.addFunction(prefix+ "_prepareG1"); - f.addParam("pP", "i32"); - f.addParam("ppreP", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call(g1mPrefix + "_normalize", c.getLocal("pP"), c.getLocal("ppreP")), // TODO Remove if already in affine - ); - } - - - - function buildPrepDoubleStep() { - const f = module.addFunction(prefix+ "_prepDblStep"); - f.addParam("R", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const Rx = c.getLocal("R"); - const Ry = c.i32_add(c.getLocal("R"), c.i32_const(2*n8q)); - const Rz = c.i32_add(c.getLocal("R"), c.i32_const(4*n8q)); - - const t0 = c.getLocal("r"); - const t3 = c.i32_add(c.getLocal("r"), c.i32_const(2*n8q)); - const t6 = c.i32_add(c.getLocal("r"), c.i32_const(4*n8q)); - - - const zsquared = c.i32_const(module.alloc(f2size)); - const t1 = c.i32_const(module.alloc(f2size)); - const t2 = c.i32_const(module.alloc(f2size)); - const t4 = c.i32_const(module.alloc(f2size)); - const t5 = c.i32_const(module.alloc(f2size)); - - f.addCode( - - // tmp0 = r.x.square(); - c.call(f2mPrefix + "_square", Rx, t0), - - // tmp1 = r.y.square(); - c.call(f2mPrefix + "_square", Ry, t1), - - // tmp2 = tmp1.square(); - c.call(f2mPrefix + "_square", t1, t2), - - // tmp3 = (tmp1 + r.x).square() - tmp0 - tmp2; - c.call(f2mPrefix + "_add", t1, Rx, t3), - c.call(f2mPrefix + "_square", t3, t3), - c.call(f2mPrefix + "_sub", t3, t0, t3), - c.call(f2mPrefix + "_sub", t3, t2, t3), - - // tmp3 = tmp3 + tmp3; - c.call(f2mPrefix + "_add", t3, t3, t3), - - // tmp4 = tmp0 + tmp0 + tmp0; - c.call(f2mPrefix + "_add", t0, t0, t4), - c.call(f2mPrefix + "_add", t4, t0, t4), - - // tmp6 = r.x + tmp4; - c.call(f2mPrefix + "_add", Rx, t4, t6), - - // tmp5 = tmp4.square(); - c.call(f2mPrefix + "_square", t4, t5), - - // zsquared = r.z.square(); - c.call(f2mPrefix + "_square", Rz, zsquared), - - // r.x = tmp5 - tmp3 - tmp3; - c.call(f2mPrefix + "_sub", t5, t3, Rx), - c.call(f2mPrefix + "_sub", Rx, t3, Rx), - - // r.z = (r.z + r.y).square() - tmp1 - zsquared; - c.call(f2mPrefix + "_add", Rz, Ry, Rz), - c.call(f2mPrefix + "_square", Rz, Rz), - c.call(f2mPrefix + "_sub", Rz, t1, Rz), - c.call(f2mPrefix + "_sub", Rz, zsquared, Rz), - - // r.y = (tmp3 - r.x) * tmp4; - c.call(f2mPrefix + "_sub", t3, Rx, Ry), - c.call(f2mPrefix + "_mul", Ry, t4, Ry), - - // tmp2 = tmp2 + tmp2; - c.call(f2mPrefix + "_add", t2, t2, t2), - - // tmp2 = tmp2 + tmp2; - c.call(f2mPrefix + "_add", t2, t2, t2), - - // tmp2 = tmp2 + tmp2; - c.call(f2mPrefix + "_add", t2, t2, t2), - - // r.y -= tmp2; - c.call(f2mPrefix + "_sub", Ry, t2, Ry), - - // tmp3 = tmp4 * zsquared; - c.call(f2mPrefix + "_mul", t4, zsquared, t3), - - // tmp3 = tmp3 + tmp3; - c.call(f2mPrefix + "_add", t3, t3, t3), - - // tmp3 = -tmp3; - c.call(f2mPrefix + "_neg", t3, t3), - - // tmp6 = tmp6.square() - tmp0 - tmp5; - c.call(f2mPrefix + "_square", t6, t6), - c.call(f2mPrefix + "_sub", t6, t0, t6), - c.call(f2mPrefix + "_sub", t6, t5, t6), - - // tmp1 = tmp1 + tmp1; - c.call(f2mPrefix + "_add", t1, t1, t1), - - // tmp1 = tmp1 + tmp1; - c.call(f2mPrefix + "_add", t1, t1, t1), - - // tmp6 = tmp6 - tmp1; - c.call(f2mPrefix + "_sub", t6, t1, t6), - - // tmp0 = r.z * zsquared; - c.call(f2mPrefix + "_mul", Rz, zsquared, t0), - - // tmp0 = tmp0 + tmp0; - c.call(f2mPrefix + "_add", t0, t0, t0), - - ); - } - - function buildPrepAddStep() { - const f = module.addFunction(prefix+ "_prepAddStep"); - f.addParam("R", "i32"); - f.addParam("Q", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const Rx = c.getLocal("R"); - const Ry = c.i32_add(c.getLocal("R"), c.i32_const(2*n8q)); - const Rz = c.i32_add(c.getLocal("R"), c.i32_const(4*n8q)); - - const Qx = c.getLocal("Q"); - const Qy = c.i32_add(c.getLocal("Q"), c.i32_const(2*n8q)); - - const t10 = c.getLocal("r"); - const t1 = c.i32_add(c.getLocal("r"), c.i32_const(2*n8q)); - const t9 = c.i32_add(c.getLocal("r"), c.i32_const(4*n8q)); - - const zsquared = c.i32_const(module.alloc(f2size)); - const ysquared = c.i32_const(module.alloc(f2size)); - const ztsquared = c.i32_const(module.alloc(f2size)); - const t0 = c.i32_const(module.alloc(f2size)); - const t2 = c.i32_const(module.alloc(f2size)); - const t3 = c.i32_const(module.alloc(f2size)); - const t4 = c.i32_const(module.alloc(f2size)); - const t5 = c.i32_const(module.alloc(f2size)); - const t6 = c.i32_const(module.alloc(f2size)); - const t7 = c.i32_const(module.alloc(f2size)); - const t8 = c.i32_const(module.alloc(f2size)); - - f.addCode( - - // zsquared = r.z.square(); - c.call(f2mPrefix + "_square", Rz, zsquared), - - // ysquared = q.y.square(); - c.call(f2mPrefix + "_square", Qy, ysquared), - - // t0 = zsquared * q.x; - c.call(f2mPrefix + "_mul", zsquared, Qx, t0), - - // t1 = ((q.y + r.z).square() - ysquared - zsquared) * zsquared; - c.call(f2mPrefix + "_add", Qy, Rz, t1), - c.call(f2mPrefix + "_square", t1, t1), - c.call(f2mPrefix + "_sub", t1, ysquared, t1), - c.call(f2mPrefix + "_sub", t1, zsquared, t1), - c.call(f2mPrefix + "_mul", t1, zsquared, t1), - - // t2 = t0 - r.x; - c.call(f2mPrefix + "_sub", t0, Rx, t2), - - // t3 = t2.square(); - c.call(f2mPrefix + "_square", t2, t3), - - // t4 = t3 + t3; - c.call(f2mPrefix + "_add", t3, t3, t4), - - // t4 = t4 + t4; - c.call(f2mPrefix + "_add", t4, t4, t4), - - // t5 = t4 * t2; - c.call(f2mPrefix + "_mul", t4, t2, t5), - - // t6 = t1 - r.y - r.y; - c.call(f2mPrefix + "_sub", t1, Ry, t6), - c.call(f2mPrefix + "_sub", t6, Ry, t6), - - // t9 = t6 * q.x; - c.call(f2mPrefix + "_mul", t6, Qx, t9), - - // t7 = t4 * r.x; - c.call(f2mPrefix + "_mul", t4, Rx, t7), - - // r.x = t6.square() - t5 - t7 - t7; - c.call(f2mPrefix + "_square", t6, Rx), - c.call(f2mPrefix + "_sub", Rx, t5, Rx), - c.call(f2mPrefix + "_sub", Rx, t7, Rx), - c.call(f2mPrefix + "_sub", Rx, t7, Rx), - - // r.z = (r.z + t2).square() - zsquared - t3; - c.call(f2mPrefix + "_add", Rz, t2, Rz), - c.call(f2mPrefix + "_square", Rz, Rz), - c.call(f2mPrefix + "_sub", Rz, zsquared, Rz), - c.call(f2mPrefix + "_sub", Rz, t3, Rz), - - // t10 = q.y + r.z; - c.call(f2mPrefix + "_add", Qy, Rz, t10), - - // t8 = (t7 - r.x) * t6; - c.call(f2mPrefix + "_sub", t7, Rx, t8), - c.call(f2mPrefix + "_mul", t8, t6, t8), - - // t0 = r.y * t5; - c.call(f2mPrefix + "_mul", Ry, t5, t0), - - // t0 = t0 + t0; - c.call(f2mPrefix + "_add", t0, t0, t0), - - // r.y = t8 - t0; - c.call(f2mPrefix + "_sub", t8, t0, Ry), - - // t10 = t10.square() - ysquared; - c.call(f2mPrefix + "_square", t10, t10), - c.call(f2mPrefix + "_sub", t10, ysquared, t10), - - // ztsquared = r.z.square(); - c.call(f2mPrefix + "_square", Rz, ztsquared), - - // t10 = t10 - ztsquared; - c.call(f2mPrefix + "_sub", t10, ztsquared, t10), - - // t9 = t9 + t9 - t10; - c.call(f2mPrefix + "_add", t9, t9, t9), - c.call(f2mPrefix + "_sub", t9, t10, t9), - - // t10 = r.z + r.z; - c.call(f2mPrefix + "_add", Rz, Rz, t10), - - // t6 = -t6; - c.call(f2mPrefix + "_neg", t6, t6), - - // t1 = t6 + t6; - c.call(f2mPrefix + "_add", t6, t6, t1), - ); - } - - - function buildPrepareG2() { - const f = module.addFunction(prefix+ "_prepareG2"); - f.addParam("pQ", "i32"); - f.addParam("ppreQ", "i32"); - f.addLocal("pCoef", "i32"); - f.addLocal("i", "i32"); - - const c = f.getCodeBuilder(); - - - const Q = c.getLocal("pQ"); - - const pR = module.alloc(f2size*3); - const R = c.i32_const(pR); - - const base = c.getLocal("ppreQ"); - - f.addCode( - c.call(g2mPrefix + "_normalize", Q, base), - c.if( - c.call(g2mPrefix + "_isZero", base), - c.ret([]) - ), - c.call(g2mPrefix + "_copy", base, R), - c.setLocal("pCoef", c.i32_add(c.getLocal("ppreQ"), c.i32_const(f2size*3))), - ); - - f.addCode( - c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), - c.block(c.loop( - - c.call(prefix + "_prepDblStep", R, c.getLocal("pCoef")), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - c.if( - c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), - [ - ...c.call(prefix + "_prepAddStep", R, base, c.getLocal("pCoef")), - ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - ] - ), - c.br_if(1, c.i32_eqz ( c.getLocal("i") )), - c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - ); - } - - - function buildF6Mul1() { - const f = module.addFunction(f6mPrefix+ "_mul1"); - f.addParam("pA", "i32"); // F6 - f.addParam("pC1", "i32"); // F2 - f.addParam("pR", "i32"); // F6 - - const c = f.getCodeBuilder(); - - const A_c0 = c.getLocal("pA"); - const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*2)); - const A_c2 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*4)); - - const c1 = c.getLocal("pC1"); - - const t1 = c.getLocal("pR"); - const t2 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*2)); - const b_b = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*4)); - - const Ac0_Ac1 = c.i32_const(module.alloc(f1size*2)); - const Ac1_Ac2 = c.i32_const(module.alloc(f1size*2)); - - f.addCode( - - c.call(f2mPrefix + "_add", A_c0, A_c1, Ac0_Ac1), - c.call(f2mPrefix + "_add", A_c1, A_c2, Ac1_Ac2), - - // let b_b = self.c1 * c1; - c.call(f2mPrefix + "_mul", A_c1, c1, b_b), - - // let t1 = (self.c1 + self.c2) * c1 - b_b; - c.call(f2mPrefix + "_mul", Ac1_Ac2, c1, t1), - c.call(f2mPrefix + "_sub", t1, b_b, t1), - - // let t1 = t1.mul_by_nonresidue(); - c.call(f2mPrefix + "_mulNR", t1, t1), - - // let t2 = (self.c0 + self.c1) * c1 - b_b; - c.call(f2mPrefix + "_mul", Ac0_Ac1, c1, t2), - c.call(f2mPrefix + "_sub", t2, b_b, t2), - ); - } - buildF6Mul1(); - - function buildF6Mul01() { - const f = module.addFunction(f6mPrefix+ "_mul01"); - f.addParam("pA", "i32"); // F6 - f.addParam("pC0", "i32"); // F2 - f.addParam("pC1", "i32"); // F2 - f.addParam("pR", "i32"); // F6 - - const c = f.getCodeBuilder(); - - const A_c0 = c.getLocal("pA"); - const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*2)); - const A_c2 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*4)); - - const c0 = c.getLocal("pC0"); - const c1 = c.getLocal("pC1"); - - const t1 = c.getLocal("pR"); - const t2 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*2)); - const t3 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*4)); - - const a_a = c.i32_const(module.alloc(f1size*2)); - const b_b = c.i32_const(module.alloc(f1size*2)); - const Ac0_Ac1 = c.i32_const(module.alloc(f1size*2)); - const Ac0_Ac2 = c.i32_const(module.alloc(f1size*2)); - - f.addCode( - // let a_a = self.c0 * c0; - c.call(f2mPrefix + "_mul", A_c0, c0, a_a), - - // let b_b = self.c1 * c1; - c.call(f2mPrefix + "_mul", A_c1, c1, b_b), - - - c.call(f2mPrefix + "_add", A_c0, A_c1, Ac0_Ac1), - c.call(f2mPrefix + "_add", A_c0, A_c2, Ac0_Ac2), - - // let t1 = (self.c1 + self.c2) * c1 - b_b; - c.call(f2mPrefix + "_add", A_c1, A_c2, t1), - c.call(f2mPrefix + "_mul", t1, c1, t1), - c.call(f2mPrefix + "_sub", t1, b_b, t1), - - // let t1 = t1.mul_by_nonresidue() + a_a; - c.call(f2mPrefix + "_mulNR", t1, t1), - c.call(f2mPrefix + "_add", t1, a_a, t1), - - // let t2 = (c0 + c1) * (self.c0 + self.c1) - a_a - b_b; - c.call(f2mPrefix + "_add", c0, c1, t2), - c.call(f2mPrefix + "_mul", t2, Ac0_Ac1, t2), - c.call(f2mPrefix + "_sub", t2, a_a, t2), - c.call(f2mPrefix + "_sub", t2, b_b, t2), - - // let t3 = (self.c0 + self.c2) * c0 - a_a + b_b; - c.call(f2mPrefix + "_mul", Ac0_Ac2, c0, t3), - c.call(f2mPrefix + "_sub", t3, a_a, t3), - c.call(f2mPrefix + "_add", t3, b_b, t3), - - - ); - } - buildF6Mul01(); - - - function buildF12Mul014() { - - const f = module.addFunction(ftmPrefix+ "_mul014"); - f.addParam("pA", "i32"); // F12 - f.addParam("pC0", "i32"); // F2 - f.addParam("pC1", "i32"); // F2 - f.addParam("pC4", "i32"); // F2 - f.addParam("pR", "i32"); // F12 - - const c = f.getCodeBuilder(); - - - const A_c0 = c.getLocal("pA"); - const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*6)); - - const c0 = c.getLocal("pC0"); - const c1 = c.getLocal("pC1"); - const c4 = c.getLocal("pC4"); - - const aa = c.i32_const(module.alloc(f1size*6)); - const bb = c.i32_const(module.alloc(f1size*6)); - const o = c.i32_const(module.alloc(f1size*2)); - - const R_c0 = c.getLocal("pR"); - const R_c1 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*6)); - - f.addCode( - // let aa = self.c0.mul_by_01(c0, c1); - c.call(f6mPrefix + "_mul01", A_c0, c0, c1, aa), - - // let bb = self.c1.mul_by_1(c4); - c.call(f6mPrefix + "_mul1", A_c1, c4, bb), - - // let o = c1 + c4; - c.call(f2mPrefix + "_add", c1, c4, o), - - // let c1 = self.c1 + self.c0; - c.call(f6mPrefix + "_add", A_c1, A_c0, R_c1), - - // let c1 = c1.mul_by_01(c0, &o); - c.call(f6mPrefix + "_mul01", R_c1, c0, o, R_c1), - - // let c1 = c1 - aa - bb; - c.call(f6mPrefix + "_sub", R_c1, aa, R_c1), - c.call(f6mPrefix + "_sub", R_c1, bb, R_c1), - - // let c0 = bb; - c.call(f6mPrefix + "_copy", bb, R_c0), - - // let c0 = c0.mul_by_nonresidue(); - c.call(f6mPrefix + "_mulNR", R_c0, R_c0), - - // let c0 = c0 + aa; - c.call(f6mPrefix + "_add", R_c0, aa, R_c0), - ); - } - buildF12Mul014(); - - - function buildELL() { - const f = module.addFunction(prefix+ "_ell"); - f.addParam("pP", "i32"); - f.addParam("pCoefs", "i32"); - f.addParam("pF", "i32"); - - const c = f.getCodeBuilder(); - - const Px = c.getLocal("pP"); - const Py = c.i32_add(c.getLocal("pP"), c.i32_const(n8q)); - - const F = c.getLocal("pF"); - - const coef0_0 = c.getLocal("pCoefs"); - const coef0_1 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size)); - const coef1_0 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*2)); - const coef1_1 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*3)); - const coef2 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*4)); - - const pc0 = module.alloc(f1size*2); - const c0 = c.i32_const(pc0); - const c0_c0 = c.i32_const(pc0); - const c0_c1 = c.i32_const(pc0+f1size); - - const pc1 = module.alloc(f1size*2); - const c1 = c.i32_const(pc1); - const c1_c0 = c.i32_const(pc1); - const c1_c1 = c.i32_const(pc1+f1size); - f.addCode( - // let mut c0 = coeffs.0; - // let mut c1 = coeffs.1; - // - // c0.c0 *= p.y; - // c0.c1 *= p.y; - // - // c1.c0 *= p.x; - // c1.c1 *= p.x; - // - // f.mul_by_014(&coeffs.2, &c1, &c0) - - c.call(f1mPrefix + "_mul", coef0_0, Py, c0_c0), - c.call(f1mPrefix + "_mul", coef0_1, Py, c0_c1), - c.call(f1mPrefix + "_mul", coef1_0, Px, c1_c0), - c.call(f1mPrefix + "_mul", coef1_1, Px, c1_c1), - - c.call(ftmPrefix + "_mul014", F, coef2, c1, c0, F), - - ); - - } - buildELL(); - - function buildMillerLoop() { - const f = module.addFunction(prefix+ "_millerLoop"); - f.addParam("ppreP", "i32"); - f.addParam("ppreQ", "i32"); - f.addParam("r", "i32"); - f.addLocal("pCoef", "i32"); - f.addLocal("i", "i32"); - - const c = f.getCodeBuilder(); - - const preP = c.getLocal("ppreP"); - const preQ = c.getLocal("ppreQ"); - - const coefs = c.getLocal("pCoef"); - - const F = c.getLocal("r"); - - - f.addCode( - c.call(ftmPrefix + "_one", F), - - c.if( - c.call(g1mPrefix + "_isZero", preP), - c.ret([]) - ), - c.if( - c.call(g1mPrefix + "_isZero", c.getLocal("ppreQ")), - c.ret([]) - ), - c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), - - c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), - c.block(c.loop( - - - c.call(prefix + "_ell", preP, coefs, F), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - c.if( - c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), - [ - ...c.call(prefix + "_ell", preP, coefs, F), - ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - ] - ), - c.call(ftmPrefix + "_square", F, F), - - c.br_if(1, c.i32_eq ( c.getLocal("i"), c.i32_const(1) )), - c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )), - c.call(prefix + "_ell", preP, coefs, F), - - ); - - - if (isLoopNegative) { - f.addCode( - c.call(ftmPrefix + "_conjugate", F, F), - ); - } - } - - - function buildFrobeniusMap(n) { - const F12 = [ - [ - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - ], - [ - [bigInt("1"), bigInt("0")], - [bigInt("3850754370037169011952147076051364057158807420970682438676050522613628423219637725072182697113062777891589506424760"), bigInt("151655185184498381465642749684540099398075398968325446656007613510403227271200139370504932015952886146304766135027")], - [bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620351"), bigInt("0")], - [bigInt("2973677408986561043442465346520108879172042883009249989176415018091420807192182638567116318576472649347015917690530"), bigInt("1028732146235106349975324479215795277384839936929757896155643118032610843298655225875571310552543014690878354869257")], - [bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350"), bigInt("0")], - [bigInt("3125332594171059424908108096204648978570118281977575435832422631601824034463382777937621250592425535493320683825557"), bigInt("877076961050607968509681729531255177986764537961432449499635504522207616027455086505066378536590128544573588734230")], - [bigInt("4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786"), bigInt("0")], - [bigInt("151655185184498381465642749684540099398075398968325446656007613510403227271200139370504932015952886146304766135027"), bigInt("3850754370037169011952147076051364057158807420970682438676050522613628423219637725072182697113062777891589506424760")], - [bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436"), bigInt("0")], - [bigInt("1028732146235106349975324479215795277384839936929757896155643118032610843298655225875571310552543014690878354869257"), bigInt("2973677408986561043442465346520108879172042883009249989176415018091420807192182638567116318576472649347015917690530")], - [bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939437"), bigInt("0")], - [bigInt("877076961050607968509681729531255177986764537961432449499635504522207616027455086505066378536590128544573588734230"), bigInt("3125332594171059424908108096204648978570118281977575435832422631601824034463382777937621250592425535493320683825557")], - ] - ]; - - const F6 = [ - [ - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - ], - [ - [bigInt("1"), bigInt("0")], - [bigInt("0"), bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436")], - [bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350"), bigInt("0")], - [bigInt("0"), bigInt("1")], - [bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436"), bigInt("0")], - [bigInt("0"), bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350")], - ], - [ - [bigInt("1"), bigInt("0")], - [bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939437"), bigInt("0")], - [bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436"), bigInt("0")], - [bigInt("4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786"), bigInt("0")], - [bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350"), bigInt("0")], - [bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620351"), bigInt("0")], - ] - ]; - - const f = module.addFunction(ftmPrefix + "_frobeniusMap"+n); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - for (let i=0; i<6; i++) { - const X = (i==0) ? c.getLocal("x") : c.i32_add(c.getLocal("x"), c.i32_const(i*f2size)); - const Xc0 = X; - const Xc1 = c.i32_add(c.getLocal("x"), c.i32_const(i*f2size + f1size)); - const R = (i==0) ? c.getLocal("r") : c.i32_add(c.getLocal("r"), c.i32_const(i*f2size)); - const Rc0 = R; - const Rc1 = c.i32_add(c.getLocal("r"), c.i32_const(i*f2size + f1size)); - const coef = mul2(F12[Math.floor(i/3)][n%12] , F6[i%3][n%6]); - const pCoef = module.alloc([ - ...utils.bigInt2BytesLE(toMontgomery(coef[0]), n8q), - ...utils.bigInt2BytesLE(toMontgomery(coef[1]), n8q), - ]); - if (n%2 == 1) { - f.addCode( - c.call(f1mPrefix + "_copy", Xc0, Rc0), - c.call(f1mPrefix + "_neg", Xc1, Rc1), - c.call(f2mPrefix + "_mul", R, c.i32_const(pCoef), R), - ); - } else { - f.addCode(c.call(f2mPrefix + "_mul", X, c.i32_const(pCoef), R)); - } - } - - function mul2(a, b) { - const ac0 = bigInt(a[0]); - const ac1 = bigInt(a[1]); - const bc0 = bigInt(b[0]); - const bc1 = bigInt(b[1]); - const res = [ - ac0.times(bc0).minus( ac1.times(bc1) ).mod(q), - ac0.times(bc1).add( ac1.times(bc0) ).mod(q), - ]; - if (res[0].isNegative()) res[0] = res[0].add(q); - return res; - } - - } - - - function buildCyclotomicSquare() { - const f = module.addFunction(prefix+ "__cyclotomicSquare"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x4 = c.i32_add(c.getLocal("x"), c.i32_const(f2size)); - const x3 = c.i32_add(c.getLocal("x"), c.i32_const(2*f2size)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(3*f2size)); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(4*f2size)); - const x5 = c.i32_add(c.getLocal("x"), c.i32_const(5*f2size)); - - const r0 = c.getLocal("r"); - const r4 = c.i32_add(c.getLocal("r"), c.i32_const(f2size)); - const r3 = c.i32_add(c.getLocal("r"), c.i32_const(2*f2size)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(3*f2size)); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(4*f2size)); - const r5 = c.i32_add(c.getLocal("r"), c.i32_const(5*f2size)); - - const t0 = c.i32_const(module.alloc(f2size)); - const t1 = c.i32_const(module.alloc(f2size)); - const t2 = c.i32_const(module.alloc(f2size)); - const t3 = c.i32_const(module.alloc(f2size)); - const t4 = c.i32_const(module.alloc(f2size)); - const t5 = c.i32_const(module.alloc(f2size)); - const tmp = c.i32_const(module.alloc(f2size)); - const AUX = c.i32_const(module.alloc(f2size)); - - - f.addCode( - -// c.call(ftmPrefix + "_square", x0, r0), - - // // t0 + t1*y = (z0 + z1*y)^2 = a^2 - // tmp = z0 * z1; - // t0 = (z0 + z1) * (z0 + my_Fp6::non_residue * z1) - tmp - my_Fp6::non_residue * tmp; - // t1 = tmp + tmp; - c.call(f2mPrefix + "_mul", x0, x1, tmp), - c.call(f2mPrefix + "_mulNR", x1, t0), - c.call(f2mPrefix + "_add", x0, t0, t0), - c.call(f2mPrefix + "_add", x0, x1, AUX), - c.call(f2mPrefix + "_mul", AUX, t0, t0), - c.call(f2mPrefix + "_mulNR", tmp, AUX), - c.call(f2mPrefix + "_add", tmp, AUX, AUX), - c.call(f2mPrefix + "_sub", t0, AUX, t0), - c.call(f2mPrefix + "_add", tmp, tmp, t1), - - // // t2 + t3*y = (z2 + z3*y)^2 = b^2 - // tmp = z2 * z3; - // t2 = (z2 + z3) * (z2 + my_Fp6::non_residue * z3) - tmp - my_Fp6::non_residue * tmp; - // t3 = tmp + tmp; - c.call(f2mPrefix + "_mul", x2, x3, tmp), - c.call(f2mPrefix + "_mulNR", x3, t2), - c.call(f2mPrefix + "_add", x2, t2, t2), - c.call(f2mPrefix + "_add", x2, x3, AUX), - c.call(f2mPrefix + "_mul", AUX, t2, t2), - c.call(f2mPrefix + "_mulNR", tmp, AUX), - c.call(f2mPrefix + "_add", tmp, AUX, AUX), - c.call(f2mPrefix + "_sub", t2, AUX, t2), - c.call(f2mPrefix + "_add", tmp, tmp, t3), - - // // t4 + t5*y = (z4 + z5*y)^2 = c^2 - // tmp = z4 * z5; - // t4 = (z4 + z5) * (z4 + my_Fp6::non_residue * z5) - tmp - my_Fp6::non_residue * tmp; - // t5 = tmp + tmp; - c.call(f2mPrefix + "_mul", x4, x5, tmp), - c.call(f2mPrefix + "_mulNR", x5, t4), - c.call(f2mPrefix + "_add", x4, t4, t4), - c.call(f2mPrefix + "_add", x4, x5, AUX), - c.call(f2mPrefix + "_mul", AUX, t4, t4), - c.call(f2mPrefix + "_mulNR", tmp, AUX), - c.call(f2mPrefix + "_add", tmp, AUX, AUX), - c.call(f2mPrefix + "_sub", t4, AUX, t4), - c.call(f2mPrefix + "_add", tmp, tmp, t5), - - // For A - // z0 = 3 * t0 - 2 * z0 - c.call(f2mPrefix + "_sub", t0, x0, r0), - c.call(f2mPrefix + "_add", r0, r0, r0), - c.call(f2mPrefix + "_add", t0, r0, r0), - // z1 = 3 * t1 + 2 * z1 - c.call(f2mPrefix + "_add", t1, x1, r1), - c.call(f2mPrefix + "_add", r1, r1, r1), - c.call(f2mPrefix + "_add", t1, r1, r1), - - // For B - // z2 = 3 * (xi * t5) + 2 * z2 - c.call(f2mPrefix + "_mul", t5, c.i32_const(pBls12381Twist), AUX), - c.call(f2mPrefix + "_add", AUX, x2, r2), - c.call(f2mPrefix + "_add", r2, r2, r2), - c.call(f2mPrefix + "_add", AUX, r2, r2), - // z3 = 3 * t4 - 2 * z3 - c.call(f2mPrefix + "_sub", t4, x3, r3), - c.call(f2mPrefix + "_add", r3, r3, r3), - c.call(f2mPrefix + "_add", t4, r3, r3), - - // For C - // z4 = 3 * t2 - 2 * z4 - c.call(f2mPrefix + "_sub", t2, x4, r4), - c.call(f2mPrefix + "_add", r4, r4, r4), - c.call(f2mPrefix + "_add", t2, r4, r4), - // z5 = 3 * t3 + 2 * z5 - c.call(f2mPrefix + "_add", t3, x5, r5), - c.call(f2mPrefix + "_add", r5, r5, r5), - c.call(f2mPrefix + "_add", t3, r5, r5), - - ); - } - - - function buildCyclotomicExp(exponent, isExpNegative, fnName) { - const exponentNafBytes = naf(exponent).map( (b) => (b==-1 ? 0xFF: b) ); - const pExponentNafBytes = module.alloc(exponentNafBytes); - // const pExponent = module.alloc(utils.bigInt2BytesLE(exponent, n8)); - - const f = module.addFunction(prefix+ "__cyclotomicExp_"+fnName); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - f.addLocal("bit", "i32"); - f.addLocal("i", "i32"); - - const c = f.getCodeBuilder(); - - const x = c.getLocal("x"); - - const res = c.getLocal("r"); - - const inverse = c.i32_const(module.alloc(ftsize)); - - - f.addCode( -// c.call(ftmPrefix + "_exp", x, c.i32_const(pExponent), c.i32_const(32), res), - - c.call(ftmPrefix + "_conjugate", x, inverse), - c.call(ftmPrefix + "_one", res), - - c.if( - c.teeLocal("bit", c.i32_load8_s(c.i32_const(exponentNafBytes.length-1), pExponentNafBytes)), - c.if( - c.i32_eq( - c.getLocal("bit"), - c.i32_const(1) - ), - c.call(ftmPrefix + "_mul", res, x, res), - c.call(ftmPrefix + "_mul", res, inverse, res), - ) - ), - - c.setLocal("i", c.i32_const(exponentNafBytes.length-2)), - c.block(c.loop( -// c.call(ftmPrefix + "_square", res, res), - c.call(prefix + "__cyclotomicSquare", res, res), - c.if( - c.teeLocal("bit", c.i32_load8_s(c.getLocal("i"), pExponentNafBytes)), - c.if( - c.i32_eq( - c.getLocal("bit"), - c.i32_const(1) - ), - c.call(ftmPrefix + "_mul", res, x, res), - c.call(ftmPrefix + "_mul", res, inverse, res), - ) - ), - c.br_if(1, c.i32_eqz ( c.getLocal("i") )), - c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - ); - - if (isExpNegative) { - f.addCode( - c.call(ftmPrefix + "_conjugate", res, res), - ); - } - - } - - function buildFinalExponentiation() { - buildCyclotomicSquare(); - buildCyclotomicExp(finalExpZ, finalExpIsNegative, "w0"); - - const f = module.addFunction(prefix+ "_finalExponentiation"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const elt = c.getLocal("x"); - const res = c.getLocal("r"); - const t0 = c.i32_const(module.alloc(ftsize)); - const t1 = c.i32_const(module.alloc(ftsize)); - const t2 = c.i32_const(module.alloc(ftsize)); - const t3 = c.i32_const(module.alloc(ftsize)); - const t4 = c.i32_const(module.alloc(ftsize)); - const t5 = c.i32_const(module.alloc(ftsize)); - const t6 = c.i32_const(module.alloc(ftsize)); - - f.addCode( - - // let mut t0 = f.frobenius_map(6) - c.call(ftmPrefix + "_frobeniusMap6", elt, t0), - - // let t1 = f.invert() - c.call(ftmPrefix + "_inverse", elt, t1), - - // let mut t2 = t0 * t1; - c.call(ftmPrefix + "_mul", t0, t1, t2), - - // t1 = t2.clone(); - c.call(ftmPrefix + "_copy", t2, t1), - - // t2 = t2.frobenius_map().frobenius_map(); - c.call(ftmPrefix + "_frobeniusMap2", t2, t2), - - // t2 *= t1; - c.call(ftmPrefix + "_mul", t2, t1, t2), - - - // t1 = cyclotomic_square(t2).conjugate(); - c.call(prefix + "__cyclotomicSquare", t2, t1), - c.call(ftmPrefix + "_conjugate", t1, t1), - - // let mut t3 = cycolotomic_exp(t2); - c.call(prefix + "__cyclotomicExp_w0", t2, t3), - - // let mut t4 = cyclotomic_square(t3); - c.call(prefix + "__cyclotomicSquare", t3, t4), - - // let mut t5 = t1 * t3; - c.call(ftmPrefix + "_mul", t1, t3, t5), - - // t1 = cycolotomic_exp(t5); - c.call(prefix + "__cyclotomicExp_w0", t5, t1), - - // t0 = cycolotomic_exp(t1); - c.call(prefix + "__cyclotomicExp_w0", t1, t0), - - // let mut t6 = cycolotomic_exp(t0); - c.call(prefix + "__cyclotomicExp_w0", t0, t6), - - // t6 *= t4; - c.call(ftmPrefix + "_mul", t6, t4, t6), - - // t4 = cycolotomic_exp(t6); - c.call(prefix + "__cyclotomicExp_w0", t6, t4), - - // t5 = t5.conjugate(); - c.call(ftmPrefix + "_conjugate", t5, t5), - - // t4 *= t5 * t2; - c.call(ftmPrefix + "_mul", t4, t5, t4), - c.call(ftmPrefix + "_mul", t4, t2, t4), - - // t5 = t2.conjugate(); - c.call(ftmPrefix + "_conjugate", t2, t5), - - // t1 *= t2; - c.call(ftmPrefix + "_mul", t1, t2, t1), - - // t1 = t1.frobenius_map().frobenius_map().frobenius_map(); - c.call(ftmPrefix + "_frobeniusMap3", t1, t1), - - // t6 *= t5; - c.call(ftmPrefix + "_mul", t6, t5, t6), - - // t6 = t6.frobenius_map(); - c.call(ftmPrefix + "_frobeniusMap1", t6, t6), - - // t3 *= t0; - c.call(ftmPrefix + "_mul", t3, t0, t3), - - // t3 = t3.frobenius_map().frobenius_map(); - c.call(ftmPrefix + "_frobeniusMap2", t3, t3), - - // t3 *= t1; - c.call(ftmPrefix + "_mul", t3, t1, t3), - - // t3 *= t6; - c.call(ftmPrefix + "_mul", t3, t6, t3), - - // f = t3 * t4; - c.call(ftmPrefix + "_mul", t3, t4, res), - - ); - } - - - function buildFinalExponentiationOld() { - const f = module.addFunction(prefix+ "_finalExponentiationOld"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const exponent = bigInt("322277361516934140462891564586510139908379969514828494218366688025288661041104682794998680497580008899973249814104447692778988208376779573819485263026159588510513834876303014016798809919343532899164848730280942609956670917565618115867287399623286813270357901731510188149934363360381614501334086825442271920079363289954510565375378443704372994881406797882676971082200626541916413184642520269678897559532260949334760604962086348898118982248842634379637598665468817769075878555493752214492790122785850202957575200176084204422751485957336465472324810982833638490904279282696134323072515220044451592646885410572234451732790590013479358343841220074174848221722017083597872017638514103174122784843925578370430843522959600095676285723737049438346544753168912974976791528535276317256904336520179281145394686565050419250614107803233314658825463117900250701199181529205942363159325765991819433914303908860460720581408201373164047773794825411011922305820065611121544561808414055302212057471395719432072209245600258134364584636810093520285711072578721435517884103526483832733289802426157301542744476740008494780363354305116978805620671467071400711358839553375340724899735460480144599782014906586543813292157922220645089192130209334926661588737007768565838519456601560804957985667880395221049249803753582637708560"); - - const pExponent = module.alloc(utils.bigInt2BytesLE( exponent, 544 )); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call(ftmPrefix + "_exp", c.getLocal("x"), c.i32_const(pExponent), c.i32_const(544), c.getLocal("r")), - ); - } - - - const pPreP = module.alloc(prePSize); - const pPreQ = module.alloc(preQSize); - - function buildPairingEquation(nPairings) { - - const f = module.addFunction(prefix+ "_pairingEq"+nPairings); - for (let i=0; i { - -const bigInt = __webpack_require__(2096); -const utils = __webpack_require__(2333); - -const buildF1m =__webpack_require__(75); -const buildF1 =__webpack_require__(8138); -const buildF2m =__webpack_require__(5420); -const buildF3m =__webpack_require__(7173); -const buildCurve =__webpack_require__(5904); -const buildFFT = __webpack_require__(3911); -const buildPol = __webpack_require__(2896); -const buildQAP = __webpack_require__(637); -const buildApplyKey = __webpack_require__(3320); - -module.exports = function buildBN128(module, _prefix) { - - const prefix = _prefix || "bn128"; - - if (module.modules[prefix]) return prefix; // already builded - - const q = bigInt("21888242871839275222246405745257275088696311157297823662689037894645226208583"); - const r = bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"); - - - const n64 = Math.floor((q.minus(1).bitLength() - 1)/64) +1; - const n8 = n64*8; - const frsize = n8; - const f1size = n8; - const f2size = f1size * 2; - const f6size = f1size * 6; - const ftsize = f1size * 12; - - const pr = module.alloc(utils.bigInt2BytesLE( r, frsize )); - - const f1mPrefix = buildF1m(module, q, "f1m"); - buildF1(module, r, "fr", "frm"); - - const pG1b = module.alloc(utils.bigInt2BytesLE( toMontgomery(bigInt(3)), f1size )); - const g1mPrefix = buildCurve(module, "g1m", "f1m", pG1b); - - buildFFT(module, "frm", "frm", "frm", "frm_mul"); - - buildPol(module, "pol", "frm"); - buildQAP(module, "qap", "frm"); - - const f2mPrefix = buildF2m(module, "f1m_neg", "f2m", "f1m"); - const pG2b = module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery(bigInt("19485874751759354771024239261021720505790618469301721065564631296452457478373")), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(bigInt("266929791119991161246907387137283842545076965332900288569378510910307636690")), f1size ) - ]); - const g2mPrefix = buildCurve(module, "g2m", "f2m", pG2b); - - - function buildGTimesFr(fnName, opMul) { - const f = module.addFunction(fnName); - f.addParam("pG", "i32"); - f.addParam("pFr", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - const AUX = c.i32_const(module.alloc(n8)); - - f.addCode( - c.call("frm_fromMontgomery", c.getLocal("pFr"), AUX), - c.call( - opMul, - c.getLocal("pG"), - AUX, - c.i32_const(n8), - c.getLocal("pr") - ) - ); - - module.exportFunction(fnName); - } - buildGTimesFr("g1m_timesFr", "g1m_timesScalar"); - buildFFT(module, "g1m", "g1m", "frm", "g1m_timesFr"); - - buildGTimesFr("g2m_timesFr", "g2m_timesScalar"); - buildFFT(module, "g2m", "g2m", "frm", "g2m_timesFr"); - - buildGTimesFr("g1m_timesFrAffine", "g1m_timesScalarAffine"); - buildGTimesFr("g2m_timesFrAffine", "g2m_timesScalarAffine"); - - buildApplyKey(module, "frm_batchApplyKey", "fmr", "frm", n8, n8, n8, "frm_mul"); - buildApplyKey(module, "g1m_batchApplyKey", "g1m", "frm", n8*3, n8*3, n8, "g1m_timesFr"); - buildApplyKey(module, "g1m_batchApplyKeyMixed", "g1m", "frm", n8*2, n8*3, n8, "g1m_timesFrAffine"); - buildApplyKey(module, "g2m_batchApplyKey", "g2m", "frm", n8*2*3, n8*3*2, n8, "g2m_timesFr"); - buildApplyKey(module, "g2m_batchApplyKeyMixed", "g2m", "frm", n8*2*2, n8*3*2, n8, "g2m_timesFrAffine"); - - function toMontgomery(a) { - return bigInt(a).times( bigInt.one.shiftLeft(f1size*8)).mod(q); - } - - const G1gen = [ - bigInt("1"), - bigInt("2"), - bigInt.one - ]; - - const pG1gen = module.alloc( - [ - ...utils.bigInt2BytesLE( toMontgomery(G1gen[0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G1gen[1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G1gen[2]), f1size ), - ] - ); - - const G1zero = [ - bigInt.zero, - bigInt.one, - bigInt.zero - ]; - - const pG1zero = module.alloc( - [ - ...utils.bigInt2BytesLE( toMontgomery(G1zero[0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G1zero[1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G1zero[2]), f1size ) - ] - ); - - const G2gen = [ - [ - bigInt("10857046999023057135944570762232829481370756359578518086990519993285655852781"), - bigInt("11559732032986387107991004021392285783925812861821192530917403151452391805634"), - ],[ - bigInt("8495653923123431417604973247489272438418190587263600148770280649306958101930"), - bigInt("4082367875863433681332203403145435568316851327593401208105741076214120093531"), - ],[ - bigInt.one, - bigInt.zero, - ] - ]; - - const pG2gen = module.alloc( - [ - ...utils.bigInt2BytesLE( toMontgomery(G2gen[0][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2gen[0][1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2gen[1][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2gen[1][1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2gen[2][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2gen[2][1]), f1size ), - ] - ); - - const G2zero = [ - [ - bigInt.zero, - bigInt.zero, - ],[ - bigInt.one, - bigInt.zero, - ],[ - bigInt.zero, - bigInt.zero, - ] - ]; - - const pG2zero = module.alloc( - [ - ...utils.bigInt2BytesLE( toMontgomery(G2zero[0][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2zero[0][1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2zero[1][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2zero[1][1]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2zero[2][0]), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(G2zero[2][1]), f1size ), - ] - ); - - const pOneT = module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery(1), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), - ]); - - const pNonResidueF6 = module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery(9), f1size ), - ...utils.bigInt2BytesLE( toMontgomery(1), f1size ), - ]); - - const pTwoInv = module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery( bigInt(2).modInv(q)), f1size ), - ...utils.bigInt2BytesLE( bigInt(0), f1size ) - ]); - - const pAltBn128Twist = pNonResidueF6; - - const pTwistCoefB = module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery("19485874751759354771024239261021720505790618469301721065564631296452457478373"), f1size ), - ...utils.bigInt2BytesLE( toMontgomery("266929791119991161246907387137283842545076965332900288569378510910307636690"), f1size ), - ]); - - function build_mulNR6() { - const f = module.addFunction(prefix + "_mulNR6"); - f.addParam("x", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call( - f2mPrefix + "_mul", - c.i32_const(pNonResidueF6), - c.getLocal("x"), - c.getLocal("pr") - ) - ); - } - build_mulNR6(); - - const f6mPrefix = buildF3m(module, prefix+"_mulNR6", "f6m", "f2m"); - - function build_mulNR12() { - const f = module.addFunction(prefix + "_mulNR12"); - f.addParam("x", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call( - f2mPrefix + "_mul", - c.i32_const(pNonResidueF6), - c.i32_add(c.getLocal("x"), c.i32_const(n8*4)), - c.getLocal("pr") - ), - c.call( - f2mPrefix + "_copy", - c.getLocal("x"), - c.i32_add(c.getLocal("pr"), c.i32_const(n8*2)), - ), - c.call( - f2mPrefix + "_copy", - c.i32_add(c.getLocal("x"), c.i32_const(n8*2)), - c.i32_add(c.getLocal("pr"), c.i32_const(n8*4)), - ) - ); - } - build_mulNR12(); - - const ftmPrefix = buildF2m(module, prefix+"_mulNR12", "ftm", f6mPrefix); - - - const ateLoopCount = bigInt("29793968203157093288"); - const ateLoopBitBytes = bits(ateLoopCount); - const pAteLoopBitBytes = module.alloc(ateLoopBitBytes); - const isLoopNegative = false; - - const ateCoefSize = 3 * f2size; - const ateNDblCoefs = ateLoopBitBytes.length-1; - const ateNAddCoefs = ateLoopBitBytes.reduce((acc, b) => acc + ( b!=0 ? 1 : 0) ,0); - const ateNCoefs = ateNAddCoefs + ateNDblCoefs + 1; - const prePSize = 3*2*n8; - const preQSize = 3*n8*2 + ateNCoefs*ateCoefSize; - const finalExpIsNegative = false; - - - module.modules[prefix] = { - n64: n64, - pG1gen: pG1gen, - pG1zero: pG1zero, - pG1b: pG1b, - pG2gen: pG2gen, - pG2zero: pG2zero, - pG2b: pG2b, - pq: module.modules["f1m"].pq, - pr: pr, - pOneT: pOneT, - prePSize: prePSize, - preQSize: preQSize, - r: r.toString(), - q: q.toString() - }; - - // console.log("PrePSize: " +prePSize); - // console.log("PreQSize: " +preQSize); - - const finalExpZ = bigInt("4965661367192848881"); - - function naf(n) { - let E = n; - const res = []; - while (E.gt(bigInt.zero)) { - if (E.isOdd()) { - const z = 2 - E.mod(4).toJSNumber(); - res.push( z ); - E = E.minus(z); - } else { - res.push( 0 ); - } - E = E.shiftRight(1); - } - return res; - } - - function bits(n) { - let E = n; - const res = []; - while (E.gt(bigInt.zero)) { - if (E.isOdd()) { - res.push( 1 ); - } else { - res.push( 0 ); - } - E = E.shiftRight(1); - } - return res; - } - - function buildPrepareG1() { - const f = module.addFunction(prefix+ "_prepareG1"); - f.addParam("pP", "i32"); - f.addParam("ppreP", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call(g1mPrefix + "_normalize", c.getLocal("pP"), c.getLocal("ppreP")), // TODO Remove if already in affine - ); - } - - function buildPrepAddStep() { - const f = module.addFunction(prefix+ "_prepAddStep"); - f.addParam("pQ", "i32"); - f.addParam("pR", "i32"); - f.addParam("pCoef", "i32"); - - const c = f.getCodeBuilder(); - - const X2 = c.getLocal("pQ"); - const Y2 = c.i32_add(c.getLocal("pQ"), c.i32_const(f2size)); - - const X1 = c.getLocal("pR"); - const Y1 = c.i32_add(c.getLocal("pR"), c.i32_const(f2size)); - const Z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*f2size)); - - const ELL_0 = c.getLocal("pCoef"); - const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); - const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); - - const D = ELL_VW; - const E = c.i32_const(module.alloc(f2size)); - const F = c.i32_const(module.alloc(f2size)); - const G = c.i32_const(module.alloc(f2size)); - const H = c.i32_const(module.alloc(f2size)); - const I = c.i32_const(module.alloc(f2size)); - const J = c.i32_const(module.alloc(f2size)); - const AUX = c.i32_const(module.alloc(f2size)); - - f.addCode( - // D = X1 - X2*Z1 - c.call(f2mPrefix + "_mul", X2, Z1, D), - c.call(f2mPrefix + "_sub", X1, D, D), - - // E = Y1 - Y2*Z1 - c.call(f2mPrefix + "_mul", Y2, Z1, E), - c.call(f2mPrefix + "_sub", Y1, E, E), - - // F = D^2 - c.call(f2mPrefix + "_square", D, F), - - // G = E^2 - c.call(f2mPrefix + "_square", E, G), - - // H = D*F - c.call(f2mPrefix + "_mul", D, F, H), - - // I = X1 * F - c.call(f2mPrefix + "_mul", X1, F, I), - - // J = H + Z1*G - (I+I) - c.call(f2mPrefix + "_add", I, I, AUX), - c.call(f2mPrefix + "_mul", Z1, G, J), - c.call(f2mPrefix + "_add", H, J, J), - c.call(f2mPrefix + "_sub", J, AUX, J), - - - // X3 (X1) = D*J - c.call(f2mPrefix + "_mul", D, J, X1), - - // Y3 (Y1) = E*(I-J)-(H*Y1) - c.call(f2mPrefix + "_mul", H, Y1, Y1), - c.call(f2mPrefix + "_sub", I, J, AUX), - c.call(f2mPrefix + "_mul", E, AUX, AUX), - c.call(f2mPrefix + "_sub", AUX, Y1, Y1), - - // Z3 (Z1) = Z1*H - c.call(f2mPrefix + "_mul", Z1, H, Z1), - - // ell_0 = xi * (E * X2 - D * Y2) - c.call(f2mPrefix + "_mul", D, Y2, AUX), - c.call(f2mPrefix + "_mul", E, X2, ELL_0), - c.call(f2mPrefix + "_sub", ELL_0, AUX, ELL_0), - c.call(f2mPrefix + "_mul", ELL_0, c.i32_const(pAltBn128Twist), ELL_0), - - - // ell_VV = - E (later: * xP) - c.call(f2mPrefix + "_neg", E, ELL_VV), - - // ell_VW = D (later: * yP ) - // Already assigned - - ); - } - - - - function buildPrepDoubleStep() { - const f = module.addFunction(prefix+ "_prepDblStep"); - f.addParam("pR", "i32"); - f.addParam("pCoef", "i32"); - - const c = f.getCodeBuilder(); - - const X1 = c.getLocal("pR"); - const Y1 = c.i32_add(c.getLocal("pR"), c.i32_const(f2size)); - const Z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*f2size)); - - const ELL_0 = c.getLocal("pCoef"); - const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); - const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); - - const A = c.i32_const(module.alloc(f2size)); - const B = c.i32_const(module.alloc(f2size)); - const C = c.i32_const(module.alloc(f2size)); - const D = c.i32_const(module.alloc(f2size)); - const E = c.i32_const(module.alloc(f2size)); - const F = c.i32_const(module.alloc(f2size)); - const G = c.i32_const(module.alloc(f2size)); - const H = c.i32_const(module.alloc(f2size)); - const I = c.i32_const(module.alloc(f2size)); - const J = c.i32_const(module.alloc(f2size)); - const E2 = c.i32_const(module.alloc(f2size)); - const AUX = c.i32_const(module.alloc(f2size)); - - f.addCode( - - // A = X1 * Y1 / 2 - c.call(f2mPrefix + "_mul", Y1, c.i32_const(pTwoInv), A), - c.call(f2mPrefix + "_mul", X1, A, A), - - // B = Y1^2 - c.call(f2mPrefix + "_square", Y1, B), - - // C = Z1^2 - c.call(f2mPrefix + "_square", Z1, C), - - // D = 3 * C - c.call(f2mPrefix + "_add", C, C, D), - c.call(f2mPrefix + "_add", D, C, D), - - // E = twist_b * D - c.call(f2mPrefix + "_mul", c.i32_const(pTwistCoefB), D, E), - - // F = 3 * E - c.call(f2mPrefix + "_add", E, E, F), - c.call(f2mPrefix + "_add", E, F, F), - - // G = (B+F)/2 - c.call(f2mPrefix + "_add", B, F, G), - c.call(f2mPrefix + "_mul", G, c.i32_const(pTwoInv), G), - - // H = (Y1+Z1)^2-(B+C) - c.call(f2mPrefix + "_add", B, C, AUX), - c.call(f2mPrefix + "_add", Y1, Z1, H), - c.call(f2mPrefix + "_square", H, H), - c.call(f2mPrefix + "_sub", H, AUX, H), - - // I = E-B - c.call(f2mPrefix + "_sub", E, B, I), - - // J = X1^2 - c.call(f2mPrefix + "_square", X1, J), - - // E_squared = E^2 - c.call(f2mPrefix + "_square", E, E2), - - // X3 (X1) = A * (B-F) - c.call(f2mPrefix + "_sub", B, F, AUX), - c.call(f2mPrefix + "_mul", A, AUX, X1), - - // Y3 (Y1) = G^2 - 3*E^2 - c.call(f2mPrefix + "_add", E2, E2, AUX), - c.call(f2mPrefix + "_add", E2, AUX, AUX), - c.call(f2mPrefix + "_square", G, Y1), - c.call(f2mPrefix + "_sub", Y1, AUX, Y1), - - // Z3 (Z1) = B * H - c.call(f2mPrefix + "_mul", B, H, Z1), - - // ell_0 = xi * I - c.call(f2mPrefix + "_mul", c.i32_const(pAltBn128Twist), I, ELL_0), - - // ell_VW = - H (later: * yP) - c.call(f2mPrefix + "_neg", H, ELL_VW), - - // ell_VV = 3*J (later: * xP) - c.call(f2mPrefix + "_add", J, J, ELL_VV), - c.call(f2mPrefix + "_add", J, ELL_VV, ELL_VV), - - ); - } - - function buildMulByQ() { - const f = module.addFunction(prefix + "_mulByQ"); - f.addParam("p1", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - const x = c.getLocal("p1"); - const y = c.i32_add(c.getLocal("p1"), c.i32_const(f2size)); - const z = c.i32_add(c.getLocal("p1"), c.i32_const(f2size*2)); - const x3 = c.getLocal("pr"); - const y3 = c.i32_add(c.getLocal("pr"), c.i32_const(f2size)); - const z3 = c.i32_add(c.getLocal("pr"), c.i32_const(f2size*2)); - - const MulByQX = c.i32_const(module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery("21575463638280843010398324269430826099269044274347216827212613867836435027261"), f1size ), - ...utils.bigInt2BytesLE( toMontgomery("10307601595873709700152284273816112264069230130616436755625194854815875713954"), f1size ), - ])); - - const MulByQY = c.i32_const(module.alloc([ - ...utils.bigInt2BytesLE( toMontgomery("2821565182194536844548159561693502659359617185244120367078079554186484126554"), f1size ), - ...utils.bigInt2BytesLE( toMontgomery("3505843767911556378687030309984248845540243509899259641013678093033130930403"), f1size ), - ])); - - f.addCode( - // The frobeniusMap(1) in this field, is the conjugate - c.call(f2mPrefix + "_conjugate", x, x3), - c.call(f2mPrefix + "_mul", MulByQX, x3, x3), - c.call(f2mPrefix + "_conjugate", y, y3), - c.call(f2mPrefix + "_mul", MulByQY, y3, y3), - c.call(f2mPrefix + "_conjugate", z, z3), - ); - } - - - function buildPrepareG2() { - buildMulByQ(); - const f = module.addFunction(prefix+ "_prepareG2"); - f.addParam("pQ", "i32"); - f.addParam("ppreQ", "i32"); - f.addLocal("pCoef", "i32"); - f.addLocal("i", "i32"); - - const c = f.getCodeBuilder(); - - const QX = c.getLocal("pQ"); - const QY = c.i32_add( c.getLocal("pQ"), c.i32_const(f2size)); - const QZ = c.i32_add( c.getLocal("pQ"), c.i32_const(f2size*2)); - - const pR = module.alloc(f2size*3); - const R = c.i32_const(pR); - const RX = c.i32_const(pR); - const RY = c.i32_const(pR+f2size); - const RZ = c.i32_const(pR+2*f2size); - - const cQX = c.i32_add( c.getLocal("ppreQ"), c.i32_const(0)); - const cQY = c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size)); - const cQZ = c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*2)); - - const pQ1 = module.alloc(f2size*3); - const Q1 = c.i32_const(pQ1); - - const pQ2 = module.alloc(f2size*3); - const Q2 = c.i32_const(pQ2); - const Q2X = c.i32_const(pQ2); - const Q2Y = c.i32_const(pQ2 + f2size); - const Q2Z = c.i32_const(pQ2 + f2size*2); - - f.addCode( - c.call(g2mPrefix + "_normalize", QX, cQX), // TODO Remove if already in affine - c.call(f2mPrefix + "_copy", cQX, RX), - c.call(f2mPrefix + "_copy", cQY, RY), - c.call(f2mPrefix + "_one", RZ), - ); - - f.addCode( - c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), - c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), - c.block(c.loop( - - c.call(prefix + "_prepDblStep", R, c.getLocal("pCoef")), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - c.if( - c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), - [ - ...c.call(prefix + "_prepAddStep", cQX, R, c.getLocal("pCoef")), - ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - ] - ), - c.br_if(1, c.i32_eqz ( c.getLocal("i") )), - c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - ); - - f.addCode( - c.call(prefix + "_mulByQ", cQX, Q1), - c.call(prefix + "_mulByQ", Q1, Q2) - ); - - if (isLoopNegative) { - f.addCode( - c.call(f2mPrefix + "_neg", RY, RY), - ); - } - - f.addCode( - c.call(f2mPrefix + "_neg", Q2Y, Q2Y), - - c.call(prefix + "_prepAddStep", Q1, R, c.getLocal("pCoef")), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - c.call(prefix + "_prepAddStep", Q2, R, c.getLocal("pCoef")), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - ); - } - - function buildMulBy024Old() { - const f = module.addFunction(prefix+ "__mulBy024Old"); - f.addParam("pEll0", "i32"); - f.addParam("pEllVW", "i32"); - f.addParam("pEllVV", "i32"); - f.addParam("pR", "i32"); // Result in F12 - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("pEll0"); - const x2 = c.getLocal("pEllVV"); - const x4 = c.getLocal("pEllVW"); - - const z0 = c.getLocal("pR"); - - const pAUX12 = module.alloc(ftsize); - const AUX12 = c.i32_const(pAUX12); - const AUX12_0 = c.i32_const(pAUX12); - const AUX12_2 = c.i32_const(pAUX12+f2size); - const AUX12_4 = c.i32_const(pAUX12+f2size*2); - const AUX12_6 = c.i32_const(pAUX12+f2size*3); - const AUX12_8 = c.i32_const(pAUX12+f2size*4); - const AUX12_10 = c.i32_const(pAUX12+f2size*5); - - f.addCode( - - c.call(f2mPrefix + "_copy", x0, AUX12_0), - c.call(f2mPrefix + "_zero", AUX12_2), - c.call(f2mPrefix + "_copy", x2, AUX12_4), - c.call(f2mPrefix + "_zero", AUX12_6), - c.call(f2mPrefix + "_copy", x4, AUX12_8), - c.call(f2mPrefix + "_zero", AUX12_10), - c.call(ftmPrefix + "_mul", AUX12, z0, z0), - ); - } - - function buildMulBy024() { - const f = module.addFunction(prefix+ "__mulBy024"); - f.addParam("pEll0", "i32"); - f.addParam("pEllVW", "i32"); - f.addParam("pEllVV", "i32"); - f.addParam("pR", "i32"); // Result in F12 - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("pEll0"); - const x2 = c.getLocal("pEllVV"); - const x4 = c.getLocal("pEllVW"); - - const z0 = c.getLocal("pR"); - const z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*n8)); - const z2 = c.i32_add(c.getLocal("pR"), c.i32_const(4*n8)); - const z3 = c.i32_add(c.getLocal("pR"), c.i32_const(6*n8)); - const z4 = c.i32_add(c.getLocal("pR"), c.i32_const(8*n8)); - const z5 = c.i32_add(c.getLocal("pR"), c.i32_const(10*n8)); - - const t0 = c.i32_const(module.alloc(f2size)); - const t1 = c.i32_const(module.alloc(f2size)); - const t2 = c.i32_const(module.alloc(f2size)); - const s0 = c.i32_const(module.alloc(f2size)); - const T3 = c.i32_const(module.alloc(f2size)); - const T4 = c.i32_const(module.alloc(f2size)); - const D0 = c.i32_const(module.alloc(f2size)); - const D2 = c.i32_const(module.alloc(f2size)); - const D4 = c.i32_const(module.alloc(f2size)); - const S1 = c.i32_const(module.alloc(f2size)); - const AUX = c.i32_const(module.alloc(f2size)); - - f.addCode( - - // D0 = z0 * x0; - c.call(f2mPrefix + "_mul", z0, x0, D0), - // D2 = z2 * x2; - c.call(f2mPrefix + "_mul", z2, x2, D2), - // D4 = z4 * x4; - c.call(f2mPrefix + "_mul", z4, x4, D4), - // t2 = z0 + z4; - c.call(f2mPrefix + "_add", z0, z4, t2), - // t1 = z0 + z2; - c.call(f2mPrefix + "_add", z0, z2, t1), - // s0 = z1 + z3 + z5; - c.call(f2mPrefix + "_add", z1, z3, s0), - c.call(f2mPrefix + "_add", s0, z5, s0), - - - // For z.a_.a_ = z0. - // S1 = z1 * x2; - c.call(f2mPrefix + "_mul", z1, x2, S1), - // T3 = S1 + D4; - c.call(f2mPrefix + "_add", S1, D4, T3), - // T4 = my_Fp6::non_residue * T3 + D0; - c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), - c.call(f2mPrefix + "_add", T4, D0, z0), - // z0 = T4; - - // For z.a_.b_ = z1 - // T3 = z5 * x4; - c.call(f2mPrefix + "_mul", z5, x4, T3), - // S1 = S1 + T3; - c.call(f2mPrefix + "_add", S1, T3, S1), - // T3 = T3 + D2; - c.call(f2mPrefix + "_add", T3, D2, T3), - // T4 = my_Fp6::non_residue * T3; - c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), - // T3 = z1 * x0; - c.call(f2mPrefix + "_mul", z1, x0, T3), - // S1 = S1 + T3; - c.call(f2mPrefix + "_add", S1, T3, S1), - // T4 = T4 + T3; - c.call(f2mPrefix + "_add", T4, T3, z1), - // z1 = T4; - - - - // For z.a_.c_ = z2 - // t0 = x0 + x2; - c.call(f2mPrefix + "_add", x0, x2, t0), - // T3 = t1 * t0 - D0 - D2; - c.call(f2mPrefix + "_mul", t1, t0, T3), - c.call(f2mPrefix + "_add", D0, D2, AUX), - c.call(f2mPrefix + "_sub", T3, AUX, T3), - // T4 = z3 * x4; - c.call(f2mPrefix + "_mul", z3, x4, T4), - // S1 = S1 + T4; - c.call(f2mPrefix + "_add", S1, T4, S1), - - - // For z.b_.a_ = z3 (z3 needs z2) - // t0 = z2 + z4; - c.call(f2mPrefix + "_add", z2, z4, t0), - // T3 = T3 + T4; - // z2 = T3; - c.call(f2mPrefix + "_add", T3, T4, z2), - // t1 = x2 + x4; - c.call(f2mPrefix + "_add", x2, x4, t1), - // T3 = t0 * t1 - D2 - D4; - c.call(f2mPrefix + "_mul", t1, t0, T3), - c.call(f2mPrefix + "_add", D2, D4, AUX), - c.call(f2mPrefix + "_sub", T3, AUX, T3), - // T4 = my_Fp6::non_residue * T3; - c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), - // T3 = z3 * x0; - c.call(f2mPrefix + "_mul", z3, x0, T3), - // S1 = S1 + T3; - c.call(f2mPrefix + "_add", S1, T3, S1), - // T4 = T4 + T3; - c.call(f2mPrefix + "_add", T4, T3, z3), - // z3 = T4; - - // For z.b_.b_ = z4 - // T3 = z5 * x2; - c.call(f2mPrefix + "_mul", z5, x2, T3), - // S1 = S1 + T3; - c.call(f2mPrefix + "_add", S1, T3, S1), - // T4 = my_Fp6::non_residue * T3; - c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), - // t0 = x0 + x4; - c.call(f2mPrefix + "_add", x0, x4, t0), - // T3 = t2 * t0 - D0 - D4; - c.call(f2mPrefix + "_mul", t2, t0, T3), - c.call(f2mPrefix + "_add", D0, D4, AUX), - c.call(f2mPrefix + "_sub", T3, AUX, T3), - // T4 = T4 + T3; - c.call(f2mPrefix + "_add", T4, T3, z4), - // z4 = T4; - - // For z.b_.c_ = z5. - // t0 = x0 + x2 + x4; - c.call(f2mPrefix + "_add", x0, x2, t0), - c.call(f2mPrefix + "_add", t0, x4, t0), - // T3 = s0 * t0 - S1; - c.call(f2mPrefix + "_mul", s0, t0, T3), - c.call(f2mPrefix + "_sub", T3, S1, z5), - // z5 = T3; - - ); - } - - - function buildMillerLoop() { - const f = module.addFunction(prefix+ "_millerLoop"); - f.addParam("ppreP", "i32"); - f.addParam("ppreQ", "i32"); - f.addParam("r", "i32"); - f.addLocal("pCoef", "i32"); - f.addLocal("i", "i32"); - - const c = f.getCodeBuilder(); - - const preP_PX = c.getLocal("ppreP"); - const preP_PY = c.i32_add(c.getLocal("ppreP"), c.i32_const(f1size)); - - const ELL_0 = c.getLocal("pCoef"); - const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); - const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); - - - const pVW = module.alloc(f2size); - const VW = c.i32_const(pVW); - const pVV = module.alloc(f2size); - const VV = c.i32_const(pVV); - - const F = c.getLocal("r"); - - - f.addCode( - c.call(ftmPrefix + "_one", F), - - c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), - - c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), - c.block(c.loop( - - - c.call(ftmPrefix + "_square", F, F), - - c.call(f2mPrefix + "_mul1", ELL_VW,preP_PY, VW), - c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), - c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - c.if( - c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), - [ - ...c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), - ...c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), - - ...c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), - ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - ] - ), - c.br_if(1, c.i32_eqz ( c.getLocal("i") )), - c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - - ); - - if (isLoopNegative) { - f.addCode( - c.call(ftmPrefix + "_inverse", F, F), - ); - } - - f.addCode( - c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), - c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), - c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), - c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), - c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), - c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), - - ); - - } - - - function buildFrobeniusMap(n) { - const F12 = [ - [ - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - ], - [ - [bigInt("1"), bigInt("0")], - [bigInt("8376118865763821496583973867626364092589906065868298776909617916018768340080"), bigInt("16469823323077808223889137241176536799009286646108169935659301613961712198316")], - [bigInt("21888242871839275220042445260109153167277707414472061641714758635765020556617"), bigInt("0")], - [bigInt("11697423496358154304825782922584725312912383441159505038794027105778954184319"), bigInt("303847389135065887422783454877609941456349188919719272345083954437860409601")], - [bigInt("21888242871839275220042445260109153167277707414472061641714758635765020556616"), bigInt("0")], - [bigInt("3321304630594332808241809054958361220322477375291206261884409189760185844239"), bigInt("5722266937896532885780051958958348231143373700109372999374820235121374419868")], - [bigInt("21888242871839275222246405745257275088696311157297823662689037894645226208582"), bigInt("0")], - [bigInt("13512124006075453725662431877630910996106405091429524885779419978626457868503"), bigInt("5418419548761466998357268504080738289687024511189653727029736280683514010267")], - [bigInt("2203960485148121921418603742825762020974279258880205651966"), bigInt("0")], - [bigInt("10190819375481120917420622822672549775783927716138318623895010788866272024264"), bigInt("21584395482704209334823622290379665147239961968378104390343953940207365798982")], - [bigInt("2203960485148121921418603742825762020974279258880205651967"), bigInt("0")], - [bigInt("18566938241244942414004596690298913868373833782006617400804628704885040364344"), bigInt("16165975933942742336466353786298926857552937457188450663314217659523851788715")], - ] - ]; - - const F6 = [ - [ - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - [bigInt("1"), bigInt("0")], - ], - [ - [bigInt("1"), bigInt("0")], - [bigInt("21575463638280843010398324269430826099269044274347216827212613867836435027261"), bigInt("10307601595873709700152284273816112264069230130616436755625194854815875713954")], - [bigInt("21888242871839275220042445260109153167277707414472061641714758635765020556616"), bigInt("0")], - [bigInt("3772000881919853776433695186713858239009073593817195771773381919316419345261"), bigInt("2236595495967245188281701248203181795121068902605861227855261137820944008926")], - [bigInt("2203960485148121921418603742825762020974279258880205651966"), bigInt("0")], - [bigInt("18429021223477853657660792034369865839114504446431234726392080002137598044644"), bigInt("9344045779998320333812420223237981029506012124075525679208581902008406485703")], - ], - [ - [bigInt("1"), bigInt("0")], - [bigInt("2581911344467009335267311115468803099551665605076196740867805258568234346338"), bigInt("19937756971775647987995932169929341994314640652964949448313374472400716661030")], - [bigInt("2203960485148121921418603742825762020974279258880205651966"), bigInt("0")], - [bigInt("5324479202449903542726783395506214481928257762400643279780343368557297135718"), bigInt("16208900380737693084919495127334387981393726419856888799917914180988844123039")], - [bigInt("21888242871839275220042445260109153167277707414472061641714758635765020556616"), bigInt("0")], - [bigInt("13981852324922362344252311234282257507216387789820983642040889267519694726527"), bigInt("7629828391165209371577384193250820201684255241773809077146787135900891633097")], - ] - ]; - - const f = module.addFunction(prefix+ "__frobeniusMap"+n); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - for (let i=0; i<6; i++) { - const X = (i==0) ? c.getLocal("x") : c.i32_add(c.getLocal("x"), c.i32_const(i*f2size)); - const Xc0 = X; - const Xc1 = c.i32_add(c.getLocal("x"), c.i32_const(i*f2size + f1size)); - const R = (i==0) ? c.getLocal("r") : c.i32_add(c.getLocal("r"), c.i32_const(i*f2size)); - const Rc0 = R; - const Rc1 = c.i32_add(c.getLocal("r"), c.i32_const(i*f2size + f1size)); - const coef = mul2(F12[Math.floor(i/3)][n%12] , F6[i%3][n%6]); - const pCoef = module.alloc([ - ...utils.bigInt2BytesLE(toMontgomery(coef[0]), 32), - ...utils.bigInt2BytesLE(toMontgomery(coef[1]), 32), - ]); - if (n%2 == 1) { - f.addCode( - c.call(f1mPrefix + "_copy", Xc0, Rc0), - c.call(f1mPrefix + "_neg", Xc1, Rc1), - c.call(f2mPrefix + "_mul", R, c.i32_const(pCoef), R), - ); - } else { - f.addCode(c.call(f2mPrefix + "_mul", X, c.i32_const(pCoef), R)); - } - } - - function mul2(a, b) { - const ac0 = bigInt(a[0]); - const ac1 = bigInt(a[1]); - const bc0 = bigInt(b[0]); - const bc1 = bigInt(b[1]); - const res = [ - ac0.times(bc0).minus( ac1.times(bc1) ).mod(q), - ac0.times(bc1).add( ac1.times(bc0) ).mod(q), - ]; - if (res[0].isNegative()) res[0] = res[0].add(q); - return res; - } - - } - - - - function buildFinalExponentiationFirstChunk() { - - const f = module.addFunction(prefix+ "__finalExponentiationFirstChunk"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const elt = c.getLocal("x"); - const eltC0 = elt; - const eltC1 = c.i32_add(elt, c.i32_const(n8*6)); - const r = c.getLocal("r"); - const pA = module.alloc(ftsize); - const A = c.i32_const(pA); - const Ac0 = A; - const Ac1 = c.i32_const(pA + n8*6); - const B = c.i32_const(module.alloc(ftsize)); - const C = c.i32_const(module.alloc(ftsize)); - const D = c.i32_const(module.alloc(ftsize)); - - f.addCode( - // const alt_bn128_Fq12 A = alt_bn128_Fq12(elt.c0,-elt.c1); - c.call(f6mPrefix + "_copy", eltC0, Ac0), - c.call(f6mPrefix + "_neg", eltC1, Ac1), - - // const alt_bn128_Fq12 B = elt.inverse(); - c.call(ftmPrefix + "_inverse", elt, B), - - // const alt_bn128_Fq12 C = A * B; - c.call(ftmPrefix + "_mul", A, B, C), - // const alt_bn128_Fq12 D = C.Frobenius_map(2); - c.call(prefix + "__frobeniusMap2", C, D), - // const alt_bn128_Fq12 result = D * C; - c.call(ftmPrefix + "_mul", C, D, r), - ); - } - - function buildCyclotomicSquare() { - const f = module.addFunction(prefix+ "__cyclotomicSquare"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x4 = c.i32_add(c.getLocal("x"), c.i32_const(f2size)); - const x3 = c.i32_add(c.getLocal("x"), c.i32_const(2*f2size)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(3*f2size)); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(4*f2size)); - const x5 = c.i32_add(c.getLocal("x"), c.i32_const(5*f2size)); - - const r0 = c.getLocal("r"); - const r4 = c.i32_add(c.getLocal("r"), c.i32_const(f2size)); - const r3 = c.i32_add(c.getLocal("r"), c.i32_const(2*f2size)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(3*f2size)); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(4*f2size)); - const r5 = c.i32_add(c.getLocal("r"), c.i32_const(5*f2size)); - - const t0 = c.i32_const(module.alloc(f2size)); - const t1 = c.i32_const(module.alloc(f2size)); - const t2 = c.i32_const(module.alloc(f2size)); - const t3 = c.i32_const(module.alloc(f2size)); - const t4 = c.i32_const(module.alloc(f2size)); - const t5 = c.i32_const(module.alloc(f2size)); - const tmp = c.i32_const(module.alloc(f2size)); - const AUX = c.i32_const(module.alloc(f2size)); - - - f.addCode( - -// c.call(ftmPrefix + "_square", x0, r0), - - // // t0 + t1*y = (z0 + z1*y)^2 = a^2 - // tmp = z0 * z1; - // t0 = (z0 + z1) * (z0 + my_Fp6::non_residue * z1) - tmp - my_Fp6::non_residue * tmp; - // t1 = tmp + tmp; - c.call(f2mPrefix + "_mul", x0, x1, tmp), - c.call(f2mPrefix + "_mul", x1, c.i32_const(pNonResidueF6), t0), - c.call(f2mPrefix + "_add", x0, t0, t0), - c.call(f2mPrefix + "_add", x0, x1, AUX), - c.call(f2mPrefix + "_mul", AUX, t0, t0), - c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), - c.call(f2mPrefix + "_add", tmp, AUX, AUX), - c.call(f2mPrefix + "_sub", t0, AUX, t0), - c.call(f2mPrefix + "_add", tmp, tmp, t1), - - // // t2 + t3*y = (z2 + z3*y)^2 = b^2 - // tmp = z2 * z3; - // t2 = (z2 + z3) * (z2 + my_Fp6::non_residue * z3) - tmp - my_Fp6::non_residue * tmp; - // t3 = tmp + tmp; - c.call(f2mPrefix + "_mul", x2, x3, tmp), - c.call(f2mPrefix + "_mul", x3, c.i32_const(pNonResidueF6), t2), - c.call(f2mPrefix + "_add", x2, t2, t2), - c.call(f2mPrefix + "_add", x2, x3, AUX), - c.call(f2mPrefix + "_mul", AUX, t2, t2), - c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), - c.call(f2mPrefix + "_add", tmp, AUX, AUX), - c.call(f2mPrefix + "_sub", t2, AUX, t2), - c.call(f2mPrefix + "_add", tmp, tmp, t3), - - // // t4 + t5*y = (z4 + z5*y)^2 = c^2 - // tmp = z4 * z5; - // t4 = (z4 + z5) * (z4 + my_Fp6::non_residue * z5) - tmp - my_Fp6::non_residue * tmp; - // t5 = tmp + tmp; - c.call(f2mPrefix + "_mul", x4, x5, tmp), - c.call(f2mPrefix + "_mul", x5, c.i32_const(pNonResidueF6), t4), - c.call(f2mPrefix + "_add", x4, t4, t4), - c.call(f2mPrefix + "_add", x4, x5, AUX), - c.call(f2mPrefix + "_mul", AUX, t4, t4), - c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), - c.call(f2mPrefix + "_add", tmp, AUX, AUX), - c.call(f2mPrefix + "_sub", t4, AUX, t4), - c.call(f2mPrefix + "_add", tmp, tmp, t5), - - // For A - // z0 = 3 * t0 - 2 * z0 - c.call(f2mPrefix + "_sub", t0, x0, r0), - c.call(f2mPrefix + "_add", r0, r0, r0), - c.call(f2mPrefix + "_add", t0, r0, r0), - // z1 = 3 * t1 + 2 * z1 - c.call(f2mPrefix + "_add", t1, x1, r1), - c.call(f2mPrefix + "_add", r1, r1, r1), - c.call(f2mPrefix + "_add", t1, r1, r1), - - // For B - // z2 = 3 * (xi * t5) + 2 * z2 - c.call(f2mPrefix + "_mul", t5, c.i32_const(pAltBn128Twist), AUX), - c.call(f2mPrefix + "_add", AUX, x2, r2), - c.call(f2mPrefix + "_add", r2, r2, r2), - c.call(f2mPrefix + "_add", AUX, r2, r2), - // z3 = 3 * t4 - 2 * z3 - c.call(f2mPrefix + "_sub", t4, x3, r3), - c.call(f2mPrefix + "_add", r3, r3, r3), - c.call(f2mPrefix + "_add", t4, r3, r3), - - // For C - // z4 = 3 * t2 - 2 * z4 - c.call(f2mPrefix + "_sub", t2, x4, r4), - c.call(f2mPrefix + "_add", r4, r4, r4), - c.call(f2mPrefix + "_add", t2, r4, r4), - // z5 = 3 * t3 + 2 * z5 - c.call(f2mPrefix + "_add", t3, x5, r5), - c.call(f2mPrefix + "_add", r5, r5, r5), - c.call(f2mPrefix + "_add", t3, r5, r5), - - ); - } - - - function buildCyclotomicExp(exponent, fnName) { - const exponentNafBytes = naf(exponent).map( (b) => (b==-1 ? 0xFF: b) ); - const pExponentNafBytes = module.alloc(exponentNafBytes); - const pExponent = module.alloc(utils.bigInt2BytesLE(exponent, 32)); - - const f = module.addFunction(prefix+ "__cyclotomicExp_"+fnName); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - f.addLocal("bit", "i32"); - f.addLocal("i", "i32"); - - const c = f.getCodeBuilder(); - - const x = c.getLocal("x"); - - const res = c.getLocal("r"); - - const inverse = c.i32_const(module.alloc(ftsize)); - - - f.addCode( -// c.call(ftmPrefix + "_exp", x, c.i32_const(pExponent), c.i32_const(32), res), - - c.call(ftmPrefix + "_conjugate", x, inverse), - c.call(ftmPrefix + "_one", res), - - c.if( - c.teeLocal("bit", c.i32_load8_s(c.i32_const(exponentNafBytes.length-1), pExponentNafBytes)), - c.if( - c.i32_eq( - c.getLocal("bit"), - c.i32_const(1) - ), - c.call(ftmPrefix + "_mul", res, x, res), - c.call(ftmPrefix + "_mul", res, inverse, res), - ) - ), - - c.setLocal("i", c.i32_const(exponentNafBytes.length-2)), - c.block(c.loop( -// c.call(ftmPrefix + "_square", res, res), - c.call(prefix + "__cyclotomicSquare", res, res), - c.if( - c.teeLocal("bit", c.i32_load8_s(c.getLocal("i"), pExponentNafBytes)), - c.if( - c.i32_eq( - c.getLocal("bit"), - c.i32_const(1) - ), - c.call(ftmPrefix + "_mul", res, x, res), - c.call(ftmPrefix + "_mul", res, inverse, res), - ) - ), - c.br_if(1, c.i32_eqz ( c.getLocal("i") )), - c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - ); - } - - - - function buildFinalExponentiationLastChunk() { - buildCyclotomicSquare(); - buildCyclotomicExp(finalExpZ, "w0"); - - const f = module.addFunction(prefix+ "__finalExponentiationLastChunk"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const elt = c.getLocal("x"); - const result = c.getLocal("r"); - const A = c.i32_const(module.alloc(ftsize)); - const B = c.i32_const(module.alloc(ftsize)); - const C = c.i32_const(module.alloc(ftsize)); - const D = c.i32_const(module.alloc(ftsize)); - const E = c.i32_const(module.alloc(ftsize)); - const F = c.i32_const(module.alloc(ftsize)); - const G = c.i32_const(module.alloc(ftsize)); - const H = c.i32_const(module.alloc(ftsize)); - const I = c.i32_const(module.alloc(ftsize)); - const J = c.i32_const(module.alloc(ftsize)); - const K = c.i32_const(module.alloc(ftsize)); - const L = c.i32_const(module.alloc(ftsize)); - const M = c.i32_const(module.alloc(ftsize)); - const N = c.i32_const(module.alloc(ftsize)); - const O = c.i32_const(module.alloc(ftsize)); - const P = c.i32_const(module.alloc(ftsize)); - const Q = c.i32_const(module.alloc(ftsize)); - const R = c.i32_const(module.alloc(ftsize)); - const S = c.i32_const(module.alloc(ftsize)); - const T = c.i32_const(module.alloc(ftsize)); - const U = c.i32_const(module.alloc(ftsize)); - - f.addCode( - - - // A = exp_by_neg_z(elt) // = elt^(-z) - c.call(prefix + "__cyclotomicExp_w0", elt, A), - finalExpIsNegative ? [] : c.call(ftmPrefix + "_conjugate", A, A), - // B = A^2 // = elt^(-2*z) - c.call(prefix + "__cyclotomicSquare", A, B), - // C = B^2 // = elt^(-4*z) - c.call(prefix + "__cyclotomicSquare", B, C), - // D = C * B // = elt^(-6*z) - c.call(ftmPrefix + "_mul", C, B, D), - // E = exp_by_neg_z(D) // = elt^(6*z^2) - c.call(prefix + "__cyclotomicExp_w0", D, E), - finalExpIsNegative ? [] : c.call(ftmPrefix + "_conjugate", E, E), - // F = E^2 // = elt^(12*z^2) - c.call(prefix + "__cyclotomicSquare", E, F), - // G = epx_by_neg_z(F) // = elt^(-12*z^3) - c.call(prefix + "__cyclotomicExp_w0", F, G), - finalExpIsNegative ? [] : c.call(ftmPrefix + "_conjugate", G, G), - // H = conj(D) // = elt^(6*z) - c.call(ftmPrefix + "_conjugate", D, H), - // I = conj(G) // = elt^(12*z^3) - c.call(ftmPrefix + "_conjugate", G, I), - // J = I * E // = elt^(12*z^3 + 6*z^2) - c.call(ftmPrefix + "_mul", I, E, J), - // K = J * H // = elt^(12*z^3 + 6*z^2 + 6*z) - c.call(ftmPrefix + "_mul", J, H, K), - // L = K * B // = elt^(12*z^3 + 6*z^2 + 4*z) - c.call(ftmPrefix + "_mul", K, B, L), - // M = K * E // = elt^(12*z^3 + 12*z^2 + 6*z) - c.call(ftmPrefix + "_mul", K, E, M), - - // N = M * elt // = elt^(12*z^3 + 12*z^2 + 6*z + 1) - c.call(ftmPrefix + "_mul", M, elt, N), - - // O = L.Frobenius_map(1) // = elt^(q*(12*z^3 + 6*z^2 + 4*z)) - c.call(prefix + "__frobeniusMap1", L, O), - // P = O * N // = elt^(q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) - c.call(ftmPrefix + "_mul", O, N, P), - // Q = K.Frobenius_map(2) // = elt^(q^2 * (12*z^3 + 6*z^2 + 6*z)) - c.call(prefix + "__frobeniusMap2", K, Q), - // R = Q * P // = elt^(q^2 * (12*z^3 + 6*z^2 + 6*z) + q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) - c.call(ftmPrefix + "_mul", Q, P, R), - // S = conj(elt) // = elt^(-1) - c.call(ftmPrefix + "_conjugate", elt, S), - // T = S * L // = elt^(12*z^3 + 6*z^2 + 4*z - 1) - c.call(ftmPrefix + "_mul", S, L, T), - // U = T.Frobenius_map(3) // = elt^(q^3(12*z^3 + 6*z^2 + 4*z - 1)) - c.call(prefix + "__frobeniusMap3", T, U), - // V = U * R // = elt^(q^3(12*z^3 + 6*z^2 + 4*z - 1) + q^2 * (12*z^3 + 6*z^2 + 6*z) + q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) - c.call(ftmPrefix + "_mul", U, R, result), - // result = V - ); - } - - - function buildFinalExponentiation() { - buildFinalExponentiationFirstChunk(); - buildFinalExponentiationLastChunk(); - const f = module.addFunction(prefix+ "_finalExponentiation"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const elt = c.getLocal("x"); - const result = c.getLocal("r"); - const eltToFirstChunk = c.i32_const(module.alloc(ftsize)); - - f.addCode( - c.call(prefix + "__finalExponentiationFirstChunk", elt, eltToFirstChunk ), - c.call(prefix + "__finalExponentiationLastChunk", eltToFirstChunk, result ) - ); - } - - - function buildFinalExponentiationOld() { - const f = module.addFunction(prefix+ "_finalExponentiationOld"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const exponent = bigInt("552484233613224096312617126783173147097382103762957654188882734314196910839907541213974502761540629817009608548654680343627701153829446747810907373256841551006201639677726139946029199968412598804882391702273019083653272047566316584365559776493027495458238373902875937659943504873220554161550525926302303331747463515644711876653177129578303191095900909191624817826566688241804408081892785725967931714097716709526092261278071952560171111444072049229123565057483750161460024353346284167282452756217662335528813519139808291170539072125381230815729071544861602750936964829313608137325426383735122175229541155376346436093930287402089517426973178917569713384748081827255472576937471496195752727188261435633271238710131736096299798168852925540549342330775279877006784354801422249722573783561685179618816480037695005515426162362431072245638324744480"); - - const pExponent = module.alloc(utils.bigInt2BytesLE( exponent, 352 )); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call(ftmPrefix + "_exp", c.getLocal("x"), c.i32_const(pExponent), c.i32_const(352), c.getLocal("r")), - ); - } - - - - - const pPreP = module.alloc(prePSize); - const pPreQ = module.alloc(preQSize); - - function buildPairingEquation(nPairings) { - - const f = module.addFunction(prefix+ "_pairingEq"+nPairings); - for (let i=0; i { - - - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -module.exports = function buildApplyKey(module, fnName, gPrefix, frPrefix, sizeGIn, sizeGOut, sizeF, opGtimesF) { +var build_timesscalar = function buildTimesScalar(module, fnName, elementLen, opAB, opAA, opCopy, opInit) { const f = module.addFunction(fnName); - f.addParam("pIn", "i32"); - f.addParam("n", "i32"); - f.addParam("pFirst", "i32"); - f.addParam("pInc", "i32"); - f.addParam("pOut", "i32"); - f.addLocal("pOldFree", "i32"); + f.addParam("base", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLength", "i32"); + f.addParam("r", "i32"); f.addLocal("i", "i32"); - f.addLocal("pFrom", "i32"); - f.addLocal("pTo", "i32"); + f.addLocal("b", "i32"); const c = f.getCodeBuilder(); - const t = c.i32_const(module.alloc(sizeF)); + const aux = c.i32_const(module.alloc(elementLen)); f.addCode( - c.setLocal("pFrom", c.getLocal("pIn")), - c.setLocal("pTo", c.getLocal("pOut")), - ); - - // t = first - f.addCode( - c.call( - frPrefix + "_copy", - c.getLocal("pFirst"), - t + c.if( + c.i32_eqz(c.getLocal("scalarLength")), + [ + ...c.call(opInit, c.getLocal("r")), + ...c.ret([]) + ] ) ); - f.addCode( - c.setLocal("i", c.i32_const(0)), - c.block(c.loop( - c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), + f.addCode(c.call(opCopy, c.getLocal("base"), aux)); + f.addCode(c.call(opInit, c.getLocal("r"))); + f.addCode(c.setLocal("i", c.getLocal("scalarLength"))); + f.addCode(c.block(c.loop( + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - c.call( - opGtimesF, - c.getLocal("pFrom"), - t, - c.getLocal("pTo") - ), - c.setLocal("pFrom", c.i32_add(c.getLocal("pFrom"), c.i32_const(sizeGIn))), - c.setLocal("pTo", c.i32_add(c.getLocal("pTo"), c.i32_const(sizeGOut))), + c.setLocal( + "b", + c.i32_load8_u( + c.i32_add( + c.getLocal("scalar"), + c.getLocal("i") + ) + ) + ), + ...innerLoop(), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.br(0) + ))); - // t = t* inc - c.call( - frPrefix + "_mul", - t, - c.getLocal("pInc"), - t - ), - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )) - ); - module.exportFunction(fnName); + function innerLoop() { + const code = []; + for (let i=0; i<8; i++) { + code.push( + ...c.call(opAA, c.getLocal("r"), c.getLocal("r")), + ...c.if( + c.i32_ge_u( c.getLocal("b"), c.i32_const(0x80 >> i)), + [ + ...c.setLocal( + "b", + c.i32_sub( + c.getLocal("b"), + c.i32_const(0x80 >> i) + ) + ), + ...c.call(opAB, c.getLocal("r"),aux, c.getLocal("r")) + ] + ) + ); + } + return code; + } }; +var build_batchinverse = buildBatchInverse$3; -/***/ }), - -/***/ 9440: -/***/ ((module) => { - - - -module.exports = buildBatchConvertion; - -function buildBatchConvertion(module, fnName, internalFnName, sizeIn, sizeOut, reverse) { - if (typeof reverse === "undefined") { - // Set the reverse in a way that allows to use the same buffer as in/out. - if (sizeIn < sizeOut) { - reverse = true; - } else { - reverse = false; - } - } - - const f = module.addFunction(fnName); - f.addParam("pIn", "i32"); - f.addParam("n", "i32"); - f.addParam("pOut", "i32"); - f.addLocal("i", "i32"); - f.addLocal("itIn", "i32"); - f.addLocal("itOut", "i32"); - - const c = f.getCodeBuilder(); - - if (reverse) { - f.addCode( - c.setLocal("itIn", - c.i32_add( - c.getLocal("pIn"), - c.i32_mul( - c.i32_sub( - c.getLocal("n"), - c.i32_const(1) - ), - c.i32_const(sizeIn) - ) - ) - ), - c.setLocal("itOut", - c.i32_add( - c.getLocal("pOut"), - c.i32_mul( - c.i32_sub( - c.getLocal("n"), - c.i32_const(1) - ), - c.i32_const(sizeOut) - ) - ) - ), - c.setLocal("i", c.i32_const(0)), - c.block(c.loop( - c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), - - c.call(internalFnName, c.getLocal("itIn"), c.getLocal("itOut")), - - c.setLocal("itIn", c.i32_sub(c.getLocal("itIn"), c.i32_const(sizeIn))), - c.setLocal("itOut", c.i32_sub(c.getLocal("itOut"), c.i32_const(sizeOut))), - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )), - ); - } else { - f.addCode( - c.setLocal("itIn", c.getLocal("pIn")), - c.setLocal("itOut", c.getLocal("pOut")), - c.setLocal("i", c.i32_const(0)), - c.block(c.loop( - c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), - - c.call(internalFnName, c.getLocal("itIn"), c.getLocal("itOut")), - - c.setLocal("itIn", c.i32_add(c.getLocal("itIn"), c.i32_const(sizeIn))), - c.setLocal("itOut", c.i32_add(c.getLocal("itOut"), c.i32_const(sizeOut))), - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )), - ); - } -} - - -/***/ }), - -/***/ 8163: -/***/ ((module) => { - - -module.exports = buildBatchInverse; - -function buildBatchInverse(module, prefix) { +function buildBatchInverse$3(module, prefix) { const n8 = module.modules[prefix].n64*8; @@ -62053,17 +59415,88 @@ function buildBatchInverse(module, prefix) { } +var build_batchconvertion = buildBatchConvertion$3; -/***/ }), +function buildBatchConvertion$3(module, fnName, internalFnName, sizeIn, sizeOut, reverse) { + if (typeof reverse === "undefined") { + // Set the reverse in a way that allows to use the same buffer as in/out. + if (sizeIn < sizeOut) { + reverse = true; + } else { + reverse = false; + } + } -/***/ 4948: -/***/ ((module) => { + const f = module.addFunction(fnName); + f.addParam("pIn", "i32"); + f.addParam("n", "i32"); + f.addParam("pOut", "i32"); + f.addLocal("i", "i32"); + f.addLocal("itIn", "i32"); + f.addLocal("itOut", "i32"); + const c = f.getCodeBuilder(); + if (reverse) { + f.addCode( + c.setLocal("itIn", + c.i32_add( + c.getLocal("pIn"), + c.i32_mul( + c.i32_sub( + c.getLocal("n"), + c.i32_const(1) + ), + c.i32_const(sizeIn) + ) + ) + ), + c.setLocal("itOut", + c.i32_add( + c.getLocal("pOut"), + c.i32_mul( + c.i32_sub( + c.getLocal("n"), + c.i32_const(1) + ), + c.i32_const(sizeOut) + ) + ) + ), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), -module.exports = buildBatchConvertion; + c.call(internalFnName, c.getLocal("itIn"), c.getLocal("itOut")), -function buildBatchConvertion(module, fnName, internalFnName, sizeIn, sizeOut, reverse) { + c.setLocal("itIn", c.i32_sub(c.getLocal("itIn"), c.i32_const(sizeIn))), + c.setLocal("itOut", c.i32_sub(c.getLocal("itOut"), c.i32_const(sizeOut))), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + ); + } else { + f.addCode( + c.setLocal("itIn", c.getLocal("pIn")), + c.setLocal("itOut", c.getLocal("pOut")), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), + + c.call(internalFnName, c.getLocal("itIn"), c.getLocal("itOut")), + + c.setLocal("itIn", c.i32_add(c.getLocal("itIn"), c.i32_const(sizeIn))), + c.setLocal("itOut", c.i32_add(c.getLocal("itOut"), c.i32_const(sizeOut))), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + ); + } +} + +var build_batchop = buildBatchConvertion$2; + +function buildBatchConvertion$2(module, fnName, internalFnName, sizeIn, sizeOut, reverse) { if (typeof reverse === "undefined") { // Set the reverse in a way that allows to use the same buffer as in/out. if (sizeIn < sizeOut) { @@ -62157,11 +59590,162 @@ function buildBatchConvertion(module, fnName, internalFnName, sizeIn, sizeOut, r } } +var bigint = {}; -/***/ }), +// Many of these utilities are from the `big-integer` library, +// but adjusted to only work with native BigInt type +// Ref https://github.com/peterolson/BigInteger.js/blob/e5d2154d3c417069c51e7116bafc3b91d0b9fe41/BigInteger.js +// Originally licensed The Unlicense -/***/ 5904: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +function compare(a, b) { + return a === b ? 0 : a > b ? 1 : -1; +} + +function square$1(n) { + return n * n; +} + +function isOdd$4(n) { + return n % 2n !== 0n; +} + +function isEven(n) { + return n % 2n === 0n; +} + +function isNegative$3(n) { + return n < 0n; +} + +function isPositive(n) { + return n > 0n; +} + +function bitLength$5(n) { + if (isNegative$3(n)) { + return n.toString(2).length - 1; // discard the - sign + } else { + return n.toString(2).length; + } +} + +function abs(n) { + return n < 0n ? -n : n; +} + +function isUnit(n) { + return abs(n) === 1n; +} + +function modInv$3(a, n) { + var t = 0n, newT = 1n, r = n, newR = abs(a), q, lastT, lastR; + while (newR !== 0n) { + q = r / newR; + lastT = t; + lastR = r; + t = newT; + r = newR; + newT = lastT - (q * newT); + newR = lastR - (q * newR); + } + if (!isUnit(r)) throw new Error(a.toString() + " and " + n.toString() + " are not co-prime"); + if (compare(t, 0n) === -1) { + t = t + n; + } + if (isNegative$3(a)) { + return -t; + } + return t; +} + +function modPow$2(n, exp, mod) { + if (mod === 0n) throw new Error("Cannot take modPow with modulus 0"); + var r = 1n, + base = n % mod; + if (isNegative$3(exp)) { + exp = exp * -1n; + base = modInv$3(base, mod); + } + while (isPositive(exp)) { + if (base === 0n) return 0n; + if (isOdd$4(exp)) r = r * base % mod; + exp = exp / 2n; + base = square$1(base) % mod; + } + return r; +} + +function compareAbs(a, b) { + a = a >= 0n ? a : -a; + b = b >= 0n ? b : -b; + return a === b ? 0 : a > b ? 1 : -1; +} + +function isDivisibleBy(a, n) { + if (n === 0n) return false; + if (isUnit(n)) return true; + if (compareAbs(n, 2n) === 0) return isEven(a); + return a % n === 0n; +} + +function isBasicPrime(v) { + var n = abs(v); + if (isUnit(n)) return false; + if (n === 2n || n === 3n || n === 5n) return true; + if (isEven(n) || isDivisibleBy(n, 3n) || isDivisibleBy(n, 5n)) return false; + if (n < 49n) return true; + // we don't know if it's prime: let the other functions figure it out +} + +function prev(n) { + return n - 1n; +} + +function millerRabinTest(n, a) { + var nPrev = prev(n), + b = nPrev, + r = 0, + d, i, x; + while (isEven(b)) b = b / 2n, r++; + next: for (i = 0; i < a.length; i++) { + if (n < a[i]) continue; + x = modPow$2(BigInt(a[i]), b, n); + if (isUnit(x) || x === nPrev) continue; + for (d = r - 1; d != 0; d--) { + x = square$1(x) % n; + if (isUnit(x)) return false; + if (x === nPrev) continue next; + } + return false; + } + return true; +} + +function isPrime$1(p) { + var isPrime = isBasicPrime(p); + if (isPrime !== undefined) return isPrime; + var n = abs(p); + var bits = bitLength$5(n); + if (bits <= 64) + return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]); + var logN = Math.log(2) * Number(bits); + var t = Math.ceil(logN); + for (var a = [], i = 0; i < t; i++) { + a.push(BigInt(i + 2)); + } + return millerRabinTest(n, a); +} + +bigint.bitLength = bitLength$5; +bigint.isOdd = isOdd$4; +bigint.isNegative = isNegative$3; +bigint.abs = abs; +bigint.isUnit = isUnit; +bigint.compare = compare; +bigint.modInv = modInv$3; +bigint.modPow = modPow$2; +bigint.isPrime = isPrime$1; +bigint.square = square$1; /* Copyright 2019 0KIMS association. @@ -62182,12 +59766,3098 @@ function buildBatchConvertion(module, fnName, internalFnName, sizeIn, sizeOut, r along with wasmsnark. If not, see . */ -const buildTimesScalarNAF = __webpack_require__(3972); -//const buildTimesScalar = require("./build_timesscalar"); -const buildBatchConvertion = __webpack_require__(9440); -const buildMultiexp = __webpack_require__(4911); +const buildInt = build_int; +const utils$5 = utils$6; +const buildExp$2 = build_timesscalar; +const buildBatchInverse$2 = build_batchinverse; +const buildBatchConvertion$1 = build_batchconvertion; +const buildBatchOp = build_batchop; +const { bitLength: bitLength$4, modInv: modInv$2, modPow: modPow$1, isPrime, isOdd: isOdd$3, square } = bigint; -module.exports = function buildCurve(module, prefix, prefixField, pB) { +var build_f1m = function buildF1m(module, _q, _prefix, _intPrefix) { + const q = BigInt(_q); + const n64 = Math.floor((bitLength$4(q - 1n) - 1)/64) +1; + const n32 = n64*2; + const n8 = n64*8; + + const prefix = _prefix || "f1m"; + if (module.modules[prefix]) return prefix; // already builded + + const intPrefix = buildInt(module, n64, _intPrefix); + const pq = module.alloc(n8, utils$5.bigInt2BytesLE(q, n8)); + + const pR2 = module.alloc(utils$5.bigInt2BytesLE(square(1n << BigInt(n64*64)) % q, n8)); + const pOne = module.alloc(utils$5.bigInt2BytesLE((1n << BigInt(n64*64)) % q, n8)); + const pZero = module.alloc(utils$5.bigInt2BytesLE(0n, n8)); + const _minusOne = q - 1n; + const _e = _minusOne >> 1n; // e = (p-1)/2 + const pe = module.alloc(n8, utils$5.bigInt2BytesLE(_e, n8)); + + const _ePlusOne = _e + 1n; // e = (p-1)/2 + const pePlusOne = module.alloc(n8, utils$5.bigInt2BytesLE(_ePlusOne, n8)); + + module.modules[prefix] = { + pq: pq, + pR2: pR2, + n64: n64, + q: q, + pOne: pOne, + pZero: pZero, + pePlusOne: pePlusOne + }; + + function buildOne() { + const f = module.addFunction(prefix+"_one"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call(intPrefix + "_copy", c.i32_const(pOne), c.getLocal("pr"))); + } + + function buildAdd() { + const f = module.addFunction(prefix+"_add"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.if( + c.call(intPrefix+"_add", c.getLocal("x"), c.getLocal("y"), c.getLocal("r")), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + c.if( + c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + ) + ) + ); + } + + function buildSub() { + const f = module.addFunction(prefix+"_sub"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.if( + c.call(intPrefix+"_sub", c.getLocal("x"), c.getLocal("y"), c.getLocal("r")), + c.drop(c.call(intPrefix+"_add", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))) + ) + ); + } + + function buildNeg() { + const f = module.addFunction(prefix+"_neg"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(prefix + "_sub", c.i32_const(pZero), c.getLocal("x"), c.getLocal("r")) + ); + } + + + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.call(prefix + "_fromMontgomery", c.getLocal("x"), AUX), + c.call(intPrefix + "_gte", AUX, c.i32_const(pePlusOne) ) + ); + } + + function buildSign() { + const f = module.addFunction(prefix+"_sign"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.if ( + c.call(intPrefix + "_isZero", c.getLocal("x")), + c.ret(c.i32_const(0)) + ), + c.call(prefix + "_fromMontgomery", c.getLocal("x"), AUX), + c.if( + c.call(intPrefix + "_gte", AUX, c.i32_const(pePlusOne)), + c.ret(c.i32_const(-1)) + ), + c.ret(c.i32_const(1)) + ); + } + + + function buildMReduct() { + const carries = module.alloc(n32*n32*8); + + const f = module.addFunction(prefix+"_mReduct"); + f.addParam("t", "i32"); + f.addParam("r", "i32"); + f.addLocal("np32", "i64"); + f.addLocal("c", "i64"); + f.addLocal("m", "i64"); + + const c = f.getCodeBuilder(); + + const np32 = Number(0x100000000n - modInv$2(q, 0x100000000n)); + + f.addCode(c.setLocal("np32", c.i64_const(np32))); + + for (let i=0; i=n32) { + f.addCode( + c.i64_store32( + c.getLocal("r"), + (k-n32)*4, + c.getLocal(c0) + ) + ); + } + [c0, c1] = [c1, c0]; + f.addCode( + c.setLocal(c1, + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ) + ); + } + f.addCode( + c.i64_store32( + c.getLocal("r"), + n32*4-4, + c.getLocal(c0) + ) + ); + + f.addCode( + c.if( + c.i32_wrap_i64(c.getLocal(c1)), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + c.if( + c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + ) + ) + ); + } + + + function buildSquare() { + + const f = module.addFunction(prefix+"_square"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + f.addLocal("c0", "i64"); + f.addLocal("c1", "i64"); + f.addLocal("c0_old", "i64"); + f.addLocal("c1_old", "i64"); + f.addLocal("np32", "i64"); + + + for (let i=0;i>1) )&&(i>1, k>>1) + ) + ) + ); + + f.addCode( + c.setLocal(c1, + c.i64_add( + c.getLocal(c1), + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ) + ) + ); + } + + // Add the old carry + + if (k>0) { + f.addCode( + c.setLocal(c0, + c.i64_add( + c.i64_and( + c.getLocal(c0), + c.i64_const(0xFFFFFFFF) + ), + c.i64_and( + c.getLocal(c0_old), + c.i64_const(0xFFFFFFFF) + ), + ) + ) + ); + + f.addCode( + c.setLocal(c1, + c.i64_add( + c.i64_add( + c.getLocal(c1), + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ), + c.getLocal(c1_old) + ) + ) + ); + } + + + for (let i=Math.max(1, k-n32+1); (i<=k)&&(i=n32) { + f.addCode( + c.i64_store32( + c.getLocal("r"), + (k-n32)*4, + c.getLocal(c0) + ) + ); + } + f.addCode( + c.setLocal( + c0_old, + c.getLocal(c1) + ), + c.setLocal( + c1_old, + c.i64_shr_u( + c.getLocal(c0_old), + c.i64_const(32) + ) + ) + ); + } + f.addCode( + c.i64_store32( + c.getLocal("r"), + n32*4-4, + c.getLocal(c0_old) + ) + ); + + f.addCode( + c.if( + c.i32_wrap_i64(c.getLocal(c1_old)), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + c.if( + c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + ) + ) + ); + } + + + function buildSquareOld() { + const f = module.addFunction(prefix+"_squareOld"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); + } + + function buildToMontgomery() { + const f = module.addFunction(prefix+"_toMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(prefix+"_mul", c.getLocal("x"), c.i32_const(pR2), c.getLocal("r"))); + } + + function buildFromMontgomery() { + + const pAux2 = module.alloc(n8*2); + + const f = module.addFunction(prefix+"_fromMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(intPrefix + "_copy", c.getLocal("x"), c.i32_const(pAux2) )); + f.addCode(c.call(intPrefix + "_zero", c.i32_const(pAux2 + n8) )); + f.addCode(c.call(prefix+"_mReduct", c.i32_const(pAux2), c.getLocal("r"))); + } + + function buildInverse() { + + const f = module.addFunction(prefix+ "_inverse"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(prefix + "_fromMontgomery", c.getLocal("x"), c.getLocal("r"))); + f.addCode(c.call(intPrefix + "_inverseMod", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))); + f.addCode(c.call(prefix + "_toMontgomery", c.getLocal("r"), c.getLocal("r"))); + } + + // Calculate various valuse needed for sqrt + + + let _nqr = 2n; + if (isPrime(q)) { + while (modPow$1(_nqr, _e, q) !== _minusOne) _nqr = _nqr + 1n; + } + + let s2 = 0; + let _t = _minusOne; + + while ((!isOdd$3(_t))&&(_t !== 0n)) { + s2++; + _t = _t >> 1n; + } + const pt = module.alloc(n8, utils$5.bigInt2BytesLE(_t, n8)); + + const _nqrToT = modPow$1(_nqr, _t, q); + const pNqrToT = module.alloc(utils$5.bigInt2BytesLE((_nqrToT << BigInt(n64*64)) % q, n8)); + + const _tPlusOneOver2 = (_t + 1n) >> 1n; + const ptPlusOneOver2 = module.alloc(n8, utils$5.bigInt2BytesLE(_tPlusOneOver2, n8)); + + function buildSqrt() { + + const f = module.addFunction(prefix+ "_sqrt"); + f.addParam("n", "i32"); + f.addParam("r", "i32"); + f.addLocal("m", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + + const c = f.getCodeBuilder(); + + const ONE = c.i32_const(pOne); + const C = c.i32_const(module.alloc(n8)); + const T = c.i32_const(module.alloc(n8)); + const R = c.i32_const(module.alloc(n8)); + const SQ = c.i32_const(module.alloc(n8)); + const B = c.i32_const(module.alloc(n8)); + + f.addCode( + + // If (n==0) return 0 + c.if( + c.call(prefix + "_isZero", c.getLocal("n")), + c.ret( + c.call(prefix + "_zero", c.getLocal("r")) + ) + ), + + c.setLocal("m", c.i32_const(s2)), + c.call(prefix + "_copy", c.i32_const(pNqrToT), C), + c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(pt), c.i32_const(n8), T), + c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(ptPlusOneOver2), c.i32_const(n8), R), + + c.block(c.loop( + c.br_if(1, c.call(prefix + "_eq", T, ONE)), + + c.call(prefix + "_square", T, SQ), + c.setLocal("i", c.i32_const(1)), + c.block(c.loop( + c.br_if(1, c.call(prefix + "_eq", SQ, ONE)), + c.call(prefix + "_square", SQ, SQ), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + + c.call(prefix + "_copy", C, B), + c.setLocal("j", c.i32_sub(c.i32_sub( c.getLocal("m"), c.getLocal("i")), c.i32_const(1)) ), + c.block(c.loop( + c.br_if(1, c.i32_eqz(c.getLocal("j"))), + c.call(prefix + "_square", B, B), + c.setLocal("j", c.i32_sub(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + + c.setLocal("m", c.getLocal("i")), + c.call(prefix + "_square", B, C), + c.call(prefix + "_mul", T, C, T), + c.call(prefix + "_mul", R, B, R), + + c.br(0) + )), + + c.if( + c.call(prefix + "_isNegative", R), + c.call(prefix + "_neg", R, c.getLocal("r")), + c.call(prefix + "_copy", R, c.getLocal("r")), + ) + ); + } + + function buildIsSquare() { + const f = module.addFunction(prefix+"_isSquare"); + f.addParam("n", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const ONE = c.i32_const(pOne); + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.if( + c.call(prefix + "_isZero", c.getLocal("n")), + c.ret(c.i32_const(1)) + ), + c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(pe), c.i32_const(n8), AUX), + c.call(prefix + "_eq", AUX, ONE) + ); + } + + + function buildLoad() { + const f = module.addFunction(prefix+"_load"); + f.addParam("scalar", "i32"); + f.addParam("scalarLen", "i32"); + f.addParam("r", "i32"); + f.addLocal("p", "i32"); + f.addLocal("l", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + const c = f.getCodeBuilder(); + + const R = c.i32_const(module.alloc(n8)); + const pAux = module.alloc(n8); + const AUX = c.i32_const(pAux); + + f.addCode( + c.call(intPrefix + "_zero", c.getLocal("r")), + c.setLocal("i", c.i32_const(n8)), + c.setLocal("p", c.getLocal("scalar")), + c.block(c.loop( + c.br_if(1, c.i32_gt_u(c.getLocal("i"), c.getLocal("scalarLen"))), + + c.if( + c.i32_eq(c.getLocal("i"), c.i32_const(n8)), + c.call(prefix + "_one", R), + c.call(prefix + "_mul", R, c.i32_const(pR2), R) + ), + c.call(prefix + "_mul", c.getLocal("p"), R, AUX), + c.call(prefix + "_add", c.getLocal("r"), AUX, c.getLocal("r")), + + c.setLocal("p", c.i32_add(c.getLocal("p"), c.i32_const(n8))), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(n8))), + c.br(0) + )), + + c.setLocal("l", c.i32_rem_u( c.getLocal("scalarLen"), c.i32_const(n8))), + c.if(c.i32_eqz(c.getLocal("l")), c.ret([])), + c.call(intPrefix + "_zero", AUX), + c.setLocal("j", c.i32_const(0)), + c.block(c.loop( + c.br_if(1, c.i32_eq(c.getLocal("j"), c.getLocal("l"))), + + c.i32_store8( + c.getLocal("j"), + pAux, + c.i32_load8_u(c.getLocal("p")), + ), + c.setLocal("p", c.i32_add(c.getLocal("p"), c.i32_const(1))), + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + + c.if( + c.i32_eq(c.getLocal("i"), c.i32_const(n8)), + c.call(prefix + "_one", R), + c.call(prefix + "_mul", R, c.i32_const(pR2), R) + ), + c.call(prefix + "_mul", AUX, R, AUX), + c.call(prefix + "_add", c.getLocal("r"), AUX, c.getLocal("r")), + ); + } + + function buildTimesScalar() { + const f = module.addFunction(prefix+"_timesScalar"); + f.addParam("x", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLen", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.call(prefix + "_load", c.getLocal("scalar"), c.getLocal("scalarLen"), AUX), + c.call(prefix + "_toMontgomery", AUX, AUX), + c.call(prefix + "_mul", c.getLocal("x"), AUX, c.getLocal("r")), + ); + } + + function buildIsOne() { + const f = module.addFunction(prefix+"_isOne"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + f.addCode( + c.ret(c.call(intPrefix + "_eq", c.getLocal("x"), c.i32_const(pOne))) + ); + } + + + module.exportFunction(intPrefix + "_copy", prefix+"_copy"); + module.exportFunction(intPrefix + "_zero", prefix+"_zero"); + module.exportFunction(intPrefix + "_isZero", prefix+"_isZero"); + module.exportFunction(intPrefix + "_eq", prefix+"_eq"); + + buildIsOne(); + buildAdd(); + buildSub(); + buildNeg(); + buildMReduct(); + buildMul(); + buildSquare(); + buildSquareOld(); + buildToMontgomery(); + buildFromMontgomery(); + buildIsNegative(); + buildSign(); + buildInverse(); + buildOne(); + buildLoad(); + buildTimesScalar(); + buildBatchInverse$2(module, prefix); + buildBatchConvertion$1(module, prefix + "_batchToMontgomery", prefix + "_toMontgomery", n8, n8); + buildBatchConvertion$1(module, prefix + "_batchFromMontgomery", prefix + "_fromMontgomery", n8, n8); + buildBatchConvertion$1(module, prefix + "_batchNeg", prefix + "_neg", n8, n8); + buildBatchOp(module, prefix + "_batchAdd", prefix + "_add", n8, n8); + buildBatchOp(module, prefix + "_batchSub", prefix + "_sub", n8, n8); + buildBatchOp(module, prefix + "_batchMul", prefix + "_mul", n8, n8); + + module.exportFunction(prefix + "_add"); + module.exportFunction(prefix + "_sub"); + module.exportFunction(prefix + "_neg"); + module.exportFunction(prefix + "_isNegative"); + module.exportFunction(prefix + "_isOne"); + module.exportFunction(prefix + "_sign"); + module.exportFunction(prefix + "_mReduct"); + module.exportFunction(prefix + "_mul"); + module.exportFunction(prefix + "_square"); + module.exportFunction(prefix + "_squareOld"); + module.exportFunction(prefix + "_fromMontgomery"); + module.exportFunction(prefix + "_toMontgomery"); + module.exportFunction(prefix + "_inverse"); + module.exportFunction(prefix + "_one"); + module.exportFunction(prefix + "_load"); + module.exportFunction(prefix + "_timesScalar"); + buildExp$2( + module, + prefix + "_exp", + n8, + prefix + "_mul", + prefix + "_square", + intPrefix + "_copy", + prefix + "_one", + ); + module.exportFunction(prefix + "_exp"); + module.exportFunction(prefix + "_batchInverse"); + if (isPrime(q)) { + buildSqrt(); + buildIsSquare(); + module.exportFunction(prefix + "_sqrt"); + module.exportFunction(prefix + "_isSquare"); + } + module.exportFunction(prefix + "_batchToMontgomery"); + module.exportFunction(prefix + "_batchFromMontgomery"); + // console.log(module.functionIdxByName); + + return prefix; +}; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const buildF1m$2 =build_f1m; +const { bitLength: bitLength$3 } = bigint; + +var build_f1 = function buildF1(module, _q, _prefix, _f1mPrefix, _intPrefix) { + + const q = BigInt(_q); + const n64 = Math.floor((bitLength$3(q - 1n) - 1)/64) +1; + const n8 = n64*8; + + const prefix = _prefix || "f1"; + if (module.modules[prefix]) return prefix; // already builded + module.modules[prefix] = { + n64: n64 + }; + + const intPrefix = _intPrefix || "int"; + const f1mPrefix = buildF1m$2(module, q, _f1mPrefix, intPrefix); + + + const pR2 = module.modules[f1mPrefix].pR2; + const pq = module.modules[f1mPrefix].pq; + const pePlusOne = module.modules[f1mPrefix].pePlusOne; + + function buildMul() { + const pAux1 = module.alloc(n8); + + const f = module.addFunction(prefix+ "_mul"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(f1mPrefix + "_mul", c.getLocal("x"), c.getLocal("y"), c.i32_const(pAux1))); + f.addCode(c.call(f1mPrefix + "_mul", c.i32_const(pAux1), c.i32_const(pR2), c.getLocal("r"))); + } + + function buildSquare() { + const f = module.addFunction(prefix+"_square"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); + } + + + function buildInverse() { + + const f = module.addFunction(prefix+ "_inverse"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(intPrefix + "_inverseMod", c.getLocal("x"), c.i32_const(pq), c.getLocal("r"))); + } + + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(intPrefix + "_gte", c.getLocal("x"), c.i32_const(pePlusOne) ) + ); + } + + + buildMul(); + buildSquare(); + buildInverse(); + buildIsNegative(); + module.exportFunction(f1mPrefix + "_add", prefix + "_add"); + module.exportFunction(f1mPrefix + "_sub", prefix + "_sub"); + module.exportFunction(f1mPrefix + "_neg", prefix + "_neg"); + module.exportFunction(prefix + "_mul"); + module.exportFunction(prefix + "_square"); + module.exportFunction(prefix + "_inverse"); + module.exportFunction(prefix + "_isNegative"); + module.exportFunction(f1mPrefix + "_copy", prefix+"_copy"); + module.exportFunction(f1mPrefix + "_zero", prefix+"_zero"); + module.exportFunction(f1mPrefix + "_one", prefix+"_one"); + module.exportFunction(f1mPrefix + "_isZero", prefix+"_isZero"); + module.exportFunction(f1mPrefix + "_eq", prefix+"_eq"); + + return prefix; +}; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const buildExp$1 = build_timesscalar; +const buildBatchInverse$1 = build_batchinverse; +const utils$4 = utils$6; + +var build_f2m = function buildF2m(module, mulNonResidueFn, prefix, f1mPrefix) { + + if (module.modules[prefix]) return prefix; // already builded + + const f1n8 = module.modules[f1mPrefix].n64*8; + const q = module.modules[f1mPrefix].q; + + module.modules[prefix] = { + n64: module.modules[f1mPrefix].n64*2 + }; + + function buildAdd() { + const f = module.addFunction(prefix+"_add"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_add", x0, y0, r0), + c.call(f1mPrefix+"_add", x1, y1, r1), + ); + } + + function buildTimesScalar() { + const f = module.addFunction(prefix+"_timesScalar"); + f.addParam("x", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLen", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_timesScalar", x0, c.getLocal("scalar"), c.getLocal("scalarLen"), r0), + c.call(f1mPrefix+"_timesScalar", x1, c.getLocal("scalar"), c.getLocal("scalarLen"), r1), + ); + } + + function buildSub() { + const f = module.addFunction(prefix+"_sub"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_sub", x0, y0, r0), + c.call(f1mPrefix+"_sub", x1, y1, r1), + ); + } + + function buildNeg() { + const f = module.addFunction(prefix+"_neg"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_neg", x0, r0), + c.call(f1mPrefix+"_neg", x1, r1), + ); + } + + function buildConjugate() { + const f = module.addFunction(prefix+"_conjugate"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_copy", x0, r0), + c.call(f1mPrefix+"_neg", x1, r1), + ); + } + + + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.if( + c.call(f1mPrefix+"_isZero", x1), + c.ret(c.call(f1mPrefix+"_isNegative", x0)) + ), + c.ret(c.call(f1mPrefix+"_isNegative", x1)) + ); + } + + function buildMul() { + const f = module.addFunction(prefix+"_mul"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + const A = c.i32_const(module.alloc(f1n8)); + const B = c.i32_const(module.alloc(f1n8)); + const C = c.i32_const(module.alloc(f1n8)); + const D = c.i32_const(module.alloc(f1n8)); + + + f.addCode( + c.call(f1mPrefix + "_mul", x0, y0, A), // A = x0*y0 + c.call(f1mPrefix + "_mul", x1, y1, B), // B = x1*y1 + + c.call(f1mPrefix + "_add", x0, x1, C), // C = x0 + x1 + c.call(f1mPrefix + "_add", y0, y1, D), // D = y0 + y1 + c.call(f1mPrefix + "_mul", C, D, C), // C = (x0 + x1)*(y0 + y1) = x0*y0+x0*y1+x1*y0+x1*y1 + + // c.call(f1mPrefix + "_mul", B, c.i32_const(pNonResidue), r0), // r0 = nr*(x1*y1) + c.call(mulNonResidueFn, B, r0), // r0 = nr*(x1*y1) + c.call(f1mPrefix + "_add", A, r0, r0), // r0 = x0*y0 + nr*(x1*y1) + c.call(f1mPrefix + "_add", A, B, r1), // r1 = x0*y0+x1*y1 + c.call(f1mPrefix + "_sub", C, r1, r1) // r1 = x0*y0+x0*y1+x1*y0+x1*y1 - x0*y0+x1*y1 = x0*y1+x1*y0 + ); + + } + + function buildMul1() { + const f = module.addFunction(prefix+"_mul1"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y = c.getLocal("y"); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + + f.addCode( + c.call(f1mPrefix + "_mul", x0, y, r0), // A = x0*y + c.call(f1mPrefix + "_mul", x1, y, r1), // B = x1*y + ); + } + + function buildSquare() { + const f = module.addFunction(prefix+"_square"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + const AB = c.i32_const(module.alloc(f1n8)); + const APB = c.i32_const(module.alloc(f1n8)); + const APNB = c.i32_const(module.alloc(f1n8)); + const ABPNAB = c.i32_const(module.alloc(f1n8)); + + + f.addCode( + // AB = x0*y1 + c.call(f1mPrefix + "_mul", x0, x1, AB), + + // APB = x0+y1 + c.call(f1mPrefix + "_add", x0, x1, APB), + + // APBN0 = x0 + nr*x1 + c.call(mulNonResidueFn, x1, APNB), + c.call(f1mPrefix + "_add", x0, APNB, APNB), + + // ABPNAB = ab + nr*ab + c.call(mulNonResidueFn, AB, ABPNAB), + c.call(f1mPrefix + "_add", ABPNAB, AB, ABPNAB), + + // r0 = APB * APNB - ABPNAB + c.call(f1mPrefix + "_mul", APB, APNB, r0), + c.call(f1mPrefix + "_sub", r0, ABPNAB, r0), + + // r1 = AB + AB + c.call(f1mPrefix + "_add", AB, AB, r1), + ); + + } + + + function buildToMontgomery() { + const f = module.addFunction(prefix+"_toMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_toMontgomery", x0, r0), + c.call(f1mPrefix+"_toMontgomery", x1, r1) + ); + } + + function buildFromMontgomery() { + const f = module.addFunction(prefix+"_fromMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_fromMontgomery", x0, r0), + c.call(f1mPrefix+"_fromMontgomery", x1, r1) + ); + } + + function buildCopy() { + const f = module.addFunction(prefix+"_copy"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_copy", x0, r0), + c.call(f1mPrefix+"_copy", x1, r1) + ); + } + + function buildZero() { + const f = module.addFunction(prefix+"_zero"); + f.addParam("x", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_zero", x0), + c.call(f1mPrefix+"_zero", x1) + ); + } + + function buildOne() { + const f = module.addFunction(prefix+"_one"); + f.addParam("x", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_one", x0), + c.call(f1mPrefix+"_zero", x1) + ); + } + + function buildEq() { + const f = module.addFunction(prefix+"_eq"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + + f.addCode( + c.i32_and( + c.call(f1mPrefix+"_eq", x0, y0), + c.call(f1mPrefix+"_eq", x1, y1) + ) + ); + } + + function buildIsZero() { + const f = module.addFunction(prefix+"_isZero"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.i32_and( + c.call(f1mPrefix+"_isZero", x0), + c.call(f1mPrefix+"_isZero", x1) + ) + ); + } + + function buildInverse() { + const f = module.addFunction(prefix+"_inverse"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + const t0 = c.i32_const(module.alloc(f1n8)); + const t1 = c.i32_const(module.alloc(f1n8)); + const t2 = c.i32_const(module.alloc(f1n8)); + const t3 = c.i32_const(module.alloc(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_square", x0, t0), + c.call(f1mPrefix+"_square", x1, t1), + // c.call(f1mPrefix+"_mul", t1, c.i32_const(pNonResidue), t2), + c.call(mulNonResidueFn, t1, t2), + + c.call(f1mPrefix+"_sub", t0, t2, t2), + c.call(f1mPrefix+"_inverse", t2, t3), + + c.call(f1mPrefix+"_mul", x0, t3, r0), + c.call(f1mPrefix+"_mul", x1, t3, r1), + c.call(f1mPrefix+"_neg", r1, r1), + ); + } + + + function buildSign() { + const f = module.addFunction(prefix+"_sign"); + f.addParam("x", "i32"); + f.addLocal("s", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.setLocal("s" , c.call( f1mPrefix + "_sign", x1)), + c.if( + c.getLocal("s"), + c.ret(c.getLocal("s")) + ), + c.ret(c.call( f1mPrefix + "_sign", x0)) + ); + } + + function buildIsOne() { + const f = module.addFunction(prefix+"_isOne"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.ret(c.i32_and( + c.call(f1mPrefix + "_isOne", x0), + c.call(f1mPrefix + "_isZero", x1), + )) + ); + } + + + // Check here: https://eprint.iacr.org/2012/685.pdf + // Alg 9adj + function buildSqrt() { + + const f = module.addFunction(prefix+"_sqrt"); + f.addParam("a", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + // BigInt can't take `undefined` so we use `|| 0` + const e34 = c.i32_const(module.alloc(utils$4.bigInt2BytesLE((BigInt(q || 0) - 3n) / 4n, f1n8 ))); + // BigInt can't take `undefined` so we use `|| 0` + const e12 = c.i32_const(module.alloc(utils$4.bigInt2BytesLE((BigInt(q || 0) - 1n) / 2n, f1n8 ))); + + const a = c.getLocal("a"); + const a1 = c.i32_const(module.alloc(f1n8*2)); + const alpha = c.i32_const(module.alloc(f1n8*2)); + const a0 = c.i32_const(module.alloc(f1n8*2)); + const pn1 = module.alloc(f1n8*2); + const n1 = c.i32_const(pn1); + const n1a = c.i32_const(pn1); + const n1b = c.i32_const(pn1+f1n8); + const x0 = c.i32_const(module.alloc(f1n8*2)); + const b = c.i32_const(module.alloc(f1n8*2)); + + f.addCode( + + c.call(prefix + "_one", n1), + c.call(prefix + "_neg", n1, n1), + + // const a1 = F.pow(a, F.sqrt_e34); + c.call(prefix + "_exp", a, e34, c.i32_const(f1n8), a1), + + // const a1 = F.pow(a, F.sqrt_e34); + c.call(prefix + "_square", a1, alpha), + c.call(prefix + "_mul", a, alpha, alpha), + + // const a0 = F.mul(F.frobenius(1, alfa), alfa); + c.call(prefix + "_conjugate", alpha, a0), + c.call(prefix + "_mul", a0, alpha, a0), + + // if (F.eq(a0, F.negone)) return null; + c.if(c.call(prefix + "_eq",a0,n1), c.unreachable() ), + + // const x0 = F.mul(a1, a); + c.call(prefix + "_mul", a1, a, x0), + + // if (F.eq(alfa, F.negone)) { + c.if( + c.call(prefix + "_eq", alpha, n1), + [ + // x = F.mul(x0, [F.F.zero, F.F.one]); + ...c.call(f1mPrefix + "_zero", n1a), + ...c.call(f1mPrefix + "_one", n1b), + ...c.call(prefix + "_mul", n1, x0, c.getLocal("pr")), + ], + [ + // const b = F.pow(F.add(F.one, alfa), F.sqrt_e12); + ...c.call(prefix + "_one", b), + ...c.call(prefix + "_add", b, alpha, b), + ...c.call(prefix + "_exp", b, e12, c.i32_const(f1n8), b), + + // x = F.mul(b, x0); + ...c.call(prefix + "_mul", b, x0, c.getLocal("pr")), + ] + ) + ); + + } + + + function buildIsSquare() { + + const f = module.addFunction(prefix+"_isSquare"); + f.addParam("a", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + // BigInt can't take `undefined` so we use `|| 0` + const e34 = c.i32_const(module.alloc(utils$4.bigInt2BytesLE((BigInt(q || 0) - 3n) / 4n, f1n8 ))); + + const a = c.getLocal("a"); + const a1 = c.i32_const(module.alloc(f1n8*2)); + const alpha = c.i32_const(module.alloc(f1n8*2)); + const a0 = c.i32_const(module.alloc(f1n8*2)); + const pn1 = module.alloc(f1n8*2); + const n1 = c.i32_const(pn1); + + f.addCode( + + c.call(prefix + "_one", n1), + c.call(prefix + "_neg", n1, n1), + + // const a1 = F.pow(a, F.sqrt_e34); + c.call(prefix + "_exp", a, e34, c.i32_const(f1n8), a1), + + // const a1 = F.pow(a, F.sqrt_e34); + c.call(prefix + "_square", a1, alpha), + c.call(prefix + "_mul", a, alpha, alpha), + + // const a0 = F.mul(F.frobenius(1, alfa), alfa); + c.call(prefix + "_conjugate", alpha, a0), + c.call(prefix + "_mul", a0, alpha, a0), + + // if (F.eq(a0, F.negone)) return null; + c.if( + c.call( + prefix + "_eq", + a0, + n1 + ), + c.ret(c.i32_const(0)) + ), + c.ret(c.i32_const(1)) + ); + + } + + + buildIsZero(); + buildIsOne(); + buildZero(); + buildOne(); + buildCopy(); + buildMul(); + buildMul1(); + buildSquare(); + buildAdd(); + buildSub(); + buildNeg(); + buildConjugate(); + buildToMontgomery(); + buildFromMontgomery(); + buildEq(); + buildInverse(); + buildTimesScalar(); + buildSign(); + buildIsNegative(); + + module.exportFunction(prefix + "_isZero"); + module.exportFunction(prefix + "_isOne"); + module.exportFunction(prefix + "_zero"); + module.exportFunction(prefix + "_one"); + module.exportFunction(prefix + "_copy"); + module.exportFunction(prefix + "_mul"); + module.exportFunction(prefix + "_mul1"); + module.exportFunction(prefix + "_square"); + module.exportFunction(prefix + "_add"); + module.exportFunction(prefix + "_sub"); + module.exportFunction(prefix + "_neg"); + module.exportFunction(prefix + "_sign"); + module.exportFunction(prefix + "_conjugate"); + module.exportFunction(prefix + "_fromMontgomery"); + module.exportFunction(prefix + "_toMontgomery"); + module.exportFunction(prefix + "_eq"); + module.exportFunction(prefix + "_inverse"); + buildBatchInverse$1(module, prefix); + buildExp$1( + module, + prefix + "_exp", + f1n8*2, + prefix + "_mul", + prefix + "_square", + prefix + "_copy", + prefix + "_one", + ); + buildSqrt(); + buildIsSquare(); + + module.exportFunction(prefix + "_exp"); + module.exportFunction(prefix + "_timesScalar"); + module.exportFunction(prefix + "_batchInverse"); + module.exportFunction(prefix + "_sqrt"); + module.exportFunction(prefix + "_isSquare"); + module.exportFunction(prefix + "_isNegative"); + + + return prefix; +}; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const buildExp = build_timesscalar; +const buildBatchInverse = build_batchinverse; + +var build_f3m = function buildF3m(module, mulNonResidueFn, prefix, f1mPrefix) { + + if (module.modules[prefix]) return prefix; // already builded + + const f1n8 = module.modules[f1mPrefix].n64*8; + module.modules[prefix] = { + n64: module.modules[f1mPrefix].n64*3 + }; + + function buildAdd() { + const f = module.addFunction(prefix+"_add"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_add", x0, y0, r0), + c.call(f1mPrefix+"_add", x1, y1, r1), + c.call(f1mPrefix+"_add", x2, y2, r2), + ); + } + + function buildTimesScalar() { + const f = module.addFunction(prefix+"_timesScalar"); + f.addParam("x", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLen", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_timesScalar", x0, c.getLocal("scalar"), c.getLocal("scalarLen"), r0), + c.call(f1mPrefix+"_timesScalar", x1, c.getLocal("scalar"), c.getLocal("scalarLen"), r1), + c.call(f1mPrefix+"_timesScalar", x2, c.getLocal("scalar"), c.getLocal("scalarLen"), r2), + ); + } + + + function buildSub() { + const f = module.addFunction(prefix+"_sub"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_sub", x0, y0, r0), + c.call(f1mPrefix+"_sub", x1, y1, r1), + c.call(f1mPrefix+"_sub", x2, y2, r2), + ); + } + + function buildNeg() { + const f = module.addFunction(prefix+"_neg"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_neg", x0, r0), + c.call(f1mPrefix+"_neg", x1, r1), + c.call(f1mPrefix+"_neg", x2, r2), + ); + } + + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.if( + c.call(f1mPrefix+"_isZero", x2), + c.if( + c.call(f1mPrefix+"_isZero", x1), + c.ret(c.call(f1mPrefix+"_isNegative", x0)), + c.ret(c.call(f1mPrefix+"_isNegative", x1)) + ) + ), + c.ret(c.call(f1mPrefix+"_isNegative", x2)) + ); + } + + + function buildMul() { + const f = module.addFunction(prefix+"_mul"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const cd = f.getCodeBuilder(); + + const a = cd.getLocal("x"); + const b = cd.i32_add(cd.getLocal("x"), cd.i32_const(f1n8)); + const c = cd.i32_add(cd.getLocal("x"), cd.i32_const(2*f1n8)); + const A = cd.getLocal("y"); + const B = cd.i32_add(cd.getLocal("y"), cd.i32_const(f1n8)); + const C = cd.i32_add(cd.getLocal("y"), cd.i32_const(2*f1n8)); + const r0 = cd.getLocal("r"); + const r1 = cd.i32_add(cd.getLocal("r"), cd.i32_const(f1n8)); + const r2 = cd.i32_add(cd.getLocal("r"), cd.i32_const(2*f1n8)); + + const aA = cd.i32_const(module.alloc(f1n8)); + const bB = cd.i32_const(module.alloc(f1n8)); + const cC = cd.i32_const(module.alloc(f1n8)); + const a_b = cd.i32_const(module.alloc(f1n8)); + const A_B = cd.i32_const(module.alloc(f1n8)); + const a_c = cd.i32_const(module.alloc(f1n8)); + const A_C = cd.i32_const(module.alloc(f1n8)); + const b_c = cd.i32_const(module.alloc(f1n8)); + const B_C = cd.i32_const(module.alloc(f1n8)); + const aA_bB = cd.i32_const(module.alloc(f1n8)); + const aA_cC = cd.i32_const(module.alloc(f1n8)); + const bB_cC = cd.i32_const(module.alloc(f1n8)); + const AUX = cd.i32_const(module.alloc(f1n8)); + + + f.addCode( + cd.call(f1mPrefix + "_mul", a, A, aA), + cd.call(f1mPrefix + "_mul", b, B, bB), + cd.call(f1mPrefix + "_mul", c, C, cC), + + cd.call(f1mPrefix + "_add", a, b, a_b), + cd.call(f1mPrefix + "_add", A, B, A_B), + cd.call(f1mPrefix + "_add", a, c, a_c), + cd.call(f1mPrefix + "_add", A, C, A_C), + cd.call(f1mPrefix + "_add", b, c, b_c), + cd.call(f1mPrefix + "_add", B, C, B_C), + + cd.call(f1mPrefix + "_add", aA, bB, aA_bB), + cd.call(f1mPrefix + "_add", aA, cC, aA_cC), + cd.call(f1mPrefix + "_add", bB, cC, bB_cC), + + cd.call(f1mPrefix + "_mul", b_c, B_C, r0), + cd.call(f1mPrefix + "_sub", r0, bB_cC, r0), + cd.call(mulNonResidueFn, r0, r0), + cd.call(f1mPrefix + "_add", aA, r0, r0), + + cd.call(f1mPrefix + "_mul", a_b, A_B, r1), + cd.call(f1mPrefix + "_sub", r1, aA_bB, r1), + cd.call(mulNonResidueFn, cC, AUX), + cd.call(f1mPrefix + "_add", r1, AUX, r1), + + cd.call(f1mPrefix + "_mul", a_c, A_C, r2), + cd.call(f1mPrefix + "_sub", r2, aA_cC, r2), + cd.call(f1mPrefix + "_add", r2, bB, r2), + ); + + } + + function buildSquare() { + const f = module.addFunction(prefix+"_square"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const A = c.getLocal("x"); + const B = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const C = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + const s0 = c.i32_const(module.alloc(f1n8)); + const ab = c.i32_const(module.alloc(f1n8)); + const s1 = c.i32_const(module.alloc(f1n8)); + const s2 = c.i32_const(module.alloc(f1n8)); + const bc = c.i32_const(module.alloc(f1n8)); + const s3 = c.i32_const(module.alloc(f1n8)); + const s4 = c.i32_const(module.alloc(f1n8)); + + + f.addCode( + + c.call(f1mPrefix + "_square", A, s0), + c.call(f1mPrefix + "_mul", A, B, ab), + c.call(f1mPrefix + "_add", ab, ab, s1), + + c.call(f1mPrefix + "_sub", A, B, s2), + c.call(f1mPrefix + "_add", s2, C, s2), + c.call(f1mPrefix + "_square", s2, s2), + + c.call(f1mPrefix + "_mul", B, C, bc), + c.call(f1mPrefix + "_add", bc, bc, s3), + + c.call(f1mPrefix + "_square", C, s4), + + c.call(mulNonResidueFn, s3, r0), + c.call(f1mPrefix + "_add", s0, r0, r0), + + c.call(mulNonResidueFn, s4, r1), + c.call(f1mPrefix + "_add", s1, r1, r1), + + c.call(f1mPrefix + "_add", s0, s4, r2), + c.call(f1mPrefix + "_sub", s3, r2, r2), + c.call(f1mPrefix + "_add", s2, r2, r2), + c.call(f1mPrefix + "_add", s1, r2, r2), + ); + + } + + + function buildToMontgomery() { + const f = module.addFunction(prefix+"_toMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_toMontgomery", x0, r0), + c.call(f1mPrefix+"_toMontgomery", x1, r1), + c.call(f1mPrefix+"_toMontgomery", x2, r2) + ); + } + + function buildFromMontgomery() { + const f = module.addFunction(prefix+"_fromMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_fromMontgomery", x0, r0), + c.call(f1mPrefix+"_fromMontgomery", x1, r1), + c.call(f1mPrefix+"_fromMontgomery", x2, r2) + ); + } + + function buildCopy() { + const f = module.addFunction(prefix+"_copy"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_copy", x0, r0), + c.call(f1mPrefix+"_copy", x1, r1), + c.call(f1mPrefix+"_copy", x2, r2), + ); + } + + function buildZero() { + const f = module.addFunction(prefix+"_zero"); + f.addParam("x", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_zero", x0), + c.call(f1mPrefix+"_zero", x1), + c.call(f1mPrefix+"_zero", x2), + ); + } + + function buildOne() { + const f = module.addFunction(prefix+"_one"); + f.addParam("x", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_one", x0), + c.call(f1mPrefix+"_zero", x1), + c.call(f1mPrefix+"_zero", x2), + ); + } + + function buildEq() { + const f = module.addFunction(prefix+"_eq"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); + + f.addCode( + c.i32_and( + c.i32_and( + c.call(f1mPrefix+"_eq", x0, y0), + c.call(f1mPrefix+"_eq", x1, y1), + ), + c.call(f1mPrefix+"_eq", x2, y2) + ) + ); + } + + function buildIsZero() { + const f = module.addFunction(prefix+"_isZero"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.i32_and( + c.i32_and( + c.call(f1mPrefix+"_isZero", x0), + c.call(f1mPrefix+"_isZero", x1) + ), + c.call(f1mPrefix+"_isZero", x2) + ) + ); + } + + function buildInverse() { + const f = module.addFunction(prefix+"_inverse"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + const t0 = c.i32_const(module.alloc(f1n8)); + const t1 = c.i32_const(module.alloc(f1n8)); + const t2 = c.i32_const(module.alloc(f1n8)); + const t3 = c.i32_const(module.alloc(f1n8)); + const t4 = c.i32_const(module.alloc(f1n8)); + const t5 = c.i32_const(module.alloc(f1n8)); + const c0 = c.i32_const(module.alloc(f1n8)); + const c1 = c.i32_const(module.alloc(f1n8)); + const c2 = c.i32_const(module.alloc(f1n8)); + const t6 = c.i32_const(module.alloc(f1n8)); + const AUX = c.i32_const(module.alloc(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_square", x0, t0), + c.call(f1mPrefix+"_square", x1, t1), + c.call(f1mPrefix+"_square", x2, t2), + c.call(f1mPrefix+"_mul", x0, x1, t3), + c.call(f1mPrefix+"_mul", x0, x2, t4), + c.call(f1mPrefix+"_mul", x1, x2, t5), + + c.call(mulNonResidueFn, t5, c0), + c.call(f1mPrefix+"_sub", t0, c0, c0), + + c.call(mulNonResidueFn, t2, c1), + c.call(f1mPrefix+"_sub", c1, t3, c1), + + c.call(f1mPrefix+"_sub", t1, t4, c2), + + c.call(f1mPrefix+"_mul", x2, c1, t6), + c.call(f1mPrefix+"_mul", x1, c2, AUX), + c.call(f1mPrefix+"_add", t6, AUX, t6), + c.call(mulNonResidueFn, t6, t6), + c.call(f1mPrefix+"_mul", x0, c0, AUX), + c.call(f1mPrefix+"_add", AUX, t6, t6), + + c.call(f1mPrefix+"_inverse", t6, t6), + + c.call(f1mPrefix+"_mul", t6, c0, r0), + c.call(f1mPrefix+"_mul", t6, c1, r1), + c.call(f1mPrefix+"_mul", t6, c2, r2) + ); + } + + + function buildSign() { + const f = module.addFunction(prefix+"_sign"); + f.addParam("x", "i32"); + f.addLocal("s", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.setLocal("s" , c.call( f1mPrefix + "_sign", x2)), + c.if( + c.getLocal("s"), + c.ret(c.getLocal("s")) + ), + c.setLocal("s" , c.call( f1mPrefix + "_sign", x1)), + c.if( + c.getLocal("s"), + c.ret(c.getLocal("s")) + ), + c.ret(c.call( f1mPrefix + "_sign", x0)) + ); + } + + function buildIsOne() { + const f = module.addFunction(prefix+"_isOne"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8*2)); + + f.addCode( + c.ret( + c.i32_and( + c.i32_and( + c.call(f1mPrefix + "_isOne", x0), + c.call(f1mPrefix + "_isZero", x1) + ), + c.call(f1mPrefix + "_isZero", x2) + ) + ) + ); + } + + buildIsZero(); + buildIsOne(); + buildZero(); + buildOne(); + buildCopy(); + buildMul(); + buildSquare(); + buildAdd(); + buildSub(); + buildNeg(); + buildSign(); + buildToMontgomery(); + buildFromMontgomery(); + buildEq(); + buildInverse(); + buildTimesScalar(); + buildIsNegative(); + + module.exportFunction(prefix + "_isZero"); + module.exportFunction(prefix + "_isOne"); + module.exportFunction(prefix + "_zero"); + module.exportFunction(prefix + "_one"); + module.exportFunction(prefix + "_copy"); + module.exportFunction(prefix + "_mul"); + module.exportFunction(prefix + "_square"); + module.exportFunction(prefix + "_add"); + module.exportFunction(prefix + "_sub"); + module.exportFunction(prefix + "_neg"); + module.exportFunction(prefix + "_sign"); + module.exportFunction(prefix + "_fromMontgomery"); + module.exportFunction(prefix + "_toMontgomery"); + module.exportFunction(prefix + "_eq"); + module.exportFunction(prefix + "_inverse"); + buildBatchInverse(module, prefix); + buildExp( + module, + prefix + "_exp", + f1n8*3, + prefix + "_mul", + prefix + "_square", + prefix + "_copy", + prefix + "_one" + ); + module.exportFunction(prefix + "_exp"); + module.exportFunction(prefix + "_timesScalar"); + module.exportFunction(prefix + "_batchInverse"); + module.exportFunction(prefix + "_isNegative"); + + return prefix; +}; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +var build_timesscalarnaf = function buildTimesScalarNAF(module, fnName, elementLen, opAB, opAA, opAmB, opCopy, opInit) { + + const f = module.addFunction(fnName); + f.addParam("base", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLength", "i32"); + f.addParam("r", "i32"); + f.addLocal("old0", "i32"); + f.addLocal("nbits", "i32"); + f.addLocal("i", "i32"); + f.addLocal("last", "i32"); + f.addLocal("cur", "i32"); + f.addLocal("carry", "i32"); + f.addLocal("p", "i32"); + + const c = f.getCodeBuilder(); + + const aux = c.i32_const(module.alloc(elementLen)); + + function getBit(IDX) { + return c.i32_and( + c.i32_shr_u( + c.i32_load( + c.i32_add( + c.getLocal("scalar"), + c.i32_and( + c.i32_shr_u( + IDX, + c.i32_const(3) + ), + c.i32_const(0xFFFFFFFC) + ) + ) + ), + c.i32_and( + IDX, + c.i32_const(0x1F) + ) + ), + c.i32_const(1) + ); + } + + function pushBit(b) { + return [ + ...c.i32_store8( + c.getLocal("p"), + c.i32_const(b) + ), + ...c.setLocal( + "p", + c.i32_add( + c.getLocal("p"), + c.i32_const(1) + ) + ) + ]; + } + + f.addCode( + c.if( + c.i32_eqz(c.getLocal("scalarLength")), + [ + ...c.call(opInit, c.getLocal("r")), + ...c.ret([]) + ] + ), + c.setLocal("nbits", c.i32_shl(c.getLocal("scalarLength"), c.i32_const(3))), + c.setLocal("old0", c.i32_load(c.i32_const(0))), + c.setLocal("p", c.getLocal("old0")), + c.i32_store( + c.i32_const(0), + c.i32_and( + c.i32_add( + c.i32_add( + c.getLocal("old0"), + c.i32_const(32) + ), + c.getLocal("nbits") + ), + c.i32_const(0xFFFFFFF8) + ) + ), + c.setLocal("i", c.i32_const(1)), + + c.setLocal("last",getBit(c.i32_const(0))), + c.setLocal("carry",c.i32_const(0)), + + c.block(c.loop( + c.br_if(1, c.i32_eq( c.getLocal("i"), c.getLocal("nbits"))), + + c.setLocal("cur", getBit(c.getLocal("i"))), + c.if( c.getLocal("last"), + c.if( c.getLocal("cur"), + c.if(c.getLocal("carry"), + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(1)), + ...pushBit(1) + ] + , + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(1)), + ...pushBit(255) + ], + ), + c.if(c.getLocal("carry"), + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(1)), + ...pushBit(255) + ] + , + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(0)), + ...pushBit(1) + ], + ), + ), + c.if( c.getLocal("cur"), + c.if(c.getLocal("carry"), + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(1)), + ...pushBit(0) + ] + , + [ + ...c.setLocal("last", c.i32_const(1)), + ...c.setLocal("carry", c.i32_const(0)), + ...pushBit(0) + ], + ), + c.if(c.getLocal("carry"), + [ + ...c.setLocal("last", c.i32_const(1)), + ...c.setLocal("carry", c.i32_const(0)), + ...pushBit(0) + ] + , + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(0)), + ...pushBit(0) + ], + ), + ) + ), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + + c.if( c.getLocal("last"), + c.if(c.getLocal("carry"), + [ + ...pushBit(255), + ...pushBit(0), + ...pushBit(1) + ] + , + [ + ...pushBit(1) + ], + ), + c.if(c.getLocal("carry"), + [ + ...pushBit(0), + ...pushBit(1) + ] + ), + ), + + c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), + + // p already points to the last bit + + c.call(opCopy, c.getLocal("base"), aux), + + c.call(opInit, c.getLocal("r")), + + c.block(c.loop( + + + c.call(opAA, c.getLocal("r"), c.getLocal("r")), + + + c.setLocal("cur", + c.i32_load8_u( + c.getLocal("p") + ) + ), + + c.if( + c.getLocal("cur"), + c.if( + c.i32_eq(c.getLocal("cur"), c.i32_const(1)), + c.call(opAB, c.getLocal("r"), aux, c.getLocal("r")), + c.call(opAmB, c.getLocal("r"), aux, c.getLocal("r")), + ) + ), + + c.br_if(1, c.i32_eq( c.getLocal("old0"), c.getLocal("p"))), + c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), + c.br(0) + + )), + + c.i32_store( c.i32_const(0), c.getLocal("old0")) + + ); + +}; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +var build_multiexp = function buildMultiexp(module, prefix, fnName, opAdd, n8b) { + + const n64g = module.modules[prefix].n64; + const n8g = n64g*8; + + function buildGetChunk() { + const f = module.addFunction(fnName + "_getChunk"); + f.addParam("pScalar", "i32"); + f.addParam("scalarSize", "i32"); // Number of bytes of the scalar + f.addParam("startBit", "i32"); // Bit to start extract + f.addParam("chunkSize", "i32"); // Chunk size in bits + f.addLocal("bitsToEnd", "i32"); + f.addLocal("mask", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.setLocal("bitsToEnd", + c.i32_sub( + c.i32_mul( + c.getLocal("scalarSize"), + c.i32_const(8) + ), + c.getLocal("startBit") + ) + ), + c.if( + c.i32_gt_s( + c.getLocal("chunkSize"), + c.getLocal("bitsToEnd") + ), + c.setLocal( + "mask", + c.i32_sub( + c.i32_shl( + c.i32_const(1), + c.getLocal("bitsToEnd") + ), + c.i32_const(1) + ) + ), + c.setLocal( + "mask", + c.i32_sub( + c.i32_shl( + c.i32_const(1), + c.getLocal("chunkSize") + ), + c.i32_const(1) + ) + ) + ), + c.i32_and( + c.i32_shr_u( + c.i32_load( + c.i32_add( + c.getLocal("pScalar"), + c.i32_shr_u( + c.getLocal("startBit"), + c.i32_const(3) + ) + ), + 0, // offset + 0 // align to byte. + ), + c.i32_and( + c.getLocal("startBit"), + c.i32_const(0x7) + ) + ), + c.getLocal("mask") + ) + ); + } + + function buildMutiexpChunk() { + const f = module.addFunction(fnName + "_chunk"); + f.addParam("pBases", "i32"); + f.addParam("pScalars", "i32"); + f.addParam("scalarSize", "i32"); // Number of points + f.addParam("n", "i32"); // Number of points + f.addParam("startBit", "i32"); // bit where it starts the chunk + f.addParam("chunkSize", "i32"); // bit where it starts the chunk + f.addParam("pr", "i32"); + f.addLocal("nChunks", "i32"); + f.addLocal("itScalar", "i32"); + f.addLocal("endScalar", "i32"); + f.addLocal("itBase", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + f.addLocal("nTable", "i32"); + f.addLocal("pTable", "i32"); + f.addLocal("idx", "i32"); + f.addLocal("pIdxTable", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.if( + c.i32_eqz(c.getLocal("n")), + [ + ...c.call(prefix + "_zero", c.getLocal("pr")), + ...c.ret([]) + ] + ), + + // Allocate memory + + c.setLocal( + "nTable", + c.i32_shl( + c.i32_const(1), + c.getLocal("chunkSize") + ) + ), + c.setLocal("pTable", c.i32_load( c.i32_const(0) )), + c.i32_store( + c.i32_const(0), + c.i32_add( + c.getLocal("pTable"), + c.i32_mul( + c.getLocal("nTable"), + c.i32_const(n8g) + ) + ) + ), + + // Reset Table + c.setLocal("j", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("j"), + c.getLocal("nTable") + ) + ), + + c.call( + prefix + "_zero", + c.i32_add( + c.getLocal("pTable"), + c.i32_mul( + c.getLocal("j"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + + // Distribute elements + c.setLocal("itBase", c.getLocal("pBases")), + c.setLocal("itScalar", c.getLocal("pScalars")), + c.setLocal("endScalar", + c.i32_add( + c.getLocal("pScalars"), + c.i32_mul( + c.getLocal("n"), + c.getLocal("scalarSize") + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("itScalar"), + c.getLocal("endScalar") + ) + ), + + c.setLocal( + "idx", + c.call(fnName + "_getChunk", + c.getLocal("itScalar"), + c.getLocal("scalarSize"), + c.getLocal("startBit"), + c.getLocal("chunkSize") + ) + ), + + c.if( + c.getLocal("idx"), + [ + ...c.setLocal( + "pIdxTable", + c.i32_add( + c.getLocal("pTable"), + c.i32_mul( + c.i32_sub( + c.getLocal("idx"), + c.i32_const(1) + ), + c.i32_const(n8g) + ) + ) + ), + ...c.call( + opAdd, + c.getLocal("pIdxTable"), + c.getLocal("itBase"), + c.getLocal("pIdxTable"), + ) + ] + ), + + c.setLocal("itScalar", c.i32_add(c.getLocal("itScalar"), c.getLocal("scalarSize"))), + c.setLocal("itBase", c.i32_add(c.getLocal("itBase"), c.i32_const(n8b))), + c.br(0) + )), + + c.call(fnName + "_reduceTable", c.getLocal("pTable"), c.getLocal("chunkSize")), + c.call( + prefix + "_copy", + c.getLocal("pTable"), + c.getLocal("pr") + ), + + + c.i32_store( + c.i32_const(0), + c.getLocal("pTable") + ) + + ); + } + + function buildMultiexp() { + const f = module.addFunction(fnName); + f.addParam("pBases", "i32"); + f.addParam("pScalars", "i32"); + f.addParam("scalarSize", "i32"); // Number of points + f.addParam("n", "i32"); // Number of points + f.addParam("pr", "i32"); + f.addLocal("chunkSize", "i32"); + f.addLocal("nChunks", "i32"); + f.addLocal("itScalar", "i32"); + f.addLocal("endScalar", "i32"); + f.addLocal("itBase", "i32"); + f.addLocal("itBit", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + f.addLocal("nTable", "i32"); + f.addLocal("pTable", "i32"); + f.addLocal("idx", "i32"); + f.addLocal("pIdxTable", "i32"); + + const c = f.getCodeBuilder(); + + const aux = c.i32_const(module.alloc(n8g)); + + const pTSizes = module.alloc([ + 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 16, 16, 15, 14, 13, 13, + 12, 11, 10, 9, 8, 7, 7, 6, + 5 , 4, 3, 2, 1, 1, 1, 1 + ]); + + f.addCode( + c.call(prefix + "_zero", c.getLocal("pr")), + c.if( + c.i32_eqz(c.getLocal("n")), + c.ret([]) + ), + c.setLocal("chunkSize", c.i32_load8_u( c.i32_clz(c.getLocal("n")), pTSizes )), + c.setLocal( + "nChunks", + c.i32_add( + c.i32_div_u( + c.i32_sub( + c.i32_shl( + c.getLocal("scalarSize"), + c.i32_const(3) + ), + c.i32_const(1) + ), + c.getLocal("chunkSize") + ), + c.i32_const(1) + ) + ), + + + // Allocate memory + + c.setLocal( + "itBit", + c.i32_mul( + c.i32_sub( + c.getLocal("nChunks"), + c.i32_const(1) + ), + c.getLocal("chunkSize") + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_lt_s( + c.getLocal("itBit"), + c.i32_const(0) + ) + ), + + // Double nChunk times + c.if( + c.i32_eqz(c.call(prefix + "_isZero", c.getLocal("pr"))), + [ + ...c.setLocal("j", c.i32_const(0)), + ...c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("j"), + c.getLocal("chunkSize") + ) + ), + + c.call(prefix + "_double", c.getLocal("pr"), c.getLocal("pr")), + + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )) + ] + ), + + c.call( + fnName + "_chunk", + c.getLocal("pBases"), + c.getLocal("pScalars"), + c.getLocal("scalarSize"), + c.getLocal("n"), + c.getLocal("itBit"), + c.getLocal("chunkSize"), + aux + ), + + c.call( + prefix + "_add", + c.getLocal("pr"), + aux, + c.getLocal("pr") + ), + c.setLocal("itBit", c.i32_sub(c.getLocal("itBit"), c.getLocal("chunkSize"))), + c.br(0) + )) + ); + } + + function buildReduceTable() { + const f = module.addFunction(fnName + "_reduceTable"); + f.addParam("pTable", "i32"); + f.addParam("p", "i32"); // Number of bits of the table + f.addLocal("half", "i32"); + f.addLocal("it1", "i32"); + f.addLocal("it2", "i32"); + f.addLocal("pAcc", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.if( + c.i32_eq(c.getLocal("p"), c.i32_const(1)), + c.ret([]) + ), + c.setLocal( + "half", + c.i32_shl( + c.i32_const(1), + c.i32_sub( + c.getLocal("p"), + c.i32_const(1) + ) + ) + ), + + c.setLocal("it1", c.getLocal("pTable")), + c.setLocal( + "it2", + c.i32_add( + c.getLocal("pTable"), + c.i32_mul( + c.getLocal("half"), + c.i32_const(n8g) + ) + ) + ), + c.setLocal("pAcc", + c.i32_sub( + c.getLocal("it2"), + c.i32_const(n8g) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("it1"), + c.getLocal("pAcc") + ) + ), + c.call( + prefix + "_add", + c.getLocal("it1"), + c.getLocal("it2"), + c.getLocal("it1") + ), + c.call( + prefix + "_add", + c.getLocal("pAcc"), + c.getLocal("it2"), + c.getLocal("pAcc") + ), + c.setLocal("it1", c.i32_add(c.getLocal("it1"), c.i32_const(n8g))), + c.setLocal("it2", c.i32_add(c.getLocal("it2"), c.i32_const(n8g))), + c.br(0) + )), + + c.call( + fnName + "_reduceTable", + c.getLocal("pTable"), + c.i32_sub( + c.getLocal("p"), + c.i32_const(1) + ) + ), + + c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), + c.block(c.loop( + c.br_if(1, c.i32_eqz(c.getLocal("p"))), + c.call(prefix + "_double", c.getLocal("pAcc"), c.getLocal("pAcc")), + c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), + c.br(0) + )), + + c.call(prefix + "_add", c.getLocal("pTable"), c.getLocal("pAcc"), c.getLocal("pTable")) + ); + } + + buildGetChunk(); + buildReduceTable(); + buildMutiexpChunk(); + buildMultiexp(); + + module.exportFunction(fnName); + module.exportFunction(fnName +"_chunk"); + + +}; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const buildTimesScalarNAF = build_timesscalarnaf; +//const buildTimesScalar = require("./build_timesscalar"); +const buildBatchConvertion = build_batchconvertion; +const buildMultiexp$1 = build_multiexp; + +var build_curve_jacobian_a0 = function buildCurve(module, prefix, prefixField, pB) { const n64 = module.modules[prefixField].n64; @@ -63337,7 +64007,7 @@ module.exports = function buildCurve(module, prefix, prefixField, pB) { f.addCode( c.if( - c.call(prefix + "_isZero", c.getLocal("pIn")), + c.call(prefix + "_isZeroAffine", c.getLocal("pIn")), [ ...c.call(prefixField + "_zero", c.getLocal("pOut")), ...c.i32_store8( @@ -63382,10 +64052,6 @@ module.exports = function buildCurve(module, prefix, prefixField, pB) { c.call(prefix + "_isZeroAffine", c.getLocal("pIn")), [ ...c.call(prefix + "_zeroAffine", c.getLocal("pOut")), - ...c.i32_store8( - c.getLocal("pOut"), - c.i32_const(0x40) - ), ...c.ret([]) ] ), @@ -63488,32 +64154,6 @@ module.exports = function buildCurve(module, prefix, prefixField, pB) { ); } - - function buildInCurveAffine() { - const f = module.addFunction(prefix + "_inCurveAffine"); - f.addParam("pIn", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x = c.getLocal("pIn"); - const y = c.i32_add(c.getLocal("pIn"), n8); - - const y2 = module.alloc(n8*2); - const x3b = module.alloc(n8*2); - - f.addCode( - c.call(prefixField + "_square", y, y2), - c.call(prefixField + "_square", x, x3b), - c.call(prefixField + "_mul", x, x3b, x3b), - c.call(prefixField + "_add", x3b, c.i32_const(pB), x3b), - - c.ret( - c.call(prefixField + "_eq", y2, x3b) - ) - ); - } - function buildInCurveAffine() { const f = module.addFunction(prefix + "_inCurveAffine"); f.addParam("pIn", "i32"); @@ -63604,8 +64244,8 @@ module.exports = function buildCurve(module, prefix, prefixField, pB) { buildBatchConvertion(module, prefix + "_batchToJacobian", prefix + "_toJacobian", n8*2, n8*3, true); - buildMultiexp(module, prefix, prefix + "_multiexp", prefix + "_add", n8*3); - buildMultiexp(module, prefix, prefix + "_multiexpAffine", prefix + "_addMixed", n8*2); + buildMultiexp$1(module, prefix, prefix + "_multiexp", prefix + "_add", n8*3); + buildMultiexp$1(module, prefix, prefix + "_multiexpAffine", prefix + "_addMixed", n8*2); /* buildTimesScalar( @@ -63706,12 +64346,6 @@ module.exports = function buildCurve(module, prefix, prefixField, pB) { return prefix; }; - -/***/ }), - -/***/ 8138: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - /* Copyright 2019 0KIMS association. @@ -63731,2434 +64365,10 @@ module.exports = function buildCurve(module, prefix, prefixField, pB) { along with wasmsnark. If not, see . */ -const bigInt = __webpack_require__(2096); +const { isOdd: isOdd$2, modInv: modInv$1, modPow } = bigint; +const utils$3 = utils$6; -const buildF1m =__webpack_require__(75); - -module.exports = function buildF1(module, _q, _prefix, _f1mPrefix, _intPrefix) { - - const q = bigInt(_q); - const n64 = Math.floor((q.minus(1).bitLength() - 1)/64) +1; - const n8 = n64*8; - - const prefix = _prefix || "f1"; - if (module.modules[prefix]) return prefix; // already builded - module.modules[prefix] = { - n64: n64 - }; - - const intPrefix = _intPrefix || "int"; - const f1mPrefix = buildF1m(module, q, _f1mPrefix, intPrefix); - - - const pR2 = module.modules[f1mPrefix].pR2; - const pq = module.modules[f1mPrefix].pq; - const pePlusOne = module.modules[f1mPrefix].pePlusOne; - - function buildMul() { - const pAux1 = module.alloc(n8); - - const f = module.addFunction(prefix+ "_mul"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - f.addCode(c.call(f1mPrefix + "_mul", c.getLocal("x"), c.getLocal("y"), c.i32_const(pAux1))); - f.addCode(c.call(f1mPrefix + "_mul", c.i32_const(pAux1), c.i32_const(pR2), c.getLocal("r"))); - } - - function buildSquare() { - const f = module.addFunction(prefix+"_square"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); - } - - - function buildInverse() { - - const f = module.addFunction(prefix+ "_inverse"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - f.addCode(c.call(intPrefix + "_inverseMod", c.getLocal("x"), c.i32_const(pq), c.getLocal("r"))); - } - - function buildIsNegative() { - const f = module.addFunction(prefix+"_isNegative"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call(intPrefix + "_gte", c.getLocal("x"), c.i32_const(pePlusOne) ) - ); - } - - - buildMul(); - buildSquare(); - buildInverse(); - buildIsNegative(); - module.exportFunction(f1mPrefix + "_add", prefix + "_add"); - module.exportFunction(f1mPrefix + "_sub", prefix + "_sub"); - module.exportFunction(f1mPrefix + "_neg", prefix + "_neg"); - module.exportFunction(prefix + "_mul"); - module.exportFunction(prefix + "_square"); - module.exportFunction(prefix + "_inverse"); - module.exportFunction(prefix + "_isNegative"); - module.exportFunction(f1mPrefix + "_copy", prefix+"_copy"); - module.exportFunction(f1mPrefix + "_zero", prefix+"_zero"); - module.exportFunction(f1mPrefix + "_one", prefix+"_one"); - module.exportFunction(f1mPrefix + "_isZero", prefix+"_isZero"); - module.exportFunction(f1mPrefix + "_eq", prefix+"_eq"); - - return prefix; -}; - - -/***/ }), - -/***/ 75: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -const bigInt = __webpack_require__(2096); -const buildInt = __webpack_require__(6754); -const utils = __webpack_require__(2333); -const buildExp = __webpack_require__(5107); -const buildBatchInverse = __webpack_require__(8163); -const buildBatchConvertion = __webpack_require__(9440); -const buildBatchOp = __webpack_require__(4948); - -module.exports = function buildF1m(module, _q, _prefix, _intPrefix) { - const q = bigInt(_q); - const n64 = Math.floor((q.minus(1).bitLength() - 1)/64) +1; - const n32 = n64*2; - const n8 = n64*8; - - const prefix = _prefix || "f1m"; - if (module.modules[prefix]) return prefix; // already builded - - const intPrefix = buildInt(module, n64, _intPrefix); - const pq = module.alloc(n8, utils.bigInt2BytesLE(q, n8)); - - const pR = module.alloc(utils.bigInt2BytesLE(bigInt.one.shiftLeft(n64*64).mod(q), n8)); - const pR2 = module.alloc(utils.bigInt2BytesLE(bigInt.one.shiftLeft(n64*64).square().mod(q), n8)); - const pOne = module.alloc(utils.bigInt2BytesLE(bigInt.one.shiftLeft(n64*64).mod(q), n8)); - const pZero = module.alloc(utils.bigInt2BytesLE(bigInt.zero, n8)); - const _minusOne = q.minus(bigInt.one); - const _e = _minusOne.shiftRight(1); // e = (p-1)/2 - const pe = module.alloc(n8, utils.bigInt2BytesLE(_e, n8)); - - const _ePlusOne = _e.add(bigInt.one); // e = (p-1)/2 - const pePlusOne = module.alloc(n8, utils.bigInt2BytesLE(_ePlusOne, n8)); - - module.modules[prefix] = { - pq: pq, - pR2: pR2, - n64: n64, - q: q, - pOne: pOne, - pZero: pZero, - pePlusOne: pePlusOne - }; - - function buildOne() { - const f = module.addFunction(prefix+"_one"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode(c.call(intPrefix + "_copy", c.i32_const(pOne), c.getLocal("pr"))); - } - - function buildAdd() { - const f = module.addFunction(prefix+"_add"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.if( - c.call(intPrefix+"_add", c.getLocal("x"), c.getLocal("y"), c.getLocal("r")), - c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), - c.if( - c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), - c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), - ) - ) - ); - } - - function buildSub() { - const f = module.addFunction(prefix+"_sub"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.if( - c.call(intPrefix+"_sub", c.getLocal("x"), c.getLocal("y"), c.getLocal("r")), - c.drop(c.call(intPrefix+"_add", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))) - ) - ); - } - - function buildNeg() { - const f = module.addFunction(prefix+"_neg"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.call(prefix + "_sub", c.i32_const(pZero), c.getLocal("x"), c.getLocal("r")) - ); - } - - - function buildIsNegative() { - const f = module.addFunction(prefix+"_isNegative"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const AUX = c.i32_const(module.alloc(n8)); - - f.addCode( - c.call(prefix + "_fromMontgomery", c.getLocal("x"), AUX), - c.call(intPrefix + "_gte", AUX, c.i32_const(pePlusOne) ) - ); - } - - -/* - function buildIsNegative() { - const f = module.addFunction(prefix+"_isNegative"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const AUX = c.i32_const(module.alloc(n8)); - - f.addCode( - c.call(prefix + "_fromMontgomery", c.getLocal("x"), AUX), - c.i32_and( - c.i32_load(AUX), - c.i32_const(1) - ) - ); - } -*/ - - function buildSign() { - const f = module.addFunction(prefix+"_sign"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const AUX = c.i32_const(module.alloc(n8)); - - f.addCode( - c.if ( - c.call(intPrefix + "_isZero", c.getLocal("x")), - c.ret(c.i32_const(0)) - ), - c.call(prefix + "_fromMontgomery", c.getLocal("x"), AUX), - c.if( - c.call(intPrefix + "_gte", AUX, c.i32_const(pePlusOne)), - c.ret(c.i32_const(-1)) - ), - c.ret(c.i32_const(1)) - ); - } - - - function buildMReduct() { - const carries = module.alloc(n32*n32*8); - - const f = module.addFunction(prefix+"_mReduct"); - f.addParam("t", "i32"); - f.addParam("r", "i32"); - f.addLocal("np32", "i64"); - f.addLocal("c", "i64"); - f.addLocal("m", "i64"); - - const c = f.getCodeBuilder(); - - const np32 = bigInt("100000000",16).minus( q.modInv(bigInt("100000000",16))).toJSNumber(); - - f.addCode(c.setLocal("np32", c.i64_const(np32))); - - for (let i=0; i=n32) { - f.addCode( - c.i64_store32( - c.getLocal("r"), - (k-n32)*4, - c.getLocal(c0) - ) - ); - } - [c0, c1] = [c1, c0]; - f.addCode( - c.setLocal(c1, - c.i64_shr_u( - c.getLocal(c0), - c.i64_const(32) - ) - ) - ); - } - f.addCode( - c.i64_store32( - c.getLocal("r"), - n32*4-4, - c.getLocal(c0) - ) - ); - - f.addCode( - c.if( - c.i32_wrap_i64(c.getLocal(c1)), - c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), - c.if( - c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), - c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), - ) - ) - ); - } - - - function buildSquare() { - - const f = module.addFunction(prefix+"_square"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - f.addLocal("c0", "i64"); - f.addLocal("c1", "i64"); - f.addLocal("c0_old", "i64"); - f.addLocal("c1_old", "i64"); - f.addLocal("np32", "i64"); - - - for (let i=0;i>1) )&&(i>1, k>>1) - ) - ) - ); - - f.addCode( - c.setLocal(c1, - c.i64_add( - c.getLocal(c1), - c.i64_shr_u( - c.getLocal(c0), - c.i64_const(32) - ) - ) - ) - ); - } - - // Add the old carry - - if (k>0) { - f.addCode( - c.setLocal(c0, - c.i64_add( - c.i64_and( - c.getLocal(c0), - c.i64_const(0xFFFFFFFF) - ), - c.i64_and( - c.getLocal(c0_old), - c.i64_const(0xFFFFFFFF) - ), - ) - ) - ); - - f.addCode( - c.setLocal(c1, - c.i64_add( - c.i64_add( - c.getLocal(c1), - c.i64_shr_u( - c.getLocal(c0), - c.i64_const(32) - ) - ), - c.getLocal(c1_old) - ) - ) - ); - } - - - for (let i=Math.max(1, k-n32+1); (i<=k)&&(i=n32) { - f.addCode( - c.i64_store32( - c.getLocal("r"), - (k-n32)*4, - c.getLocal(c0) - ) - ); - } - f.addCode( - c.setLocal( - c0_old, - c.getLocal(c1) - ), - c.setLocal( - c1_old, - c.i64_shr_u( - c.getLocal(c0_old), - c.i64_const(32) - ) - ) - ); - } - f.addCode( - c.i64_store32( - c.getLocal("r"), - n32*4-4, - c.getLocal(c0_old) - ) - ); - - f.addCode( - c.if( - c.i32_wrap_i64(c.getLocal(c1_old)), - c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), - c.if( - c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), - c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), - ) - ) - ); - } - - - function buildSquareOld() { - const f = module.addFunction(prefix+"_squareOld"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); - } - - function buildToMontgomery() { - const f = module.addFunction(prefix+"_toMontgomery"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - f.addCode(c.call(prefix+"_mul", c.getLocal("x"), c.i32_const(pR2), c.getLocal("r"))); - } - - function buildFromMontgomery() { - - const pAux2 = module.alloc(n8*2); - - const f = module.addFunction(prefix+"_fromMontgomery"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - f.addCode(c.call(intPrefix + "_copy", c.getLocal("x"), c.i32_const(pAux2) )); - f.addCode(c.call(intPrefix + "_zero", c.i32_const(pAux2 + n8) )); - f.addCode(c.call(prefix+"_mReduct", c.i32_const(pAux2), c.getLocal("r"))); - } - - function buildInverse() { - - const f = module.addFunction(prefix+ "_inverse"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - f.addCode(c.call(prefix + "_fromMontgomery", c.getLocal("x"), c.getLocal("r"))); - f.addCode(c.call(intPrefix + "_inverseMod", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))); - f.addCode(c.call(prefix + "_toMontgomery", c.getLocal("r"), c.getLocal("r"))); - } - - // Calculate various valuse needed for sqrt - - - let _nqr = bigInt(2); - if (q.isPrime()) { - while (!_nqr.modPow(_e, q).equals(_minusOne)) _nqr = _nqr.add(bigInt.one); - } - - const pnqr = module.alloc(utils.bigInt2BytesLE(_nqr.shiftLeft(n64*64).mod(q), n8)); - - let s2 = 0; - let _t = _minusOne; - - while ((!_t.isOdd())&&(!_t.isZero())) { - s2++; - _t = _t.shiftRight(1); - } - const pt = module.alloc(n8, utils.bigInt2BytesLE(_t, n8)); - - const _nqrToT = _nqr.modPow(_t, q); - const pNqrToT = module.alloc(utils.bigInt2BytesLE(_nqrToT.shiftLeft(n64*64).mod(q), n8)); - - const _tPlusOneOver2 = _t.add(1).shiftRight(1); - const ptPlusOneOver2 = module.alloc(n8, utils.bigInt2BytesLE(_tPlusOneOver2, n8)); - - function buildSqrt() { - - const f = module.addFunction(prefix+ "_sqrt"); - f.addParam("n", "i32"); - f.addParam("r", "i32"); - f.addLocal("m", "i32"); - f.addLocal("i", "i32"); - f.addLocal("j", "i32"); - - const c = f.getCodeBuilder(); - - const ONE = c.i32_const(pOne); - const C = c.i32_const(module.alloc(n8)); - const T = c.i32_const(module.alloc(n8)); - const R = c.i32_const(module.alloc(n8)); - const SQ = c.i32_const(module.alloc(n8)); - const B = c.i32_const(module.alloc(n8)); - - f.addCode( - - // If (n==0) return 0 - c.if( - c.call(prefix + "_isZero", c.getLocal("n")), - c.ret( - c.call(prefix + "_zero", c.getLocal("r")) - ) - ), - - c.setLocal("m", c.i32_const(s2)), - c.call(prefix + "_copy", c.i32_const(pNqrToT), C), - c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(pt), c.i32_const(n8), T), - c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(ptPlusOneOver2), c.i32_const(n8), R), - - c.block(c.loop( - c.br_if(1, c.call(prefix + "_eq", T, ONE)), - - c.call(prefix + "_square", T, SQ), - c.setLocal("i", c.i32_const(1)), - c.block(c.loop( - c.br_if(1, c.call(prefix + "_eq", SQ, ONE)), - c.call(prefix + "_square", SQ, SQ), - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), - c.br(0) - )), - - c.call(prefix + "_copy", C, B), - c.setLocal("j", c.i32_sub(c.i32_sub( c.getLocal("m"), c.getLocal("i")), c.i32_const(1)) ), - c.block(c.loop( - c.br_if(1, c.i32_eqz(c.getLocal("j"))), - c.call(prefix + "_square", B, B), - c.setLocal("j", c.i32_sub(c.getLocal("j"), c.i32_const(1))), - c.br(0) - )), - - c.setLocal("m", c.getLocal("i")), - c.call(prefix + "_square", B, C), - c.call(prefix + "_mul", T, C, T), - c.call(prefix + "_mul", R, B, R), - - c.br(0) - )), - - c.if( - c.call(prefix + "_isNegative", R), - c.call(prefix + "_neg", R, c.getLocal("r")), - c.call(prefix + "_copy", R, c.getLocal("r")), - ) - ); - } - - function buildIsSquare() { - const f = module.addFunction(prefix+"_isSquare"); - f.addParam("n", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const ONE = c.i32_const(pOne); - const AUX = c.i32_const(module.alloc(n8)); - - f.addCode( - c.if( - c.call(prefix + "_isZero", c.getLocal("n")), - c.ret(c.i32_const(1)) - ), - c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(pe), c.i32_const(n8), AUX), - c.call(prefix + "_eq", AUX, ONE) - ); - } - - - function buildLoad() { - const f = module.addFunction(prefix+"_load"); - f.addParam("scalar", "i32"); - f.addParam("scalarLen", "i32"); - f.addParam("r", "i32"); - f.addLocal("p", "i32"); - f.addLocal("l", "i32"); - f.addLocal("i", "i32"); - f.addLocal("j", "i32"); - const c = f.getCodeBuilder(); - - const R = c.i32_const(module.alloc(n8)); - const pAux = module.alloc(n8); - const AUX = c.i32_const(pAux); - - f.addCode( - c.call(intPrefix + "_zero", c.getLocal("r")), - c.setLocal("i", c.i32_const(n8)), - c.setLocal("p", c.getLocal("scalar")), - c.block(c.loop( - c.br_if(1, c.i32_gt_u(c.getLocal("i"), c.getLocal("scalarLen"))), - - c.if( - c.i32_eq(c.getLocal("i"), c.i32_const(n8)), - c.call(prefix + "_one", R), - c.call(prefix + "_mul", R, c.i32_const(pR2), R) - ), - c.call(prefix + "_mul", c.getLocal("p"), R, AUX), - c.call(prefix + "_add", c.getLocal("r"), AUX, c.getLocal("r")), - - c.setLocal("p", c.i32_add(c.getLocal("p"), c.i32_const(n8))), - c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(n8))), - c.br(0) - )), - - c.setLocal("l", c.i32_rem_u( c.getLocal("scalarLen"), c.i32_const(n8))), - c.if(c.i32_eqz(c.getLocal("l")), c.ret([])), - c.call(intPrefix + "_zero", AUX), - c.setLocal("j", c.i32_const(0)), - c.block(c.loop( - c.br_if(1, c.i32_eq(c.getLocal("j"), c.getLocal("l"))), - - c.i32_store8( - c.getLocal("j"), - pAux, - c.i32_load8_u(c.getLocal("p")), - ), - c.setLocal("p", c.i32_add(c.getLocal("p"), c.i32_const(1))), - c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), - c.br(0) - )), - - c.if( - c.i32_eq(c.getLocal("i"), c.i32_const(n8)), - c.call(prefix + "_one", R), - c.call(prefix + "_mul", R, c.i32_const(pR2), R) - ), - c.call(prefix + "_mul", AUX, R, AUX), - c.call(prefix + "_add", c.getLocal("r"), AUX, c.getLocal("r")), - ); - } - - function buildTimesScalar() { - const f = module.addFunction(prefix+"_timesScalar"); - f.addParam("x", "i32"); - f.addParam("scalar", "i32"); - f.addParam("scalarLen", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const AUX = c.i32_const(module.alloc(n8)); - - f.addCode( - c.call(prefix + "_load", c.getLocal("scalar"), c.getLocal("scalarLen"), AUX), - c.call(prefix + "_toMontgomery", AUX, AUX), - c.call(prefix + "_mul", c.getLocal("x"), AUX, c.getLocal("r")), - ); - } - - function buildIsOne() { - const f = module.addFunction(prefix+"_isOne"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - f.addCode( - c.ret(c.call(intPrefix + "_eq", c.getLocal("x"), c.i32_const(pOne))) - ); - } - - - module.exportFunction(intPrefix + "_copy", prefix+"_copy"); - module.exportFunction(intPrefix + "_zero", prefix+"_zero"); - module.exportFunction(intPrefix + "_isZero", prefix+"_isZero"); - module.exportFunction(intPrefix + "_eq", prefix+"_eq"); - - buildIsOne(); - buildAdd(); - buildSub(); - buildNeg(); - buildMReduct(); - buildMul(); - buildSquare(); - buildSquareOld(); - buildToMontgomery(); - buildFromMontgomery(); - buildIsNegative(); - buildSign(); - buildInverse(); - buildOne(); - buildLoad(); - buildTimesScalar(); - buildBatchInverse(module, prefix); - buildBatchConvertion(module, prefix + "_batchToMontgomery", prefix + "_toMontgomery", n8, n8); - buildBatchConvertion(module, prefix + "_batchFromMontgomery", prefix + "_fromMontgomery", n8, n8); - buildBatchConvertion(module, prefix + "_batchNeg", prefix + "_neg", n8, n8); - buildBatchOp(module, prefix + "_batchAdd", prefix + "_add", n8, n8); - buildBatchOp(module, prefix + "_batchSub", prefix + "_sub", n8, n8); - buildBatchOp(module, prefix + "_batchMul", prefix + "_mul", n8, n8); - - module.exportFunction(prefix + "_add"); - module.exportFunction(prefix + "_sub"); - module.exportFunction(prefix + "_neg"); - module.exportFunction(prefix + "_isNegative"); - module.exportFunction(prefix + "_isOne"); - module.exportFunction(prefix + "_sign"); - module.exportFunction(prefix + "_mReduct"); - module.exportFunction(prefix + "_mul"); - module.exportFunction(prefix + "_square"); - module.exportFunction(prefix + "_squareOld"); - module.exportFunction(prefix + "_fromMontgomery"); - module.exportFunction(prefix + "_toMontgomery"); - module.exportFunction(prefix + "_inverse"); - module.exportFunction(prefix + "_one"); - module.exportFunction(prefix + "_load"); - module.exportFunction(prefix + "_timesScalar"); - buildExp( - module, - prefix + "_exp", - n8, - prefix + "_mul", - prefix + "_square", - intPrefix + "_copy", - prefix + "_one", - ); - module.exportFunction(prefix + "_exp"); - module.exportFunction(prefix + "_batchInverse"); - if (q.isPrime()) { - buildSqrt(); - buildIsSquare(); - module.exportFunction(prefix + "_sqrt"); - module.exportFunction(prefix + "_isSquare"); - } - module.exportFunction(prefix + "_batchToMontgomery"); - module.exportFunction(prefix + "_batchFromMontgomery"); - // console.log(module.functionIdxByName); - - return prefix; -}; - - -/***/ }), - -/***/ 5420: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ -const buildExp = __webpack_require__(5107); -const buildBatchInverse = __webpack_require__(8163); -const bigInt = __webpack_require__(2096); -const utils = __webpack_require__(2333); - -module.exports = function buildF2m(module, mulNonResidueFn, prefix, f1mPrefix) { - - if (module.modules[prefix]) return prefix; // already builded - - const f1n8 = module.modules[f1mPrefix].n64*8; - const q = module.modules[f1mPrefix].q; - - module.modules[prefix] = { - n64: module.modules[f1mPrefix].n64*2 - }; - - function buildAdd() { - const f = module.addFunction(prefix+"_add"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const y0 = c.getLocal("y"); - const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_add", x0, y0, r0), - c.call(f1mPrefix+"_add", x1, y1, r1), - ); - } - - function buildTimesScalar() { - const f = module.addFunction(prefix+"_timesScalar"); - f.addParam("x", "i32"); - f.addParam("scalar", "i32"); - f.addParam("scalarLen", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_timesScalar", x0, c.getLocal("scalar"), c.getLocal("scalarLen"), r0), - c.call(f1mPrefix+"_timesScalar", x1, c.getLocal("scalar"), c.getLocal("scalarLen"), r1), - ); - } - - function buildSub() { - const f = module.addFunction(prefix+"_sub"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const y0 = c.getLocal("y"); - const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_sub", x0, y0, r0), - c.call(f1mPrefix+"_sub", x1, y1, r1), - ); - } - - function buildNeg() { - const f = module.addFunction(prefix+"_neg"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_neg", x0, r0), - c.call(f1mPrefix+"_neg", x1, r1), - ); - } - - function buildConjugate() { - const f = module.addFunction(prefix+"_conjugate"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_copy", x0, r0), - c.call(f1mPrefix+"_neg", x1, r1), - ); - } - - - function buildIsNegative() { - const f = module.addFunction(prefix+"_isNegative"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - - f.addCode( - c.if( - c.call(f1mPrefix+"_isZero", x1), - c.ret(c.call(f1mPrefix+"_isNegative", x0)) - ), - c.ret(c.call(f1mPrefix+"_isNegative", x1)) - ); - } - - function buildMul() { - const f = module.addFunction(prefix+"_mul"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const y0 = c.getLocal("y"); - const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - const A = c.i32_const(module.alloc(f1n8)); - const B = c.i32_const(module.alloc(f1n8)); - const C = c.i32_const(module.alloc(f1n8)); - const D = c.i32_const(module.alloc(f1n8)); - - - f.addCode( - c.call(f1mPrefix + "_mul", x0, y0, A), // A = x0*y0 - c.call(f1mPrefix + "_mul", x1, y1, B), // B = x1*y1 - - c.call(f1mPrefix + "_add", x0, x1, C), // C = x0 + x1 - c.call(f1mPrefix + "_add", y0, y1, D), // D = y0 + y1 - c.call(f1mPrefix + "_mul", C, D, C), // C = (x0 + x1)*(y0 + y1) = x0*y0+x0*y1+x1*y0+x1*y1 - - // c.call(f1mPrefix + "_mul", B, c.i32_const(pNonResidue), r0), // r0 = nr*(x1*y1) - c.call(mulNonResidueFn, B, r0), // r0 = nr*(x1*y1) - c.call(f1mPrefix + "_add", A, r0, r0), // r0 = x0*y0 + nr*(x1*y1) - c.call(f1mPrefix + "_add", A, B, r1), // r1 = x0*y0+x1*y1 - c.call(f1mPrefix + "_sub", C, r1, r1) // r1 = x0*y0+x0*y1+x1*y0+x1*y1 - x0*y0+x1*y1 = x0*y1+x1*y0 - ); - - } - - function buildMul1() { - const f = module.addFunction(prefix+"_mul1"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const y = c.getLocal("y"); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - - f.addCode( - c.call(f1mPrefix + "_mul", x0, y, r0), // A = x0*y - c.call(f1mPrefix + "_mul", x1, y, r1), // B = x1*y - ); - } - - function buildSquare() { - const f = module.addFunction(prefix+"_square"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - const AB = c.i32_const(module.alloc(f1n8)); - const APB = c.i32_const(module.alloc(f1n8)); - const APNB = c.i32_const(module.alloc(f1n8)); - const ABPNAB = c.i32_const(module.alloc(f1n8)); - - - f.addCode( - // AB = x0*y1 - c.call(f1mPrefix + "_mul", x0, x1, AB), - - // APB = x0+y1 - c.call(f1mPrefix + "_add", x0, x1, APB), - - // APBN0 = x0 + nr*x1 - c.call(mulNonResidueFn, x1, APNB), - c.call(f1mPrefix + "_add", x0, APNB, APNB), - - // ABPNAB = ab + nr*ab - c.call(mulNonResidueFn, AB, ABPNAB), - c.call(f1mPrefix + "_add", ABPNAB, AB, ABPNAB), - - // r0 = APB * APNB - ABPNAB - c.call(f1mPrefix + "_mul", APB, APNB, r0), - c.call(f1mPrefix + "_sub", r0, ABPNAB, r0), - - // r1 = AB + AB - c.call(f1mPrefix + "_add", AB, AB, r1), - ); - - } - - - function buildToMontgomery() { - const f = module.addFunction(prefix+"_toMontgomery"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_toMontgomery", x0, r0), - c.call(f1mPrefix+"_toMontgomery", x1, r1) - ); - } - - function buildFromMontgomery() { - const f = module.addFunction(prefix+"_fromMontgomery"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_fromMontgomery", x0, r0), - c.call(f1mPrefix+"_fromMontgomery", x1, r1) - ); - } - - function buildCopy() { - const f = module.addFunction(prefix+"_copy"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_copy", x0, r0), - c.call(f1mPrefix+"_copy", x1, r1) - ); - } - - function buildZero() { - const f = module.addFunction(prefix+"_zero"); - f.addParam("x", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_zero", x0), - c.call(f1mPrefix+"_zero", x1) - ); - } - - function buildOne() { - const f = module.addFunction(prefix+"_one"); - f.addParam("x", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_one", x0), - c.call(f1mPrefix+"_zero", x1) - ); - } - - function buildEq() { - const f = module.addFunction(prefix+"_eq"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const y0 = c.getLocal("y"); - const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); - - f.addCode( - c.i32_and( - c.call(f1mPrefix+"_eq", x0, y0), - c.call(f1mPrefix+"_eq", x1, y1) - ) - ); - } - - function buildIsZero() { - const f = module.addFunction(prefix+"_isZero"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - - f.addCode( - c.i32_and( - c.call(f1mPrefix+"_isZero", x0), - c.call(f1mPrefix+"_isZero", x1) - ) - ); - } - - function buildInverse() { - const f = module.addFunction(prefix+"_inverse"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - - const t0 = c.i32_const(module.alloc(f1n8)); - const t1 = c.i32_const(module.alloc(f1n8)); - const t2 = c.i32_const(module.alloc(f1n8)); - const t3 = c.i32_const(module.alloc(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_square", x0, t0), - c.call(f1mPrefix+"_square", x1, t1), - // c.call(f1mPrefix+"_mul", t1, c.i32_const(pNonResidue), t2), - c.call(mulNonResidueFn, t1, t2), - - c.call(f1mPrefix+"_sub", t0, t2, t2), - c.call(f1mPrefix+"_inverse", t2, t3), - - c.call(f1mPrefix+"_mul", x0, t3, r0), - c.call(f1mPrefix+"_mul", x1, t3, r1), - c.call(f1mPrefix+"_neg", r1, r1), - ); - } - - - function buildSign() { - const f = module.addFunction(prefix+"_sign"); - f.addParam("x", "i32"); - f.addLocal("s", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - - f.addCode( - c.setLocal("s" , c.call( f1mPrefix + "_sign", x1)), - c.if( - c.getLocal("s"), - c.ret(c.getLocal("s")) - ), - c.ret(c.call( f1mPrefix + "_sign", x0)) - ); - } - - function buildIsOne() { - const f = module.addFunction(prefix+"_isOne"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - - f.addCode( - c.ret(c.i32_and( - c.call(f1mPrefix + "_isOne", x0), - c.call(f1mPrefix + "_isZero", x1), - )) - ); - } - - - // Check here: https://eprint.iacr.org/2012/685.pdf - // Alg 9adj - function buildSqrt() { - - const f = module.addFunction(prefix+"_sqrt"); - f.addParam("a", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - const e34 = c.i32_const(module.alloc(utils.bigInt2BytesLE(bigInt(q).minus(bigInt(3)).divide(4), f1n8 ))); - const e12 = c.i32_const(module.alloc(utils.bigInt2BytesLE(bigInt(q).minus(bigInt(1)).divide(2), f1n8 ))); - - const a = c.getLocal("a"); - const a1 = c.i32_const(module.alloc(f1n8*2)); - const alpha = c.i32_const(module.alloc(f1n8*2)); - const a0 = c.i32_const(module.alloc(f1n8*2)); - const pn1 = module.alloc(f1n8*2); - const n1 = c.i32_const(pn1); - const n1a = c.i32_const(pn1); - const n1b = c.i32_const(pn1+f1n8); - const x0 = c.i32_const(module.alloc(f1n8*2)); - const b = c.i32_const(module.alloc(f1n8*2)); - - f.addCode( - - c.call(prefix + "_one", n1), - c.call(prefix + "_neg", n1, n1), - - // const a1 = F.pow(a, F.sqrt_e34); - c.call(prefix + "_exp", a, e34, c.i32_const(f1n8), a1), - - // const a1 = F.pow(a, F.sqrt_e34); - c.call(prefix + "_square", a1, alpha), - c.call(prefix + "_mul", a, alpha, alpha), - - // const a0 = F.mul(F.frobenius(1, alfa), alfa); - c.call(prefix + "_conjugate", alpha, a0), - c.call(prefix + "_mul", a0, alpha, a0), - - // if (F.eq(a0, F.negone)) return null; - c.if(c.call(prefix + "_eq",a0,n1), c.unreachable() ), - - // const x0 = F.mul(a1, a); - c.call(prefix + "_mul", a1, a, x0), - - // if (F.eq(alfa, F.negone)) { - c.if( - c.call(prefix + "_eq", alpha, n1), - [ - // x = F.mul(x0, [F.F.zero, F.F.one]); - ...c.call(f1mPrefix + "_zero", n1a), - ...c.call(f1mPrefix + "_one", n1b), - ...c.call(prefix + "_mul", n1, x0, c.getLocal("pr")), - ], - [ - // const b = F.pow(F.add(F.one, alfa), F.sqrt_e12); - ...c.call(prefix + "_one", b), - ...c.call(prefix + "_add", b, alpha, b), - ...c.call(prefix + "_exp", b, e12, c.i32_const(f1n8), b), - - // x = F.mul(b, x0); - ...c.call(prefix + "_mul", b, x0, c.getLocal("pr")), - ] - ) - ); - - } - - - function buildIsSquare() { - - const f = module.addFunction(prefix+"_isSquare"); - f.addParam("a", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const e34 = c.i32_const(module.alloc(utils.bigInt2BytesLE(bigInt(q).minus(bigInt(3)).divide(4), f1n8 ))); - - const a = c.getLocal("a"); - const a1 = c.i32_const(module.alloc(f1n8*2)); - const alpha = c.i32_const(module.alloc(f1n8*2)); - const a0 = c.i32_const(module.alloc(f1n8*2)); - const pn1 = module.alloc(f1n8*2); - const n1 = c.i32_const(pn1); - - f.addCode( - - c.call(prefix + "_one", n1), - c.call(prefix + "_neg", n1, n1), - - // const a1 = F.pow(a, F.sqrt_e34); - c.call(prefix + "_exp", a, e34, c.i32_const(f1n8), a1), - - // const a1 = F.pow(a, F.sqrt_e34); - c.call(prefix + "_square", a1, alpha), - c.call(prefix + "_mul", a, alpha, alpha), - - // const a0 = F.mul(F.frobenius(1, alfa), alfa); - c.call(prefix + "_conjugate", alpha, a0), - c.call(prefix + "_mul", a0, alpha, a0), - - // if (F.eq(a0, F.negone)) return null; - c.if( - c.call( - prefix + "_eq", - a0, - n1 - ), - c.ret(c.i32_const(0)) - ), - c.ret(c.i32_const(1)) - ); - - } - - - buildIsZero(); - buildIsOne(); - buildZero(); - buildOne(); - buildCopy(); - buildMul(); - buildMul1(); - buildSquare(); - buildAdd(); - buildSub(); - buildNeg(); - buildConjugate(); - buildToMontgomery(); - buildFromMontgomery(); - buildEq(); - buildInverse(); - buildTimesScalar(); - buildSign(); - buildIsNegative(); - - module.exportFunction(prefix + "_isZero"); - module.exportFunction(prefix + "_isOne"); - module.exportFunction(prefix + "_zero"); - module.exportFunction(prefix + "_one"); - module.exportFunction(prefix + "_copy"); - module.exportFunction(prefix + "_mul"); - module.exportFunction(prefix + "_mul1"); - module.exportFunction(prefix + "_square"); - module.exportFunction(prefix + "_add"); - module.exportFunction(prefix + "_sub"); - module.exportFunction(prefix + "_neg"); - module.exportFunction(prefix + "_sign"); - module.exportFunction(prefix + "_conjugate"); - module.exportFunction(prefix + "_fromMontgomery"); - module.exportFunction(prefix + "_toMontgomery"); - module.exportFunction(prefix + "_eq"); - module.exportFunction(prefix + "_inverse"); - buildBatchInverse(module, prefix); - buildExp( - module, - prefix + "_exp", - f1n8*2, - prefix + "_mul", - prefix + "_square", - prefix + "_copy", - prefix + "_one", - ); - buildSqrt(); - buildIsSquare(); - - module.exportFunction(prefix + "_exp"); - module.exportFunction(prefix + "_timesScalar"); - module.exportFunction(prefix + "_batchInverse"); - module.exportFunction(prefix + "_sqrt"); - module.exportFunction(prefix + "_isSquare"); - module.exportFunction(prefix + "_isNegative"); - - - return prefix; -}; - - -/***/ }), - -/***/ 7173: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ -const buildExp = __webpack_require__(5107); -const buildBatchInverse = __webpack_require__(8163); - -module.exports = function buildF3m(module, mulNonResidueFn, prefix, f1mPrefix) { - - if (module.modules[prefix]) return prefix; // already builded - - const f1n8 = module.modules[f1mPrefix].n64*8; - module.modules[prefix] = { - n64: module.modules[f1mPrefix].n64*3 - }; - - function buildAdd() { - const f = module.addFunction(prefix+"_add"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const y0 = c.getLocal("y"); - const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); - const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_add", x0, y0, r0), - c.call(f1mPrefix+"_add", x1, y1, r1), - c.call(f1mPrefix+"_add", x2, y2, r2), - ); - } - - function buildTimesScalar() { - const f = module.addFunction(prefix+"_timesScalar"); - f.addParam("x", "i32"); - f.addParam("scalar", "i32"); - f.addParam("scalarLen", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_timesScalar", x0, c.getLocal("scalar"), c.getLocal("scalarLen"), r0), - c.call(f1mPrefix+"_timesScalar", x1, c.getLocal("scalar"), c.getLocal("scalarLen"), r1), - c.call(f1mPrefix+"_timesScalar", x2, c.getLocal("scalar"), c.getLocal("scalarLen"), r2), - ); - } - - - function buildSub() { - const f = module.addFunction(prefix+"_sub"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const y0 = c.getLocal("y"); - const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); - const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_sub", x0, y0, r0), - c.call(f1mPrefix+"_sub", x1, y1, r1), - c.call(f1mPrefix+"_sub", x2, y2, r2), - ); - } - - function buildNeg() { - const f = module.addFunction(prefix+"_neg"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_neg", x0, r0), - c.call(f1mPrefix+"_neg", x1, r1), - c.call(f1mPrefix+"_neg", x2, r2), - ); - } - - function buildIsNegative() { - const f = module.addFunction(prefix+"_isNegative"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - - f.addCode( - c.if( - c.call(f1mPrefix+"_isZero", x2), - c.if( - c.call(f1mPrefix+"_isZero", x1), - c.ret(c.call(f1mPrefix+"_isNegative", x0)), - c.ret(c.call(f1mPrefix+"_isNegative", x1)) - ) - ), - c.ret(c.call(f1mPrefix+"_isNegative", x2)) - ); - } - - - function buildMul() { - const f = module.addFunction(prefix+"_mul"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.addParam("r", "i32"); - - const cd = f.getCodeBuilder(); - - const a = cd.getLocal("x"); - const b = cd.i32_add(cd.getLocal("x"), cd.i32_const(f1n8)); - const c = cd.i32_add(cd.getLocal("x"), cd.i32_const(2*f1n8)); - const A = cd.getLocal("y"); - const B = cd.i32_add(cd.getLocal("y"), cd.i32_const(f1n8)); - const C = cd.i32_add(cd.getLocal("y"), cd.i32_const(2*f1n8)); - const r0 = cd.getLocal("r"); - const r1 = cd.i32_add(cd.getLocal("r"), cd.i32_const(f1n8)); - const r2 = cd.i32_add(cd.getLocal("r"), cd.i32_const(2*f1n8)); - - const aA = cd.i32_const(module.alloc(f1n8)); - const bB = cd.i32_const(module.alloc(f1n8)); - const cC = cd.i32_const(module.alloc(f1n8)); - const a_b = cd.i32_const(module.alloc(f1n8)); - const A_B = cd.i32_const(module.alloc(f1n8)); - const a_c = cd.i32_const(module.alloc(f1n8)); - const A_C = cd.i32_const(module.alloc(f1n8)); - const b_c = cd.i32_const(module.alloc(f1n8)); - const B_C = cd.i32_const(module.alloc(f1n8)); - const aA_bB = cd.i32_const(module.alloc(f1n8)); - const aA_cC = cd.i32_const(module.alloc(f1n8)); - const bB_cC = cd.i32_const(module.alloc(f1n8)); - const AUX = cd.i32_const(module.alloc(f1n8)); - - - f.addCode( - cd.call(f1mPrefix + "_mul", a, A, aA), - cd.call(f1mPrefix + "_mul", b, B, bB), - cd.call(f1mPrefix + "_mul", c, C, cC), - - cd.call(f1mPrefix + "_add", a, b, a_b), - cd.call(f1mPrefix + "_add", A, B, A_B), - cd.call(f1mPrefix + "_add", a, c, a_c), - cd.call(f1mPrefix + "_add", A, C, A_C), - cd.call(f1mPrefix + "_add", b, c, b_c), - cd.call(f1mPrefix + "_add", B, C, B_C), - - cd.call(f1mPrefix + "_add", aA, bB, aA_bB), - cd.call(f1mPrefix + "_add", aA, cC, aA_cC), - cd.call(f1mPrefix + "_add", bB, cC, bB_cC), - - cd.call(f1mPrefix + "_mul", b_c, B_C, r0), - cd.call(f1mPrefix + "_sub", r0, bB_cC, r0), - cd.call(mulNonResidueFn, r0, r0), - cd.call(f1mPrefix + "_add", aA, r0, r0), - - cd.call(f1mPrefix + "_mul", a_b, A_B, r1), - cd.call(f1mPrefix + "_sub", r1, aA_bB, r1), - cd.call(mulNonResidueFn, cC, AUX), - cd.call(f1mPrefix + "_add", r1, AUX, r1), - - cd.call(f1mPrefix + "_mul", a_c, A_C, r2), - cd.call(f1mPrefix + "_sub", r2, aA_cC, r2), - cd.call(f1mPrefix + "_add", r2, bB, r2), - ); - - } - - function buildSquare() { - const f = module.addFunction(prefix+"_square"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const A = c.getLocal("x"); - const B = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const C = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - const s0 = c.i32_const(module.alloc(f1n8)); - const ab = c.i32_const(module.alloc(f1n8)); - const s1 = c.i32_const(module.alloc(f1n8)); - const s2 = c.i32_const(module.alloc(f1n8)); - const bc = c.i32_const(module.alloc(f1n8)); - const s3 = c.i32_const(module.alloc(f1n8)); - const s4 = c.i32_const(module.alloc(f1n8)); - - - f.addCode( - - c.call(f1mPrefix + "_square", A, s0), - c.call(f1mPrefix + "_mul", A, B, ab), - c.call(f1mPrefix + "_add", ab, ab, s1), - - c.call(f1mPrefix + "_sub", A, B, s2), - c.call(f1mPrefix + "_add", s2, C, s2), - c.call(f1mPrefix + "_square", s2, s2), - - c.call(f1mPrefix + "_mul", B, C, bc), - c.call(f1mPrefix + "_add", bc, bc, s3), - - c.call(f1mPrefix + "_square", C, s4), - - c.call(mulNonResidueFn, s3, r0), - c.call(f1mPrefix + "_add", s0, r0, r0), - - c.call(mulNonResidueFn, s4, r1), - c.call(f1mPrefix + "_add", s1, r1, r1), - - c.call(f1mPrefix + "_add", s0, s4, r2), - c.call(f1mPrefix + "_sub", s3, r2, r2), - c.call(f1mPrefix + "_add", s2, r2, r2), - c.call(f1mPrefix + "_add", s1, r2, r2), - ); - - } - - - function buildToMontgomery() { - const f = module.addFunction(prefix+"_toMontgomery"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_toMontgomery", x0, r0), - c.call(f1mPrefix+"_toMontgomery", x1, r1), - c.call(f1mPrefix+"_toMontgomery", x2, r2) - ); - } - - function buildFromMontgomery() { - const f = module.addFunction(prefix+"_fromMontgomery"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_fromMontgomery", x0, r0), - c.call(f1mPrefix+"_fromMontgomery", x1, r1), - c.call(f1mPrefix+"_fromMontgomery", x2, r2) - ); - } - - function buildCopy() { - const f = module.addFunction(prefix+"_copy"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_copy", x0, r0), - c.call(f1mPrefix+"_copy", x1, r1), - c.call(f1mPrefix+"_copy", x2, r2), - ); - } - - function buildZero() { - const f = module.addFunction(prefix+"_zero"); - f.addParam("x", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_zero", x0), - c.call(f1mPrefix+"_zero", x1), - c.call(f1mPrefix+"_zero", x2), - ); - } - - function buildOne() { - const f = module.addFunction(prefix+"_one"); - f.addParam("x", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - - f.addCode( - c.call(f1mPrefix+"_one", x0), - c.call(f1mPrefix+"_zero", x1), - c.call(f1mPrefix+"_zero", x2), - ); - } - - function buildEq() { - const f = module.addFunction(prefix+"_eq"); - f.addParam("x", "i32"); - f.addParam("y", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const y0 = c.getLocal("y"); - const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); - const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); - - f.addCode( - c.i32_and( - c.i32_and( - c.call(f1mPrefix+"_eq", x0, y0), - c.call(f1mPrefix+"_eq", x1, y1), - ), - c.call(f1mPrefix+"_eq", x2, y2) - ) - ); - } - - function buildIsZero() { - const f = module.addFunction(prefix+"_isZero"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - - f.addCode( - c.i32_and( - c.i32_and( - c.call(f1mPrefix+"_isZero", x0), - c.call(f1mPrefix+"_isZero", x1) - ), - c.call(f1mPrefix+"_isZero", x2) - ) - ); - } - - function buildInverse() { - const f = module.addFunction(prefix+"_inverse"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - const r0 = c.getLocal("r"); - const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); - const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); - - const t0 = c.i32_const(module.alloc(f1n8)); - const t1 = c.i32_const(module.alloc(f1n8)); - const t2 = c.i32_const(module.alloc(f1n8)); - const t3 = c.i32_const(module.alloc(f1n8)); - const t4 = c.i32_const(module.alloc(f1n8)); - const t5 = c.i32_const(module.alloc(f1n8)); - const c0 = c.i32_const(module.alloc(f1n8)); - const c1 = c.i32_const(module.alloc(f1n8)); - const c2 = c.i32_const(module.alloc(f1n8)); - const t6 = c.i32_const(module.alloc(f1n8)); - const AUX = c.i32_const(module.alloc(f1n8)); - - f.addCode( - c.call(f1mPrefix+"_square", x0, t0), - c.call(f1mPrefix+"_square", x1, t1), - c.call(f1mPrefix+"_square", x2, t2), - c.call(f1mPrefix+"_mul", x0, x1, t3), - c.call(f1mPrefix+"_mul", x0, x2, t4), - c.call(f1mPrefix+"_mul", x1, x2, t5), - - c.call(mulNonResidueFn, t5, c0), - c.call(f1mPrefix+"_sub", t0, c0, c0), - - c.call(mulNonResidueFn, t2, c1), - c.call(f1mPrefix+"_sub", c1, t3, c1), - - c.call(f1mPrefix+"_sub", t1, t4, c2), - - c.call(f1mPrefix+"_mul", x2, c1, t6), - c.call(f1mPrefix+"_mul", x1, c2, AUX), - c.call(f1mPrefix+"_add", t6, AUX, t6), - c.call(mulNonResidueFn, t6, t6), - c.call(f1mPrefix+"_mul", x0, c0, AUX), - c.call(f1mPrefix+"_add", AUX, t6, t6), - - c.call(f1mPrefix+"_inverse", t6, t6), - - c.call(f1mPrefix+"_mul", t6, c0, r0), - c.call(f1mPrefix+"_mul", t6, c1, r1), - c.call(f1mPrefix+"_mul", t6, c2, r2) - ); - } - - - function buildSign() { - const f = module.addFunction(prefix+"_sign"); - f.addParam("x", "i32"); - f.addLocal("s", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); - - f.addCode( - c.setLocal("s" , c.call( f1mPrefix + "_sign", x2)), - c.if( - c.getLocal("s"), - c.ret(c.getLocal("s")) - ), - c.setLocal("s" , c.call( f1mPrefix + "_sign", x1)), - c.if( - c.getLocal("s"), - c.ret(c.getLocal("s")) - ), - c.ret(c.call( f1mPrefix + "_sign", x0)) - ); - } - - function buildIsOne() { - const f = module.addFunction(prefix+"_isOne"); - f.addParam("x", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - const x0 = c.getLocal("x"); - const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); - const x2 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8*2)); - - f.addCode( - c.ret( - c.i32_and( - c.i32_and( - c.call(f1mPrefix + "_isOne", x0), - c.call(f1mPrefix + "_isZero", x1) - ), - c.call(f1mPrefix + "_isZero", x2) - ) - ) - ); - } - - buildIsZero(); - buildIsOne(); - buildZero(); - buildOne(); - buildCopy(); - buildMul(); - buildSquare(); - buildAdd(); - buildSub(); - buildNeg(); - buildSign(); - buildToMontgomery(); - buildFromMontgomery(); - buildEq(); - buildInverse(); - buildTimesScalar(); - buildIsNegative(); - - module.exportFunction(prefix + "_isZero"); - module.exportFunction(prefix + "_isOne"); - module.exportFunction(prefix + "_zero"); - module.exportFunction(prefix + "_one"); - module.exportFunction(prefix + "_copy"); - module.exportFunction(prefix + "_mul"); - module.exportFunction(prefix + "_square"); - module.exportFunction(prefix + "_add"); - module.exportFunction(prefix + "_sub"); - module.exportFunction(prefix + "_neg"); - module.exportFunction(prefix + "_sign"); - module.exportFunction(prefix + "_fromMontgomery"); - module.exportFunction(prefix + "_toMontgomery"); - module.exportFunction(prefix + "_eq"); - module.exportFunction(prefix + "_inverse"); - buildBatchInverse(module, prefix); - buildExp( - module, - prefix + "_exp", - f1n8*3, - prefix + "_mul", - prefix + "_square", - prefix + "_copy", - prefix + "_one" - ); - module.exportFunction(prefix + "_exp"); - module.exportFunction(prefix + "_timesScalar"); - module.exportFunction(prefix + "_batchInverse"); - module.exportFunction(prefix + "_isNegative"); - - return prefix; -}; - - -/***/ }), - -/***/ 3911: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -const bigInt = __webpack_require__(2096); -const utils = __webpack_require__(2333); - -module.exports = function buildFFT(module, prefix, gPrefix, fPrefix, opGtimesF) { +var build_fft = function buildFFT(module, prefix, gPrefix, fPrefix, opGtimesF) { const n64f = module.modules[fPrefix].n64; const n8f = n64f*8; @@ -66168,61 +64378,61 @@ module.exports = function buildFFT(module, prefix, gPrefix, fPrefix, opGtimesF) const q = module.modules[fPrefix].q; - let rem = q.minus(bigInt(1)); + let rem = q - 1n; let maxBits = 0; - while (!rem.isOdd()) { + while (!isOdd$2(rem)) { maxBits ++; - rem = rem.shiftRight(1); + rem = rem >> 1n; } - let nr = bigInt(2); + let nr = 2n; - while ( nr.modPow(q.shiftRight(1), q).equals(1) ) nr = nr.add(1); + while ( modPow(nr, q >> 1n, q) === 1n ) nr = nr + 1n; // console.log(nr); const w = new Array(maxBits+1); - w[maxBits] = nr.modPow(rem, q); + w[maxBits] = modPow(nr, rem, q); let n=maxBits-1; while (n>=0) { - w[n] = w[n+1].modPow(2, q); + w[n] = modPow(w[n+1], 2n, q); n--; } const bytes = []; - const R = bigInt(1).shiftLeft(n8f*8).mod(q); + const R = (1n << BigInt(n8f*8)) % q; for (let i=0; i { - /* Copyright 2019 0KIMS association. @@ -67528,1581 +65732,7 @@ module.exports = function buildFFT(module, prefix, gPrefix, fPrefix, opGtimesF) along with wasmsnark. If not, see . */ -const utils = __webpack_require__(2333); - -module.exports = function buildInt(module, n64, _prefix) { - - const prefix = _prefix || "int"; - if (module.modules[prefix]) return prefix; // already builded - module.modules[prefix] = {}; - - const n32 = n64*2; - const n8 = n64*8; - - const one = module.alloc(n8, utils.bigInt2BytesLE(1, n8)); - - function buildCopy() { - const f = module.addFunction(prefix+"_copy"); - f.addParam("px", "i32"); - f.addParam("pr", "i32"); - - const c = f.getCodeBuilder(); - - for (let i=0; i>1) )&&(i>1, k>>1) - ) - ) - ); - - f.addCode( - c.setLocal(c1, - c.i64_add( - c.getLocal(c1), - c.i64_shr_u( - c.getLocal(c0), - c.i64_const(32) - ) - ) - ) - ); - } - - // Add the old carry - - if (k>0) { - f.addCode( - c.setLocal(c0, - c.i64_add( - c.i64_and( - c.getLocal(c0), - c.i64_const(0xFFFFFFFF) - ), - c.i64_and( - c.getLocal(c0_old), - c.i64_const(0xFFFFFFFF) - ), - ) - ) - ); - - f.addCode( - c.setLocal(c1, - c.i64_add( - c.i64_add( - c.getLocal(c1), - c.i64_shr_u( - c.getLocal(c0), - c.i64_const(32) - ) - ), - c.getLocal(c1_old) - ) - ) - ); - } - - f.addCode( - c.i64_store32( - c.getLocal("r"), - k*4, - c.getLocal(c0) - ) - ); - - f.addCode( - c.setLocal( - c0_old, - c.getLocal(c1) - ), - c.setLocal( - c1_old, - c.i64_shr_u( - c.getLocal(c0_old), - c.i64_const(32) - ) - ) - ); - - } - f.addCode( - c.i64_store32( - c.getLocal("r"), - n32*4*2-4, - c.getLocal(c0_old) - ) - ); - - } - - - function buildSquareOld() { - const f = module.addFunction(prefix+"_squareOld"); - f.addParam("x", "i32"); - f.addParam("r", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); - } - - function _buildMul1() { - const f = module.addFunction(prefix+"__mul1"); - f.addParam("px", "i32"); - f.addParam("y", "i64"); - f.addParam("pr", "i32"); - f.addLocal("c", "i64"); - - const c = f.getCodeBuilder(); - - f.addCode(c.setLocal( - "c", - c.i64_mul( - c.i64_load32_u(c.getLocal("px"), 0, 0), - c.getLocal("y") - ) - )); - - f.addCode(c.i64_store32( - c.getLocal("pr"), - 0, - 0, - c.getLocal("c"), - )); - - for (let i=1; i3)&&(Y[eY]==0) ey--; - f.addCode(c.block(c.loop( - c.br_if( - 1, - c.i32_or( - c.i32_load8_u( - c.i32_add(Y , c.getLocal("eY")), - 0, - 0 - ), - c.i32_eq( - c.getLocal("eY"), - c.i32_const(3) - ) - ) - ), - c.setLocal("eY", c.i32_sub(c.getLocal("eY"), c.i32_const(1))), - c.br(0) - ))); - - f.addCode( - c.setLocal( - "sy", - c.i64_add( - c.i64_load32_u( - c.i32_sub( - c.i32_add( Y, c.getLocal("eY")), - c.i32_const(3) - ), - 0, - 0 - ), - c.i64_const(1) - ) - ) - ); - - // Force a divide by 0 if quotien is 0 - f.addCode( - c.if( - c.i64_eq( - c.getLocal("sy"), - c.i64_const(1) - ), - c.drop(c.i64_div_u(c.i64_const(0), c.i64_const(0))) - ) - ); - - f.addCode(c.block(c.loop( - - // while (eX>7)&&(Y[eX]==0) ex--; - c.block(c.loop( - c.br_if( - 1, - c.i32_or( - c.i32_load8_u( - c.i32_add(R , c.getLocal("eX")), - 0, - 0 - ), - c.i32_eq( - c.getLocal("eX"), - c.i32_const(7) - ) - ) - ), - c.setLocal("eX", c.i32_sub(c.getLocal("eX"), c.i32_const(1))), - c.br(0) - )), - - c.setLocal( - "sx", - c.i64_load( - c.i32_sub( - c.i32_add( R, c.getLocal("eX")), - c.i32_const(7) - ), - 0, - 0 - ) - ), - - c.setLocal( - "sx", - c.i64_div_u( - c.getLocal("sx"), - c.getLocal("sy") - ) - ), - c.setLocal( - "ec", - c.i32_sub( - c.i32_sub( - c.getLocal("eX"), - c.getLocal("eY") - ), - c.i32_const(4) - ) - ), - - // While greater than 32 bits or ec is neg, shr and inc exp - c.block(c.loop( - c.br_if( - 1, - c.i32_and( - c.i64_eqz( - c.i64_and( - c.getLocal("sx"), - c.i64_const("0xFFFFFFFF00000000") - ) - ), - c.i32_ge_s( - c.getLocal("ec"), - c.i32_const(0) - ) - ) - ), - - c.setLocal( - "sx", - c.i64_shr_u( - c.getLocal("sx"), - c.i64_const(8) - ) - ), - - c.setLocal( - "ec", - c.i32_add( - c.getLocal("ec"), - c.i32_const(1) - ) - ), - c.br(0) - )), - - c.if( - c.i64_eqz(c.getLocal("sx")), - [ - ...c.br_if( - 2, - c.i32_eqz(c.call(prefix + "_gte", R, Y)) - ), - ...c.setLocal("sx", c.i64_const(1)), - ...c.setLocal("ec", c.i32_const(0)) - ] - ), - - c.call(prefix + "__mul1", Y, c.getLocal("sx"), R2), - c.drop(c.call( - prefix + "_sub", - R, - c.i32_sub(R2, c.getLocal("ec")), - R - )), - c.call( - prefix + "__add1", - c.i32_add(C, c.getLocal("ec")), - c.getLocal("sx") - ), - c.br(0) - ))); - } - - function buildInverseMod() { - - const f = module.addFunction(prefix+"_inverseMod"); - f.addParam("px", "i32"); - f.addParam("pm", "i32"); - f.addParam("pr", "i32"); - f.addLocal("t", "i32"); - f.addLocal("newt", "i32"); - f.addLocal("r", "i32"); - f.addLocal("qq", "i32"); - f.addLocal("qr", "i32"); - f.addLocal("newr", "i32"); - f.addLocal("swp", "i32"); - f.addLocal("x", "i32"); - f.addLocal("signt", "i32"); - f.addLocal("signnewt", "i32"); - f.addLocal("signx", "i32"); - - const c = f.getCodeBuilder(); - - const aux1 = c.i32_const(module.alloc(n8)); - const aux2 = c.i32_const(module.alloc(n8)); - const aux3 = c.i32_const(module.alloc(n8)); - const aux4 = c.i32_const(module.alloc(n8)); - const aux5 = c.i32_const(module.alloc(n8)); - const aux6 = c.i32_const(module.alloc(n8)); - const mulBuff = c.i32_const(module.alloc(n8*2)); - const aux7 = c.i32_const(module.alloc(n8)); - - f.addCode( - c.setLocal("t", aux1), - c.call(prefix + "_zero", aux1), - c.setLocal("signt", c.i32_const(0)), - ); - - f.addCode( - c.setLocal("r", aux2), - c.call(prefix + "_copy", c.getLocal("pm"), aux2) - ); - - f.addCode( - c.setLocal("newt", aux3), - c.call(prefix + "_one", aux3), - c.setLocal("signnewt", c.i32_const(0)), - ); - - f.addCode( - c.setLocal("newr", aux4), - c.call(prefix + "_copy", c.getLocal("px"), aux4) - ); - - - - - f.addCode(c.setLocal("qq", aux5)); - f.addCode(c.setLocal("qr", aux6)); - f.addCode(c.setLocal("x", aux7)); - - f.addCode(c.block(c.loop( - c.br_if( - 1, - c.call(prefix + "_isZero", c.getLocal("newr") ) - ), - c.call(prefix + "_div", c.getLocal("r"), c.getLocal("newr"), c.getLocal("qq"), c.getLocal("qr")), - - c.call(prefix + "_mul", c.getLocal("qq"), c.getLocal("newt"), mulBuff), - - c.if( - c.getLocal("signt"), - c.if( - c.getLocal("signnewt"), - c.if ( - c.call(prefix + "_gte", mulBuff, c.getLocal("t")), - [ - ...c.drop(c.call(prefix + "_sub", mulBuff, c.getLocal("t"), c.getLocal("x"))), - ...c.setLocal("signx", c.i32_const(0)) - ], - [ - ...c.drop(c.call(prefix + "_sub", c.getLocal("t"), mulBuff, c.getLocal("x"))), - ...c.setLocal("signx", c.i32_const(1)) - ], - ), - [ - ...c.drop(c.call(prefix + "_add", mulBuff, c.getLocal("t"), c.getLocal("x"))), - ...c.setLocal("signx", c.i32_const(1)) - ] - ), - c.if( - c.getLocal("signnewt"), - [ - ...c.drop(c.call(prefix + "_add", mulBuff, c.getLocal("t"), c.getLocal("x"))), - ...c.setLocal("signx", c.i32_const(0)) - ], - c.if ( - c.call(prefix + "_gte", c.getLocal("t"), mulBuff), - [ - ...c.drop(c.call(prefix + "_sub", c.getLocal("t"), mulBuff, c.getLocal("x"))), - ...c.setLocal("signx", c.i32_const(0)) - ], - [ - ...c.drop(c.call(prefix + "_sub", mulBuff, c.getLocal("t"), c.getLocal("x"))), - ...c.setLocal("signx", c.i32_const(1)) - ] - ) - ) - ), - - c.setLocal("swp", c.getLocal("t")), - c.setLocal("t", c.getLocal("newt")), - c.setLocal("newt", c.getLocal("x")), - c.setLocal("x", c.getLocal("swp")), - - c.setLocal("signt", c.getLocal("signnewt")), - c.setLocal("signnewt", c.getLocal("signx")), - - c.setLocal("swp", c.getLocal("r")), - c.setLocal("r", c.getLocal("newr")), - c.setLocal("newr", c.getLocal("qr")), - c.setLocal("qr", c.getLocal("swp")), - - c.br(0) - ))); - - f.addCode(c.if( - c.getLocal("signt"), - c.drop(c.call(prefix + "_sub", c.getLocal("pm"), c.getLocal("t"), c.getLocal("pr"))), - c.call(prefix + "_copy", c.getLocal("t"), c.getLocal("pr")) - )); - } - - - buildCopy(); - buildZero(); - buildIsZero(); - buildOne(); - buildEq(); - buildGte(); - buildAdd(); - buildSub(); - buildMul(); - buildSquare(); - buildSquareOld(); - buildDiv(); - buildInverseMod(); - module.exportFunction(prefix+"_copy"); - module.exportFunction(prefix+"_zero"); - module.exportFunction(prefix+"_one"); - module.exportFunction(prefix+"_isZero"); - module.exportFunction(prefix+"_eq"); - module.exportFunction(prefix+"_gte"); - module.exportFunction(prefix+"_add"); - module.exportFunction(prefix+"_sub"); - module.exportFunction(prefix+"_mul"); - module.exportFunction(prefix+"_square"); - module.exportFunction(prefix+"_squareOld"); - module.exportFunction(prefix+"_div"); - module.exportFunction(prefix+"_inverseMod"); - - return prefix; -}; - - -/***/ }), - -/***/ 4911: -/***/ ((module) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -module.exports = function buildMultiexp(module, prefix, fnName, opAdd, n8b) { - - const n64g = module.modules[prefix].n64; - const n8g = n64g*8; - - function buildGetChunk() { - const f = module.addFunction(fnName + "_getChunk"); - f.addParam("pScalar", "i32"); - f.addParam("scalarSize", "i32"); // Number of bytes of the scalar - f.addParam("startBit", "i32"); // Bit to start extract - f.addParam("chunkSize", "i32"); // Chunk size in bits - f.addLocal("bitsToEnd", "i32"); - f.addLocal("mask", "i32"); - f.setReturnType("i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.setLocal("bitsToEnd", - c.i32_sub( - c.i32_mul( - c.getLocal("scalarSize"), - c.i32_const(8) - ), - c.getLocal("startBit") - ) - ), - c.if( - c.i32_gt_s( - c.getLocal("chunkSize"), - c.getLocal("bitsToEnd") - ), - c.setLocal( - "mask", - c.i32_sub( - c.i32_shl( - c.i32_const(1), - c.getLocal("bitsToEnd") - ), - c.i32_const(1) - ) - ), - c.setLocal( - "mask", - c.i32_sub( - c.i32_shl( - c.i32_const(1), - c.getLocal("chunkSize") - ), - c.i32_const(1) - ) - ) - ), - c.i32_and( - c.i32_shr_u( - c.i32_load( - c.i32_add( - c.getLocal("pScalar"), - c.i32_shr_u( - c.getLocal("startBit"), - c.i32_const(3) - ) - ), - 0, // offset - 0 // align to byte. - ), - c.i32_and( - c.getLocal("startBit"), - c.i32_const(0x7) - ) - ), - c.getLocal("mask") - ) - ); - } - - function buildMutiexpChunk() { - const f = module.addFunction(fnName + "_chunk"); - f.addParam("pBases", "i32"); - f.addParam("pScalars", "i32"); - f.addParam("scalarSize", "i32"); // Number of points - f.addParam("n", "i32"); // Number of points - f.addParam("startBit", "i32"); // bit where it starts the chunk - f.addParam("chunkSize", "i32"); // bit where it starts the chunk - f.addParam("pr", "i32"); - f.addLocal("nChunks", "i32"); - f.addLocal("itScalar", "i32"); - f.addLocal("endScalar", "i32"); - f.addLocal("itBase", "i32"); - f.addLocal("i", "i32"); - f.addLocal("j", "i32"); - f.addLocal("nTable", "i32"); - f.addLocal("pTable", "i32"); - f.addLocal("idx", "i32"); - f.addLocal("pIdxTable", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.if( - c.i32_eqz(c.getLocal("n")), - [ - ...c.call(prefix + "_zero", c.getLocal("pr")), - ...c.ret([]) - ] - ), - - // Allocate memory - - c.setLocal( - "nTable", - c.i32_shl( - c.i32_const(1), - c.getLocal("chunkSize") - ) - ), - c.setLocal("pTable", c.i32_load( c.i32_const(0) )), - c.i32_store( - c.i32_const(0), - c.i32_add( - c.getLocal("pTable"), - c.i32_mul( - c.getLocal("nTable"), - c.i32_const(n8g) - ) - ) - ), - - // Reset Table - c.setLocal("j", c.i32_const(0)), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("j"), - c.getLocal("nTable") - ) - ), - - c.call( - prefix + "_zero", - c.i32_add( - c.getLocal("pTable"), - c.i32_mul( - c.getLocal("j"), - c.i32_const(n8g) - ) - ) - ), - - c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), - c.br(0) - )), - - // Distribute elements - c.setLocal("itBase", c.getLocal("pBases")), - c.setLocal("itScalar", c.getLocal("pScalars")), - c.setLocal("endScalar", - c.i32_add( - c.getLocal("pScalars"), - c.i32_mul( - c.getLocal("n"), - c.getLocal("scalarSize") - ) - ) - ), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("itScalar"), - c.getLocal("endScalar") - ) - ), - - c.setLocal( - "idx", - c.call(fnName + "_getChunk", - c.getLocal("itScalar"), - c.getLocal("scalarSize"), - c.getLocal("startBit"), - c.getLocal("chunkSize") - ) - ), - - c.if( - c.getLocal("idx"), - [ - ...c.setLocal( - "pIdxTable", - c.i32_add( - c.getLocal("pTable"), - c.i32_mul( - c.i32_sub( - c.getLocal("idx"), - c.i32_const(1) - ), - c.i32_const(n8g) - ) - ) - ), - ...c.call( - opAdd, - c.getLocal("pIdxTable"), - c.getLocal("itBase"), - c.getLocal("pIdxTable"), - ) - ] - ), - - c.setLocal("itScalar", c.i32_add(c.getLocal("itScalar"), c.getLocal("scalarSize"))), - c.setLocal("itBase", c.i32_add(c.getLocal("itBase"), c.i32_const(n8b))), - c.br(0) - )), - - c.call(fnName + "_reduceTable", c.getLocal("pTable"), c.getLocal("chunkSize")), - c.call( - prefix + "_copy", - c.getLocal("pTable"), - c.getLocal("pr") - ), - - - c.i32_store( - c.i32_const(0), - c.getLocal("pTable") - ) - - ); - } - - function buildMultiexp() { - const f = module.addFunction(fnName); - f.addParam("pBases", "i32"); - f.addParam("pScalars", "i32"); - f.addParam("scalarSize", "i32"); // Number of points - f.addParam("n", "i32"); // Number of points - f.addParam("pr", "i32"); - f.addLocal("chunkSize", "i32"); - f.addLocal("nChunks", "i32"); - f.addLocal("itScalar", "i32"); - f.addLocal("endScalar", "i32"); - f.addLocal("itBase", "i32"); - f.addLocal("itBit", "i32"); - f.addLocal("i", "i32"); - f.addLocal("j", "i32"); - f.addLocal("nTable", "i32"); - f.addLocal("pTable", "i32"); - f.addLocal("idx", "i32"); - f.addLocal("pIdxTable", "i32"); - - const c = f.getCodeBuilder(); - - const aux = c.i32_const(module.alloc(n8g)); - - const pTSizes = module.alloc([ - 17, 17, 17, 17, 17, 17, 17, 17, - 17, 17, 16, 16, 15, 14, 13, 13, - 12, 11, 10, 9, 8, 7, 7, 6, - 5 , 4, 3, 2, 1, 1, 1, 1 - ]); - - f.addCode( - c.call(prefix + "_zero", c.getLocal("pr")), - c.if( - c.i32_eqz(c.getLocal("n")), - c.ret([]) - ), - c.setLocal("chunkSize", c.i32_load8_u( c.i32_clz(c.getLocal("n")), pTSizes )), - c.setLocal( - "nChunks", - c.i32_add( - c.i32_div_u( - c.i32_sub( - c.i32_shl( - c.getLocal("scalarSize"), - c.i32_const(3) - ), - c.i32_const(1) - ), - c.getLocal("chunkSize") - ), - c.i32_const(1) - ) - ), - - - // Allocate memory - - c.setLocal( - "itBit", - c.i32_mul( - c.i32_sub( - c.getLocal("nChunks"), - c.i32_const(1) - ), - c.getLocal("chunkSize") - ) - ), - c.block(c.loop( - c.br_if( - 1, - c.i32_lt_s( - c.getLocal("itBit"), - c.i32_const(0) - ) - ), - - // Double nChunk times - c.if( - c.i32_eqz(c.call(prefix + "_isZero", c.getLocal("pr"))), - [ - ...c.setLocal("j", c.i32_const(0)), - ...c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("j"), - c.getLocal("chunkSize") - ) - ), - - c.call(prefix + "_double", c.getLocal("pr"), c.getLocal("pr")), - - c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), - c.br(0) - )) - ] - ), - - c.call( - fnName + "_chunk", - c.getLocal("pBases"), - c.getLocal("pScalars"), - c.getLocal("scalarSize"), - c.getLocal("n"), - c.getLocal("itBit"), - c.getLocal("chunkSize"), - aux - ), - - c.call( - prefix + "_add", - c.getLocal("pr"), - aux, - c.getLocal("pr") - ), - c.setLocal("itBit", c.i32_sub(c.getLocal("itBit"), c.getLocal("chunkSize"))), - c.br(0) - )) - ); - } - - function buildReduceTable() { - const f = module.addFunction(fnName + "_reduceTable"); - f.addParam("pTable", "i32"); - f.addParam("p", "i32"); // Number of bits of the table - f.addLocal("half", "i32"); - f.addLocal("it1", "i32"); - f.addLocal("it2", "i32"); - f.addLocal("pAcc", "i32"); - - const c = f.getCodeBuilder(); - - f.addCode( - c.if( - c.i32_eq(c.getLocal("p"), c.i32_const(1)), - c.ret([]) - ), - c.setLocal( - "half", - c.i32_shl( - c.i32_const(1), - c.i32_sub( - c.getLocal("p"), - c.i32_const(1) - ) - ) - ), - - c.setLocal("it1", c.getLocal("pTable")), - c.setLocal( - "it2", - c.i32_add( - c.getLocal("pTable"), - c.i32_mul( - c.getLocal("half"), - c.i32_const(n8g) - ) - ) - ), - c.setLocal("pAcc", - c.i32_sub( - c.getLocal("it2"), - c.i32_const(n8g) - ) - ), - c.block(c.loop( - c.br_if( - 1, - c.i32_eq( - c.getLocal("it1"), - c.getLocal("pAcc") - ) - ), - c.call( - prefix + "_add", - c.getLocal("it1"), - c.getLocal("it2"), - c.getLocal("it1") - ), - c.call( - prefix + "_add", - c.getLocal("pAcc"), - c.getLocal("it2"), - c.getLocal("pAcc") - ), - c.setLocal("it1", c.i32_add(c.getLocal("it1"), c.i32_const(n8g))), - c.setLocal("it2", c.i32_add(c.getLocal("it2"), c.i32_const(n8g))), - c.br(0) - )), - - c.call( - fnName + "_reduceTable", - c.getLocal("pTable"), - c.i32_sub( - c.getLocal("p"), - c.i32_const(1) - ) - ), - - c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), - c.block(c.loop( - c.br_if(1, c.i32_eqz(c.getLocal("p"))), - c.call(prefix + "_double", c.getLocal("pAcc"), c.getLocal("pAcc")), - c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), - c.br(0) - )), - - c.call(prefix + "_add", c.getLocal("pTable"), c.getLocal("pAcc"), c.getLocal("pTable")) - ); - } - - buildGetChunk(); - buildReduceTable(); - buildMutiexpChunk(); - buildMultiexp(); - - module.exportFunction(fnName); - module.exportFunction(fnName +"_chunk"); - - -}; - - - - - -/***/ }), - -/***/ 2896: -/***/ ((module) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -module.exports = function buildPol(module, prefix, prefixField) { +var build_pol = function buildPol(module, prefix, prefixField) { const n64 = module.modules[prefixField].n64; const n8 = n64*8; @@ -69242,14 +65872,7 @@ module.exports = function buildPol(module, prefix, prefixField) { }; - -/***/ }), - -/***/ 637: -/***/ ((module) => { - - -module.exports = function buildQAP(module, prefix, prefixField) { +var build_qap = function buildQAP(module, prefix, prefixField) { const n64 = module.modules[prefixField].n64; const n8 = n64*8; @@ -69586,13 +66209,6 @@ module.exports = function buildQAP(module, prefix, prefixField) { }; - - -/***/ }), - -/***/ 5107: -/***/ ((module) => { - /* Copyright 2019 0KIMS association. @@ -69612,320 +66228,3090 @@ module.exports = function buildQAP(module, prefix, prefixField) { along with wasmsnark. If not, see . */ -module.exports = function buildTimesScalar(module, fnName, elementLen, opAB, opAA, opCopy, opInit) { +var build_applykey = function buildApplyKey(module, fnName, gPrefix, frPrefix, sizeGIn, sizeGOut, sizeF, opGtimesF) { const f = module.addFunction(fnName); - f.addParam("base", "i32"); - f.addParam("scalar", "i32"); - f.addParam("scalarLength", "i32"); - f.addParam("r", "i32"); + f.addParam("pIn", "i32"); + f.addParam("n", "i32"); + f.addParam("pFirst", "i32"); + f.addParam("pInc", "i32"); + f.addParam("pOut", "i32"); + f.addLocal("pOldFree", "i32"); f.addLocal("i", "i32"); - f.addLocal("b", "i32"); + f.addLocal("pFrom", "i32"); + f.addLocal("pTo", "i32"); const c = f.getCodeBuilder(); - const aux = c.i32_const(module.alloc(elementLen)); + const t = c.i32_const(module.alloc(sizeF)); f.addCode( - c.if( - c.i32_eqz(c.getLocal("scalarLength")), - [ - ...c.call(opInit, c.getLocal("r")), - ...c.ret([]) - ] + c.setLocal("pFrom", c.getLocal("pIn")), + c.setLocal("pTo", c.getLocal("pOut")), + ); + + // t = first + f.addCode( + c.call( + frPrefix + "_copy", + c.getLocal("pFirst"), + t ) ); - f.addCode(c.call(opCopy, c.getLocal("base"), aux)); - f.addCode(c.call(opInit, c.getLocal("r"))); - f.addCode(c.setLocal("i", c.getLocal("scalarLength"))); - f.addCode(c.block(c.loop( - c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), - - c.setLocal( - "b", - c.i32_load8_u( - c.i32_add( - c.getLocal("scalar"), - c.getLocal("i") - ) - ) - ), - ...innerLoop(), - c.br_if(1, c.i32_eqz ( c.getLocal("i") )), - c.br(0) - ))); - - - function innerLoop() { - const code = []; - for (let i=0; i<8; i++) { - code.push( - ...c.call(opAA, c.getLocal("r"), c.getLocal("r")), - ...c.if( - c.i32_ge_u( c.getLocal("b"), c.i32_const(0x80 >> i)), - [ - ...c.setLocal( - "b", - c.i32_sub( - c.getLocal("b"), - c.i32_const(0x80 >> i) - ) - ), - ...c.call(opAB, c.getLocal("r"),aux, c.getLocal("r")) - ] - ) - ); - } - return code; - } - -}; - - -/***/ }), - -/***/ 3972: -/***/ ((module) => { - -/* - Copyright 2019 0KIMS association. - - This file is part of wasmsnark (Web Assembly zkSnark Prover). - - wasmsnark is a free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - wasmsnark is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - License for more details. - - You should have received a copy of the GNU General Public License - along with wasmsnark. If not, see . -*/ - -module.exports = function buildTimesScalarNAF(module, fnName, elementLen, opAB, opAA, opAmB, opCopy, opInit) { - - const f = module.addFunction(fnName); - f.addParam("base", "i32"); - f.addParam("scalar", "i32"); - f.addParam("scalarLength", "i32"); - f.addParam("r", "i32"); - f.addLocal("old0", "i32"); - f.addLocal("nbits", "i32"); - f.addLocal("i", "i32"); - f.addLocal("last", "i32"); - f.addLocal("cur", "i32"); - f.addLocal("carry", "i32"); - f.addLocal("p", "i32"); - - const c = f.getCodeBuilder(); - - const aux = c.i32_const(module.alloc(elementLen)); - - function getBit(IDX) { - return c.i32_and( - c.i32_shr_u( - c.i32_load( - c.i32_add( - c.getLocal("scalar"), - c.i32_and( - c.i32_shr_u( - IDX, - c.i32_const(3) - ), - c.i32_const(0xFFFFFFFC) - ) - ) - ), - c.i32_and( - IDX, - c.i32_const(0x1F) - ) - ), - c.i32_const(1) - ); - } - - function pushBit(b) { - return [ - ...c.i32_store8( - c.getLocal("p"), - c.i32_const(b) - ), - ...c.setLocal( - "p", - c.i32_add( - c.getLocal("p"), - c.i32_const(1) - ) - ) - ]; - } - f.addCode( - c.if( - c.i32_eqz(c.getLocal("scalarLength")), - [ - ...c.call(opInit, c.getLocal("r")), - ...c.ret([]) - ] - ), - c.setLocal("nbits", c.i32_shl(c.getLocal("scalarLength"), c.i32_const(3))), - c.setLocal("old0", c.i32_load(c.i32_const(0))), - c.setLocal("p", c.getLocal("old0")), - c.i32_store( - c.i32_const(0), - c.i32_and( - c.i32_add( - c.i32_add( - c.getLocal("old0"), - c.i32_const(32) - ), - c.getLocal("nbits") - ), - c.i32_const(0xFFFFFFF8) - ) - ), - c.setLocal("i", c.i32_const(1)), - - c.setLocal("last",getBit(c.i32_const(0))), - c.setLocal("carry",c.i32_const(0)), - + c.setLocal("i", c.i32_const(0)), c.block(c.loop( - c.br_if(1, c.i32_eq( c.getLocal("i"), c.getLocal("nbits"))), + c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), - c.setLocal("cur", getBit(c.getLocal("i"))), - c.if( c.getLocal("last"), - c.if( c.getLocal("cur"), - c.if(c.getLocal("carry"), - [ - ...c.setLocal("last", c.i32_const(0)), - ...c.setLocal("carry", c.i32_const(1)), - ...pushBit(1) - ] - , - [ - ...c.setLocal("last", c.i32_const(0)), - ...c.setLocal("carry", c.i32_const(1)), - ...pushBit(255) - ], - ), - c.if(c.getLocal("carry"), - [ - ...c.setLocal("last", c.i32_const(0)), - ...c.setLocal("carry", c.i32_const(1)), - ...pushBit(255) - ] - , - [ - ...c.setLocal("last", c.i32_const(0)), - ...c.setLocal("carry", c.i32_const(0)), - ...pushBit(1) - ], - ), - ), - c.if( c.getLocal("cur"), - c.if(c.getLocal("carry"), - [ - ...c.setLocal("last", c.i32_const(0)), - ...c.setLocal("carry", c.i32_const(1)), - ...pushBit(0) - ] - , - [ - ...c.setLocal("last", c.i32_const(1)), - ...c.setLocal("carry", c.i32_const(0)), - ...pushBit(0) - ], - ), - c.if(c.getLocal("carry"), - [ - ...c.setLocal("last", c.i32_const(1)), - ...c.setLocal("carry", c.i32_const(0)), - ...pushBit(0) - ] - , - [ - ...c.setLocal("last", c.i32_const(0)), - ...c.setLocal("carry", c.i32_const(0)), - ...pushBit(0) - ], - ), - ) + c.call( + opGtimesF, + c.getLocal("pFrom"), + t, + c.getLocal("pTo") + ), + c.setLocal("pFrom", c.i32_add(c.getLocal("pFrom"), c.i32_const(sizeGIn))), + c.setLocal("pTo", c.i32_add(c.getLocal("pTo"), c.i32_const(sizeGOut))), + + // t = t* inc + c.call( + frPrefix + "_mul", + t, + c.getLocal("pInc"), + t ), c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), c.br(0) - )), - - c.if( c.getLocal("last"), - c.if(c.getLocal("carry"), - [ - ...pushBit(255), - ...pushBit(0), - ...pushBit(1) - ] - , - [ - ...pushBit(1) - ], - ), - c.if(c.getLocal("carry"), - [ - ...pushBit(0), - ...pushBit(1) - ] - ), - ), - - c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), - - // p already points to the last bit - - c.call(opCopy, c.getLocal("base"), aux), - - c.call(opInit, c.getLocal("r")), - - c.block(c.loop( - - - c.call(opAA, c.getLocal("r"), c.getLocal("r")), - - - c.setLocal("cur", - c.i32_load8_u( - c.getLocal("p") - ) - ), - - c.if( - c.getLocal("cur"), - c.if( - c.i32_eq(c.getLocal("cur"), c.i32_const(1)), - c.call(opAB, c.getLocal("r"), aux, c.getLocal("r")), - c.call(opAmB, c.getLocal("r"), aux, c.getLocal("r")), - ) - ), - - c.br_if(1, c.i32_eq( c.getLocal("old0"), c.getLocal("p"))), - c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), - c.br(0) - - )), - - c.i32_store( c.i32_const(0), c.getLocal("old0")) - + )) ); + module.exportFunction(fnName); + }; +const utils$2 = utils$6; -/***/ }), +const buildF1m$1 =build_f1m; +const buildF1$1 =build_f1; +const buildF2m$1 =build_f2m; +const buildF3m$1 =build_f3m; +const buildCurve$1 =build_curve_jacobian_a0; +const buildFFT$2 = build_fft; +const buildPol$1 = build_pol; +const buildQAP$1 = build_qap; +const buildApplyKey$1 = build_applykey; +const { bitLength: bitLength$2, modInv, isOdd: isOdd$1, isNegative: isNegative$2 } = bigint; -/***/ 2333: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +var build_bn128 = function buildBN128(module, _prefix) { + + const prefix = _prefix || "bn128"; + + if (module.modules[prefix]) return prefix; // already builded + + const q = 21888242871839275222246405745257275088696311157297823662689037894645226208583n; + const r = 21888242871839275222246405745257275088548364400416034343698204186575808495617n; + + + const n64 = Math.floor((bitLength$2(q - 1n) - 1)/64) +1; + const n8 = n64*8; + const frsize = n8; + const f1size = n8; + const f2size = f1size * 2; + const ftsize = f1size * 12; + + const pr = module.alloc(utils$2.bigInt2BytesLE( r, frsize )); + + const f1mPrefix = buildF1m$1(module, q, "f1m"); + buildF1$1(module, r, "fr", "frm"); + + const pG1b = module.alloc(utils$2.bigInt2BytesLE( toMontgomery(3n), f1size )); + const g1mPrefix = buildCurve$1(module, "g1m", "f1m", pG1b); + + buildFFT$2(module, "frm", "frm", "frm", "frm_mul"); + + buildPol$1(module, "pol", "frm"); + buildQAP$1(module, "qap", "frm"); + + const f2mPrefix = buildF2m$1(module, "f1m_neg", "f2m", "f1m"); + const pG2b = module.alloc([ + ...utils$2.bigInt2BytesLE( toMontgomery(19485874751759354771024239261021720505790618469301721065564631296452457478373n), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(266929791119991161246907387137283842545076965332900288569378510910307636690n), f1size ) + ]); + const g2mPrefix = buildCurve$1(module, "g2m", "f2m", pG2b); + + + function buildGTimesFr(fnName, opMul) { + const f = module.addFunction(fnName); + f.addParam("pG", "i32"); + f.addParam("pFr", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.call("frm_fromMontgomery", c.getLocal("pFr"), AUX), + c.call( + opMul, + c.getLocal("pG"), + AUX, + c.i32_const(n8), + c.getLocal("pr") + ) + ); + + module.exportFunction(fnName); + } + buildGTimesFr("g1m_timesFr", "g1m_timesScalar"); + buildFFT$2(module, "g1m", "g1m", "frm", "g1m_timesFr"); + + buildGTimesFr("g2m_timesFr", "g2m_timesScalar"); + buildFFT$2(module, "g2m", "g2m", "frm", "g2m_timesFr"); + + buildGTimesFr("g1m_timesFrAffine", "g1m_timesScalarAffine"); + buildGTimesFr("g2m_timesFrAffine", "g2m_timesScalarAffine"); + + buildApplyKey$1(module, "frm_batchApplyKey", "fmr", "frm", n8, n8, n8, "frm_mul"); + buildApplyKey$1(module, "g1m_batchApplyKey", "g1m", "frm", n8*3, n8*3, n8, "g1m_timesFr"); + buildApplyKey$1(module, "g1m_batchApplyKeyMixed", "g1m", "frm", n8*2, n8*3, n8, "g1m_timesFrAffine"); + buildApplyKey$1(module, "g2m_batchApplyKey", "g2m", "frm", n8*2*3, n8*3*2, n8, "g2m_timesFr"); + buildApplyKey$1(module, "g2m_batchApplyKeyMixed", "g2m", "frm", n8*2*2, n8*3*2, n8, "g2m_timesFrAffine"); + + function toMontgomery(a) { + return BigInt(a) * ( 1n << BigInt(f1size*8)) % q; + } + + const G1gen = [ + 1n, + 2n, + 1n + ]; + + const pG1gen = module.alloc( + [ + ...utils$2.bigInt2BytesLE( toMontgomery(G1gen[0]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G1gen[1]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G1gen[2]), f1size ), + ] + ); + + const G1zero = [ + 0n, + 1n, + 0n + ]; + + const pG1zero = module.alloc( + [ + ...utils$2.bigInt2BytesLE( toMontgomery(G1zero[0]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G1zero[1]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G1zero[2]), f1size ) + ] + ); + + const G2gen = [ + [ + 10857046999023057135944570762232829481370756359578518086990519993285655852781n, + 11559732032986387107991004021392285783925812861821192530917403151452391805634n, + ],[ + 8495653923123431417604973247489272438418190587263600148770280649306958101930n, + 4082367875863433681332203403145435568316851327593401208105741076214120093531n, + ],[ + 1n, + 0n, + ] + ]; + + const pG2gen = module.alloc( + [ + ...utils$2.bigInt2BytesLE( toMontgomery(G2gen[0][0]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G2gen[0][1]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G2gen[1][0]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G2gen[1][1]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G2gen[2][0]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G2gen[2][1]), f1size ), + ] + ); + + const G2zero = [ + [ + 0n, + 0n, + ],[ + 1n, + 0n, + ],[ + 0n, + 0n, + ] + ]; + + const pG2zero = module.alloc( + [ + ...utils$2.bigInt2BytesLE( toMontgomery(G2zero[0][0]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G2zero[0][1]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G2zero[1][0]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G2zero[1][1]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G2zero[2][0]), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(G2zero[2][1]), f1size ), + ] + ); + + const pOneT = module.alloc([ + ...utils$2.bigInt2BytesLE( toMontgomery(1), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(0), f1size ), + ]); + + const pNonResidueF6 = module.alloc([ + ...utils$2.bigInt2BytesLE( toMontgomery(9), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(1), f1size ), + ]); + + const pTwoInv = module.alloc([ + ...utils$2.bigInt2BytesLE( toMontgomery( modInv(2n, q)), f1size ), + ...utils$2.bigInt2BytesLE( 0n, f1size ) + ]); + + const pAltBn128Twist = pNonResidueF6; + + const pTwistCoefB = module.alloc([ + ...utils$2.bigInt2BytesLE( toMontgomery(19485874751759354771024239261021720505790618469301721065564631296452457478373n), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery(266929791119991161246907387137283842545076965332900288569378510910307636690n), f1size ), + ]); + + function build_mulNR6() { + const f = module.addFunction(prefix + "_mulNR6"); + f.addParam("x", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call( + f2mPrefix + "_mul", + c.i32_const(pNonResidueF6), + c.getLocal("x"), + c.getLocal("pr") + ) + ); + } + build_mulNR6(); + + const f6mPrefix = buildF3m$1(module, prefix+"_mulNR6", "f6m", "f2m"); + + function build_mulNR12() { + const f = module.addFunction(prefix + "_mulNR12"); + f.addParam("x", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call( + f2mPrefix + "_mul", + c.i32_const(pNonResidueF6), + c.i32_add(c.getLocal("x"), c.i32_const(n8*4)), + c.getLocal("pr") + ), + c.call( + f2mPrefix + "_copy", + c.getLocal("x"), + c.i32_add(c.getLocal("pr"), c.i32_const(n8*2)), + ), + c.call( + f2mPrefix + "_copy", + c.i32_add(c.getLocal("x"), c.i32_const(n8*2)), + c.i32_add(c.getLocal("pr"), c.i32_const(n8*4)), + ) + ); + } + build_mulNR12(); + + const ftmPrefix = buildF2m$1(module, prefix+"_mulNR12", "ftm", f6mPrefix); + + + const ateLoopCount = 29793968203157093288n; + const ateLoopBitBytes = bits(ateLoopCount); + const pAteLoopBitBytes = module.alloc(ateLoopBitBytes); + + const ateCoefSize = 3 * f2size; + const ateNDblCoefs = ateLoopBitBytes.length-1; + const ateNAddCoefs = ateLoopBitBytes.reduce((acc, b) => acc + ( b!=0 ? 1 : 0) ,0); + const ateNCoefs = ateNAddCoefs + ateNDblCoefs + 1; + const prePSize = 3*2*n8; + const preQSize = 3*n8*2 + ateNCoefs*ateCoefSize; + + + module.modules[prefix] = { + n64: n64, + pG1gen: pG1gen, + pG1zero: pG1zero, + pG1b: pG1b, + pG2gen: pG2gen, + pG2zero: pG2zero, + pG2b: pG2b, + pq: module.modules["f1m"].pq, + pr: pr, + pOneT: pOneT, + prePSize: prePSize, + preQSize: preQSize, + r: r.toString(), + q: q.toString() + }; + + // console.log("PrePSize: " +prePSize); + // console.log("PreQSize: " +preQSize); + + const finalExpZ = 4965661367192848881n; + + function naf(n) { + let E = n; + const res = []; + while (E > 0n) { + if (isOdd$1(E)) { + const z = 2 - Number(E % 4n); + res.push( z ); + E = E - BigInt(z); + } else { + res.push( 0 ); + } + E = E >> 1n; + } + return res; + } + + function bits(n) { + let E = n; + const res = []; + while (E > 0n) { + if (isOdd$1(E)) { + res.push( 1 ); + } else { + res.push( 0 ); + } + E = E >> 1n; + } + return res; + } + + function buildPrepareG1() { + const f = module.addFunction(prefix+ "_prepareG1"); + f.addParam("pP", "i32"); + f.addParam("ppreP", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(g1mPrefix + "_normalize", c.getLocal("pP"), c.getLocal("ppreP")), // TODO Remove if already in affine + ); + } + + function buildPrepAddStep() { + const f = module.addFunction(prefix+ "_prepAddStep"); + f.addParam("pQ", "i32"); + f.addParam("pR", "i32"); + f.addParam("pCoef", "i32"); + + const c = f.getCodeBuilder(); + + const X2 = c.getLocal("pQ"); + const Y2 = c.i32_add(c.getLocal("pQ"), c.i32_const(f2size)); + + const X1 = c.getLocal("pR"); + const Y1 = c.i32_add(c.getLocal("pR"), c.i32_const(f2size)); + const Z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*f2size)); + + const ELL_0 = c.getLocal("pCoef"); + const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); + const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); + + const D = ELL_VW; + const E = c.i32_const(module.alloc(f2size)); + const F = c.i32_const(module.alloc(f2size)); + const G = c.i32_const(module.alloc(f2size)); + const H = c.i32_const(module.alloc(f2size)); + const I = c.i32_const(module.alloc(f2size)); + const J = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + f.addCode( + // D = X1 - X2*Z1 + c.call(f2mPrefix + "_mul", X2, Z1, D), + c.call(f2mPrefix + "_sub", X1, D, D), + + // E = Y1 - Y2*Z1 + c.call(f2mPrefix + "_mul", Y2, Z1, E), + c.call(f2mPrefix + "_sub", Y1, E, E), + + // F = D^2 + c.call(f2mPrefix + "_square", D, F), + + // G = E^2 + c.call(f2mPrefix + "_square", E, G), + + // H = D*F + c.call(f2mPrefix + "_mul", D, F, H), + + // I = X1 * F + c.call(f2mPrefix + "_mul", X1, F, I), + + // J = H + Z1*G - (I+I) + c.call(f2mPrefix + "_add", I, I, AUX), + c.call(f2mPrefix + "_mul", Z1, G, J), + c.call(f2mPrefix + "_add", H, J, J), + c.call(f2mPrefix + "_sub", J, AUX, J), + + + // X3 (X1) = D*J + c.call(f2mPrefix + "_mul", D, J, X1), + + // Y3 (Y1) = E*(I-J)-(H*Y1) + c.call(f2mPrefix + "_mul", H, Y1, Y1), + c.call(f2mPrefix + "_sub", I, J, AUX), + c.call(f2mPrefix + "_mul", E, AUX, AUX), + c.call(f2mPrefix + "_sub", AUX, Y1, Y1), + + // Z3 (Z1) = Z1*H + c.call(f2mPrefix + "_mul", Z1, H, Z1), + + // ell_0 = xi * (E * X2 - D * Y2) + c.call(f2mPrefix + "_mul", D, Y2, AUX), + c.call(f2mPrefix + "_mul", E, X2, ELL_0), + c.call(f2mPrefix + "_sub", ELL_0, AUX, ELL_0), + c.call(f2mPrefix + "_mul", ELL_0, c.i32_const(pAltBn128Twist), ELL_0), + + + // ell_VV = - E (later: * xP) + c.call(f2mPrefix + "_neg", E, ELL_VV), + + // ell_VW = D (later: * yP ) + // Already assigned + + ); + } + + + + function buildPrepDoubleStep() { + const f = module.addFunction(prefix+ "_prepDblStep"); + f.addParam("pR", "i32"); + f.addParam("pCoef", "i32"); + + const c = f.getCodeBuilder(); + + const X1 = c.getLocal("pR"); + const Y1 = c.i32_add(c.getLocal("pR"), c.i32_const(f2size)); + const Z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*f2size)); + + const ELL_0 = c.getLocal("pCoef"); + const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); + const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); + + const A = c.i32_const(module.alloc(f2size)); + const B = c.i32_const(module.alloc(f2size)); + const C = c.i32_const(module.alloc(f2size)); + const D = c.i32_const(module.alloc(f2size)); + const E = c.i32_const(module.alloc(f2size)); + const F = c.i32_const(module.alloc(f2size)); + const G = c.i32_const(module.alloc(f2size)); + const H = c.i32_const(module.alloc(f2size)); + const I = c.i32_const(module.alloc(f2size)); + const J = c.i32_const(module.alloc(f2size)); + const E2 = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + f.addCode( + + // A = X1 * Y1 / 2 + c.call(f2mPrefix + "_mul", Y1, c.i32_const(pTwoInv), A), + c.call(f2mPrefix + "_mul", X1, A, A), + + // B = Y1^2 + c.call(f2mPrefix + "_square", Y1, B), + + // C = Z1^2 + c.call(f2mPrefix + "_square", Z1, C), + + // D = 3 * C + c.call(f2mPrefix + "_add", C, C, D), + c.call(f2mPrefix + "_add", D, C, D), + + // E = twist_b * D + c.call(f2mPrefix + "_mul", c.i32_const(pTwistCoefB), D, E), + + // F = 3 * E + c.call(f2mPrefix + "_add", E, E, F), + c.call(f2mPrefix + "_add", E, F, F), + + // G = (B+F)/2 + c.call(f2mPrefix + "_add", B, F, G), + c.call(f2mPrefix + "_mul", G, c.i32_const(pTwoInv), G), + + // H = (Y1+Z1)^2-(B+C) + c.call(f2mPrefix + "_add", B, C, AUX), + c.call(f2mPrefix + "_add", Y1, Z1, H), + c.call(f2mPrefix + "_square", H, H), + c.call(f2mPrefix + "_sub", H, AUX, H), + + // I = E-B + c.call(f2mPrefix + "_sub", E, B, I), + + // J = X1^2 + c.call(f2mPrefix + "_square", X1, J), + + // E_squared = E^2 + c.call(f2mPrefix + "_square", E, E2), + + // X3 (X1) = A * (B-F) + c.call(f2mPrefix + "_sub", B, F, AUX), + c.call(f2mPrefix + "_mul", A, AUX, X1), + + // Y3 (Y1) = G^2 - 3*E^2 + c.call(f2mPrefix + "_add", E2, E2, AUX), + c.call(f2mPrefix + "_add", E2, AUX, AUX), + c.call(f2mPrefix + "_square", G, Y1), + c.call(f2mPrefix + "_sub", Y1, AUX, Y1), + + // Z3 (Z1) = B * H + c.call(f2mPrefix + "_mul", B, H, Z1), + + // ell_0 = xi * I + c.call(f2mPrefix + "_mul", c.i32_const(pAltBn128Twist), I, ELL_0), + + // ell_VW = - H (later: * yP) + c.call(f2mPrefix + "_neg", H, ELL_VW), + + // ell_VV = 3*J (later: * xP) + c.call(f2mPrefix + "_add", J, J, ELL_VV), + c.call(f2mPrefix + "_add", J, ELL_VV, ELL_VV), + + ); + } + + function buildMulByQ() { + const f = module.addFunction(prefix + "_mulByQ"); + f.addParam("p1", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + const x = c.getLocal("p1"); + const y = c.i32_add(c.getLocal("p1"), c.i32_const(f2size)); + const z = c.i32_add(c.getLocal("p1"), c.i32_const(f2size*2)); + const x3 = c.getLocal("pr"); + const y3 = c.i32_add(c.getLocal("pr"), c.i32_const(f2size)); + const z3 = c.i32_add(c.getLocal("pr"), c.i32_const(f2size*2)); + + const MulByQX = c.i32_const(module.alloc([ + ...utils$2.bigInt2BytesLE( toMontgomery("21575463638280843010398324269430826099269044274347216827212613867836435027261"), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery("10307601595873709700152284273816112264069230130616436755625194854815875713954"), f1size ), + ])); + + const MulByQY = c.i32_const(module.alloc([ + ...utils$2.bigInt2BytesLE( toMontgomery("2821565182194536844548159561693502659359617185244120367078079554186484126554"), f1size ), + ...utils$2.bigInt2BytesLE( toMontgomery("3505843767911556378687030309984248845540243509899259641013678093033130930403"), f1size ), + ])); + + f.addCode( + // The frobeniusMap(1) in this field, is the conjugate + c.call(f2mPrefix + "_conjugate", x, x3), + c.call(f2mPrefix + "_mul", MulByQX, x3, x3), + c.call(f2mPrefix + "_conjugate", y, y3), + c.call(f2mPrefix + "_mul", MulByQY, y3, y3), + c.call(f2mPrefix + "_conjugate", z, z3), + ); + } + + + function buildPrepareG2() { + buildMulByQ(); + const f = module.addFunction(prefix+ "_prepareG2"); + f.addParam("pQ", "i32"); + f.addParam("ppreQ", "i32"); + f.addLocal("pCoef", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const QX = c.getLocal("pQ"); + + const pR = module.alloc(f2size*3); + const R = c.i32_const(pR); + const RX = c.i32_const(pR); + const RY = c.i32_const(pR+f2size); + const RZ = c.i32_const(pR+2*f2size); + + const cQX = c.i32_add( c.getLocal("ppreQ"), c.i32_const(0)); + const cQY = c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size)); + + const pQ1 = module.alloc(f2size*3); + const Q1 = c.i32_const(pQ1); + + const pQ2 = module.alloc(f2size*3); + const Q2 = c.i32_const(pQ2); + const Q2Y = c.i32_const(pQ2 + f2size); + + f.addCode( + c.call(g2mPrefix + "_normalize", QX, cQX), // TODO Remove if already in affine + c.call(f2mPrefix + "_copy", cQX, RX), + c.call(f2mPrefix + "_copy", cQY, RY), + c.call(f2mPrefix + "_one", RZ), + ); + + f.addCode( + c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), + c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), + c.block(c.loop( + + c.call(prefix + "_prepDblStep", R, c.getLocal("pCoef")), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.if( + c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), + [ + ...c.call(prefix + "_prepAddStep", cQX, R, c.getLocal("pCoef")), + ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + ] + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + + f.addCode( + c.call(prefix + "_mulByQ", cQX, Q1), + c.call(prefix + "_mulByQ", Q1, Q2) + ); + + f.addCode( + c.call(f2mPrefix + "_neg", Q2Y, Q2Y), + + c.call(prefix + "_prepAddStep", Q1, R, c.getLocal("pCoef")), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.call(prefix + "_prepAddStep", Q2, R, c.getLocal("pCoef")), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + ); + } + + function buildMulBy024Old() { + const f = module.addFunction(prefix+ "__mulBy024Old"); + f.addParam("pEll0", "i32"); + f.addParam("pEllVW", "i32"); + f.addParam("pEllVV", "i32"); + f.addParam("pR", "i32"); // Result in F12 + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("pEll0"); + const x2 = c.getLocal("pEllVV"); + const x4 = c.getLocal("pEllVW"); + + const z0 = c.getLocal("pR"); + + const pAUX12 = module.alloc(ftsize); + const AUX12 = c.i32_const(pAUX12); + const AUX12_0 = c.i32_const(pAUX12); + const AUX12_2 = c.i32_const(pAUX12+f2size); + const AUX12_4 = c.i32_const(pAUX12+f2size*2); + const AUX12_6 = c.i32_const(pAUX12+f2size*3); + const AUX12_8 = c.i32_const(pAUX12+f2size*4); + const AUX12_10 = c.i32_const(pAUX12+f2size*5); + + f.addCode( + + c.call(f2mPrefix + "_copy", x0, AUX12_0), + c.call(f2mPrefix + "_zero", AUX12_2), + c.call(f2mPrefix + "_copy", x2, AUX12_4), + c.call(f2mPrefix + "_zero", AUX12_6), + c.call(f2mPrefix + "_copy", x4, AUX12_8), + c.call(f2mPrefix + "_zero", AUX12_10), + c.call(ftmPrefix + "_mul", AUX12, z0, z0), + ); + } + + function buildMulBy024() { + const f = module.addFunction(prefix+ "__mulBy024"); + f.addParam("pEll0", "i32"); + f.addParam("pEllVW", "i32"); + f.addParam("pEllVV", "i32"); + f.addParam("pR", "i32"); // Result in F12 + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("pEll0"); + const x2 = c.getLocal("pEllVV"); + const x4 = c.getLocal("pEllVW"); + + const z0 = c.getLocal("pR"); + const z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*n8)); + const z2 = c.i32_add(c.getLocal("pR"), c.i32_const(4*n8)); + const z3 = c.i32_add(c.getLocal("pR"), c.i32_const(6*n8)); + const z4 = c.i32_add(c.getLocal("pR"), c.i32_const(8*n8)); + const z5 = c.i32_add(c.getLocal("pR"), c.i32_const(10*n8)); + + const t0 = c.i32_const(module.alloc(f2size)); + const t1 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const s0 = c.i32_const(module.alloc(f2size)); + const T3 = c.i32_const(module.alloc(f2size)); + const T4 = c.i32_const(module.alloc(f2size)); + const D0 = c.i32_const(module.alloc(f2size)); + const D2 = c.i32_const(module.alloc(f2size)); + const D4 = c.i32_const(module.alloc(f2size)); + const S1 = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + f.addCode( + + // D0 = z0 * x0; + c.call(f2mPrefix + "_mul", z0, x0, D0), + // D2 = z2 * x2; + c.call(f2mPrefix + "_mul", z2, x2, D2), + // D4 = z4 * x4; + c.call(f2mPrefix + "_mul", z4, x4, D4), + // t2 = z0 + z4; + c.call(f2mPrefix + "_add", z0, z4, t2), + // t1 = z0 + z2; + c.call(f2mPrefix + "_add", z0, z2, t1), + // s0 = z1 + z3 + z5; + c.call(f2mPrefix + "_add", z1, z3, s0), + c.call(f2mPrefix + "_add", s0, z5, s0), + + + // For z.a_.a_ = z0. + // S1 = z1 * x2; + c.call(f2mPrefix + "_mul", z1, x2, S1), + // T3 = S1 + D4; + c.call(f2mPrefix + "_add", S1, D4, T3), + // T4 = my_Fp6::non_residue * T3 + D0; + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), + c.call(f2mPrefix + "_add", T4, D0, z0), + // z0 = T4; + + // For z.a_.b_ = z1 + // T3 = z5 * x4; + c.call(f2mPrefix + "_mul", z5, x4, T3), + // S1 = S1 + T3; + c.call(f2mPrefix + "_add", S1, T3, S1), + // T3 = T3 + D2; + c.call(f2mPrefix + "_add", T3, D2, T3), + // T4 = my_Fp6::non_residue * T3; + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), + // T3 = z1 * x0; + c.call(f2mPrefix + "_mul", z1, x0, T3), + // S1 = S1 + T3; + c.call(f2mPrefix + "_add", S1, T3, S1), + // T4 = T4 + T3; + c.call(f2mPrefix + "_add", T4, T3, z1), + // z1 = T4; + + + + // For z.a_.c_ = z2 + // t0 = x0 + x2; + c.call(f2mPrefix + "_add", x0, x2, t0), + // T3 = t1 * t0 - D0 - D2; + c.call(f2mPrefix + "_mul", t1, t0, T3), + c.call(f2mPrefix + "_add", D0, D2, AUX), + c.call(f2mPrefix + "_sub", T3, AUX, T3), + // T4 = z3 * x4; + c.call(f2mPrefix + "_mul", z3, x4, T4), + // S1 = S1 + T4; + c.call(f2mPrefix + "_add", S1, T4, S1), + + + // For z.b_.a_ = z3 (z3 needs z2) + // t0 = z2 + z4; + c.call(f2mPrefix + "_add", z2, z4, t0), + // T3 = T3 + T4; + // z2 = T3; + c.call(f2mPrefix + "_add", T3, T4, z2), + // t1 = x2 + x4; + c.call(f2mPrefix + "_add", x2, x4, t1), + // T3 = t0 * t1 - D2 - D4; + c.call(f2mPrefix + "_mul", t1, t0, T3), + c.call(f2mPrefix + "_add", D2, D4, AUX), + c.call(f2mPrefix + "_sub", T3, AUX, T3), + // T4 = my_Fp6::non_residue * T3; + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), + // T3 = z3 * x0; + c.call(f2mPrefix + "_mul", z3, x0, T3), + // S1 = S1 + T3; + c.call(f2mPrefix + "_add", S1, T3, S1), + // T4 = T4 + T3; + c.call(f2mPrefix + "_add", T4, T3, z3), + // z3 = T4; + + // For z.b_.b_ = z4 + // T3 = z5 * x2; + c.call(f2mPrefix + "_mul", z5, x2, T3), + // S1 = S1 + T3; + c.call(f2mPrefix + "_add", S1, T3, S1), + // T4 = my_Fp6::non_residue * T3; + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), + // t0 = x0 + x4; + c.call(f2mPrefix + "_add", x0, x4, t0), + // T3 = t2 * t0 - D0 - D4; + c.call(f2mPrefix + "_mul", t2, t0, T3), + c.call(f2mPrefix + "_add", D0, D4, AUX), + c.call(f2mPrefix + "_sub", T3, AUX, T3), + // T4 = T4 + T3; + c.call(f2mPrefix + "_add", T4, T3, z4), + // z4 = T4; + + // For z.b_.c_ = z5. + // t0 = x0 + x2 + x4; + c.call(f2mPrefix + "_add", x0, x2, t0), + c.call(f2mPrefix + "_add", t0, x4, t0), + // T3 = s0 * t0 - S1; + c.call(f2mPrefix + "_mul", s0, t0, T3), + c.call(f2mPrefix + "_sub", T3, S1, z5), + // z5 = T3; + + ); + } + + + function buildMillerLoop() { + const f = module.addFunction(prefix+ "_millerLoop"); + f.addParam("ppreP", "i32"); + f.addParam("ppreQ", "i32"); + f.addParam("r", "i32"); + f.addLocal("pCoef", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const preP_PX = c.getLocal("ppreP"); + const preP_PY = c.i32_add(c.getLocal("ppreP"), c.i32_const(f1size)); + + const ELL_0 = c.getLocal("pCoef"); + const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); + const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); + + + const pVW = module.alloc(f2size); + const VW = c.i32_const(pVW); + const pVV = module.alloc(f2size); + const VV = c.i32_const(pVV); + + const F = c.getLocal("r"); + + + f.addCode( + c.call(ftmPrefix + "_one", F), + + c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), + + c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), + c.block(c.loop( + + + c.call(ftmPrefix + "_square", F, F), + + c.call(f2mPrefix + "_mul1", ELL_VW,preP_PY, VW), + c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), + c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.if( + c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), + [ + ...c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), + ...c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), + + ...c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), + ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + ] + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + + ); + + f.addCode( + c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), + c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), + c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), + c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), + c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + ); + + } + + + function buildFrobeniusMap(n) { + const F12 = [ + [ + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + ], + [ + [1n, 0n], + [8376118865763821496583973867626364092589906065868298776909617916018768340080n, 16469823323077808223889137241176536799009286646108169935659301613961712198316n], + [21888242871839275220042445260109153167277707414472061641714758635765020556617n, 0n], + [11697423496358154304825782922584725312912383441159505038794027105778954184319n, 303847389135065887422783454877609941456349188919719272345083954437860409601n], + [21888242871839275220042445260109153167277707414472061641714758635765020556616n, 0n], + [3321304630594332808241809054958361220322477375291206261884409189760185844239n, 5722266937896532885780051958958348231143373700109372999374820235121374419868n], + [21888242871839275222246405745257275088696311157297823662689037894645226208582n, 0n], + [13512124006075453725662431877630910996106405091429524885779419978626457868503n, 5418419548761466998357268504080738289687024511189653727029736280683514010267n], + [2203960485148121921418603742825762020974279258880205651966n, 0n], + [10190819375481120917420622822672549775783927716138318623895010788866272024264n, 21584395482704209334823622290379665147239961968378104390343953940207365798982n], + [2203960485148121921418603742825762020974279258880205651967n, 0n], + [18566938241244942414004596690298913868373833782006617400804628704885040364344n, 16165975933942742336466353786298926857552937457188450663314217659523851788715n], + ] + ]; + + const F6 = [ + [ + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + ], + [ + [1n, 0n], + [21575463638280843010398324269430826099269044274347216827212613867836435027261n, 10307601595873709700152284273816112264069230130616436755625194854815875713954n], + [21888242871839275220042445260109153167277707414472061641714758635765020556616n, 0n], + [3772000881919853776433695186713858239009073593817195771773381919316419345261n, 2236595495967245188281701248203181795121068902605861227855261137820944008926n], + [2203960485148121921418603742825762020974279258880205651966n, 0n], + [18429021223477853657660792034369865839114504446431234726392080002137598044644n, 9344045779998320333812420223237981029506012124075525679208581902008406485703n], + ], + [ + [1n, 0n], + [2581911344467009335267311115468803099551665605076196740867805258568234346338n, 19937756971775647987995932169929341994314640652964949448313374472400716661030n], + [2203960485148121921418603742825762020974279258880205651966n, 0n], + [5324479202449903542726783395506214481928257762400643279780343368557297135718n, 16208900380737693084919495127334387981393726419856888799917914180988844123039n], + [21888242871839275220042445260109153167277707414472061641714758635765020556616n, 0n], + [13981852324922362344252311234282257507216387789820983642040889267519694726527n, 7629828391165209371577384193250820201684255241773809077146787135900891633097n], + ] + ]; + + const f = module.addFunction(prefix+ "__frobeniusMap"+n); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + for (let i=0; i<6; i++) { + const X = (i==0) ? c.getLocal("x") : c.i32_add(c.getLocal("x"), c.i32_const(i*f2size)); + const Xc0 = X; + const Xc1 = c.i32_add(c.getLocal("x"), c.i32_const(i*f2size + f1size)); + const R = (i==0) ? c.getLocal("r") : c.i32_add(c.getLocal("r"), c.i32_const(i*f2size)); + const Rc0 = R; + const Rc1 = c.i32_add(c.getLocal("r"), c.i32_const(i*f2size + f1size)); + const coef = mul2(F12[Math.floor(i/3)][n%12] , F6[i%3][n%6]); + const pCoef = module.alloc([ + ...utils$2.bigInt2BytesLE(toMontgomery(coef[0]), 32), + ...utils$2.bigInt2BytesLE(toMontgomery(coef[1]), 32), + ]); + if (n%2 == 1) { + f.addCode( + c.call(f1mPrefix + "_copy", Xc0, Rc0), + c.call(f1mPrefix + "_neg", Xc1, Rc1), + c.call(f2mPrefix + "_mul", R, c.i32_const(pCoef), R), + ); + } else { + f.addCode(c.call(f2mPrefix + "_mul", X, c.i32_const(pCoef), R)); + } + } + + function mul2(a, b) { + const ac0 = BigInt(a[0]); + const ac1 = BigInt(a[1]); + const bc0 = BigInt(b[0]); + const bc1 = BigInt(b[1]); + const res = [ + (ac0 * bc0 - ( ac1 * bc1) ) % q, + (ac0 * bc1 + ( ac1 * bc0) ) % q, + ]; + if (isNegative$2(res[0])) res[0] = res[0] + q; + return res; + } + + } + + + + function buildFinalExponentiationFirstChunk() { + + const f = module.addFunction(prefix+ "__finalExponentiationFirstChunk"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const elt = c.getLocal("x"); + const eltC0 = elt; + const eltC1 = c.i32_add(elt, c.i32_const(n8*6)); + const r = c.getLocal("r"); + const pA = module.alloc(ftsize); + const A = c.i32_const(pA); + const Ac0 = A; + const Ac1 = c.i32_const(pA + n8*6); + const B = c.i32_const(module.alloc(ftsize)); + const C = c.i32_const(module.alloc(ftsize)); + const D = c.i32_const(module.alloc(ftsize)); + + f.addCode( + // const alt_bn128_Fq12 A = alt_bn128_Fq12(elt.c0,-elt.c1); + c.call(f6mPrefix + "_copy", eltC0, Ac0), + c.call(f6mPrefix + "_neg", eltC1, Ac1), + + // const alt_bn128_Fq12 B = elt.inverse(); + c.call(ftmPrefix + "_inverse", elt, B), + + // const alt_bn128_Fq12 C = A * B; + c.call(ftmPrefix + "_mul", A, B, C), + // const alt_bn128_Fq12 D = C.Frobenius_map(2); + c.call(prefix + "__frobeniusMap2", C, D), + // const alt_bn128_Fq12 result = D * C; + c.call(ftmPrefix + "_mul", C, D, r), + ); + } + + function buildCyclotomicSquare() { + const f = module.addFunction(prefix+ "__cyclotomicSquare"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x4 = c.i32_add(c.getLocal("x"), c.i32_const(f2size)); + const x3 = c.i32_add(c.getLocal("x"), c.i32_const(2*f2size)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(3*f2size)); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(4*f2size)); + const x5 = c.i32_add(c.getLocal("x"), c.i32_const(5*f2size)); + + const r0 = c.getLocal("r"); + const r4 = c.i32_add(c.getLocal("r"), c.i32_const(f2size)); + const r3 = c.i32_add(c.getLocal("r"), c.i32_const(2*f2size)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(3*f2size)); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(4*f2size)); + const r5 = c.i32_add(c.getLocal("r"), c.i32_const(5*f2size)); + + const t0 = c.i32_const(module.alloc(f2size)); + const t1 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const t3 = c.i32_const(module.alloc(f2size)); + const t4 = c.i32_const(module.alloc(f2size)); + const t5 = c.i32_const(module.alloc(f2size)); + const tmp = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + + f.addCode( + // // t0 + t1*y = (z0 + z1*y)^2 = a^2 + // tmp = z0 * z1; + // t0 = (z0 + z1) * (z0 + my_Fp6::non_residue * z1) - tmp - my_Fp6::non_residue * tmp; + // t1 = tmp + tmp; + c.call(f2mPrefix + "_mul", x0, x1, tmp), + c.call(f2mPrefix + "_mul", x1, c.i32_const(pNonResidueF6), t0), + c.call(f2mPrefix + "_add", x0, t0, t0), + c.call(f2mPrefix + "_add", x0, x1, AUX), + c.call(f2mPrefix + "_mul", AUX, t0, t0), + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t0, AUX, t0), + c.call(f2mPrefix + "_add", tmp, tmp, t1), + + // // t2 + t3*y = (z2 + z3*y)^2 = b^2 + // tmp = z2 * z3; + // t2 = (z2 + z3) * (z2 + my_Fp6::non_residue * z3) - tmp - my_Fp6::non_residue * tmp; + // t3 = tmp + tmp; + c.call(f2mPrefix + "_mul", x2, x3, tmp), + c.call(f2mPrefix + "_mul", x3, c.i32_const(pNonResidueF6), t2), + c.call(f2mPrefix + "_add", x2, t2, t2), + c.call(f2mPrefix + "_add", x2, x3, AUX), + c.call(f2mPrefix + "_mul", AUX, t2, t2), + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t2, AUX, t2), + c.call(f2mPrefix + "_add", tmp, tmp, t3), + + // // t4 + t5*y = (z4 + z5*y)^2 = c^2 + // tmp = z4 * z5; + // t4 = (z4 + z5) * (z4 + my_Fp6::non_residue * z5) - tmp - my_Fp6::non_residue * tmp; + // t5 = tmp + tmp; + c.call(f2mPrefix + "_mul", x4, x5, tmp), + c.call(f2mPrefix + "_mul", x5, c.i32_const(pNonResidueF6), t4), + c.call(f2mPrefix + "_add", x4, t4, t4), + c.call(f2mPrefix + "_add", x4, x5, AUX), + c.call(f2mPrefix + "_mul", AUX, t4, t4), + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t4, AUX, t4), + c.call(f2mPrefix + "_add", tmp, tmp, t5), + + // For A + // z0 = 3 * t0 - 2 * z0 + c.call(f2mPrefix + "_sub", t0, x0, r0), + c.call(f2mPrefix + "_add", r0, r0, r0), + c.call(f2mPrefix + "_add", t0, r0, r0), + // z1 = 3 * t1 + 2 * z1 + c.call(f2mPrefix + "_add", t1, x1, r1), + c.call(f2mPrefix + "_add", r1, r1, r1), + c.call(f2mPrefix + "_add", t1, r1, r1), + + // For B + // z2 = 3 * (xi * t5) + 2 * z2 + c.call(f2mPrefix + "_mul", t5, c.i32_const(pAltBn128Twist), AUX), + c.call(f2mPrefix + "_add", AUX, x2, r2), + c.call(f2mPrefix + "_add", r2, r2, r2), + c.call(f2mPrefix + "_add", AUX, r2, r2), + // z3 = 3 * t4 - 2 * z3 + c.call(f2mPrefix + "_sub", t4, x3, r3), + c.call(f2mPrefix + "_add", r3, r3, r3), + c.call(f2mPrefix + "_add", t4, r3, r3), + + // For C + // z4 = 3 * t2 - 2 * z4 + c.call(f2mPrefix + "_sub", t2, x4, r4), + c.call(f2mPrefix + "_add", r4, r4, r4), + c.call(f2mPrefix + "_add", t2, r4, r4), + // z5 = 3 * t3 + 2 * z5 + c.call(f2mPrefix + "_add", t3, x5, r5), + c.call(f2mPrefix + "_add", r5, r5, r5), + c.call(f2mPrefix + "_add", t3, r5, r5), + + ); + } + + + function buildCyclotomicExp(exponent, fnName) { + const exponentNafBytes = naf(exponent).map( (b) => (b==-1 ? 0xFF: b) ); + const pExponentNafBytes = module.alloc(exponentNafBytes); + + const f = module.addFunction(prefix+ "__cyclotomicExp_"+fnName); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + f.addLocal("bit", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const x = c.getLocal("x"); + + const res = c.getLocal("r"); + + const inverse = c.i32_const(module.alloc(ftsize)); + + + f.addCode( + c.call(ftmPrefix + "_conjugate", x, inverse), + c.call(ftmPrefix + "_one", res), + + c.if( + c.teeLocal("bit", c.i32_load8_s(c.i32_const(exponentNafBytes.length-1), pExponentNafBytes)), + c.if( + c.i32_eq( + c.getLocal("bit"), + c.i32_const(1) + ), + c.call(ftmPrefix + "_mul", res, x, res), + c.call(ftmPrefix + "_mul", res, inverse, res), + ) + ), + + c.setLocal("i", c.i32_const(exponentNafBytes.length-2)), + c.block(c.loop( + c.call(prefix + "__cyclotomicSquare", res, res), + c.if( + c.teeLocal("bit", c.i32_load8_s(c.getLocal("i"), pExponentNafBytes)), + c.if( + c.i32_eq( + c.getLocal("bit"), + c.i32_const(1) + ), + c.call(ftmPrefix + "_mul", res, x, res), + c.call(ftmPrefix + "_mul", res, inverse, res), + ) + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + + + function buildFinalExponentiationLastChunk() { + buildCyclotomicSquare(); + buildCyclotomicExp(finalExpZ, "w0"); + + const f = module.addFunction(prefix+ "__finalExponentiationLastChunk"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const elt = c.getLocal("x"); + const result = c.getLocal("r"); + const A = c.i32_const(module.alloc(ftsize)); + const B = c.i32_const(module.alloc(ftsize)); + const C = c.i32_const(module.alloc(ftsize)); + const D = c.i32_const(module.alloc(ftsize)); + const E = c.i32_const(module.alloc(ftsize)); + const F = c.i32_const(module.alloc(ftsize)); + const G = c.i32_const(module.alloc(ftsize)); + const H = c.i32_const(module.alloc(ftsize)); + const I = c.i32_const(module.alloc(ftsize)); + const J = c.i32_const(module.alloc(ftsize)); + const K = c.i32_const(module.alloc(ftsize)); + const L = c.i32_const(module.alloc(ftsize)); + const M = c.i32_const(module.alloc(ftsize)); + const N = c.i32_const(module.alloc(ftsize)); + const O = c.i32_const(module.alloc(ftsize)); + const P = c.i32_const(module.alloc(ftsize)); + const Q = c.i32_const(module.alloc(ftsize)); + const R = c.i32_const(module.alloc(ftsize)); + const S = c.i32_const(module.alloc(ftsize)); + const T = c.i32_const(module.alloc(ftsize)); + const U = c.i32_const(module.alloc(ftsize)); + + f.addCode( + + + // A = exp_by_neg_z(elt) // = elt^(-z) + c.call(prefix + "__cyclotomicExp_w0", elt, A), + c.call(ftmPrefix + "_conjugate", A, A), + // B = A^2 // = elt^(-2*z) + c.call(prefix + "__cyclotomicSquare", A, B), + // C = B^2 // = elt^(-4*z) + c.call(prefix + "__cyclotomicSquare", B, C), + // D = C * B // = elt^(-6*z) + c.call(ftmPrefix + "_mul", C, B, D), + // E = exp_by_neg_z(D) // = elt^(6*z^2) + c.call(prefix + "__cyclotomicExp_w0", D, E), + c.call(ftmPrefix + "_conjugate", E, E), + // F = E^2 // = elt^(12*z^2) + c.call(prefix + "__cyclotomicSquare", E, F), + // G = epx_by_neg_z(F) // = elt^(-12*z^3) + c.call(prefix + "__cyclotomicExp_w0", F, G), + c.call(ftmPrefix + "_conjugate", G, G), + // H = conj(D) // = elt^(6*z) + c.call(ftmPrefix + "_conjugate", D, H), + // I = conj(G) // = elt^(12*z^3) + c.call(ftmPrefix + "_conjugate", G, I), + // J = I * E // = elt^(12*z^3 + 6*z^2) + c.call(ftmPrefix + "_mul", I, E, J), + // K = J * H // = elt^(12*z^3 + 6*z^2 + 6*z) + c.call(ftmPrefix + "_mul", J, H, K), + // L = K * B // = elt^(12*z^3 + 6*z^2 + 4*z) + c.call(ftmPrefix + "_mul", K, B, L), + // M = K * E // = elt^(12*z^3 + 12*z^2 + 6*z) + c.call(ftmPrefix + "_mul", K, E, M), + + // N = M * elt // = elt^(12*z^3 + 12*z^2 + 6*z + 1) + c.call(ftmPrefix + "_mul", M, elt, N), + + // O = L.Frobenius_map(1) // = elt^(q*(12*z^3 + 6*z^2 + 4*z)) + c.call(prefix + "__frobeniusMap1", L, O), + // P = O * N // = elt^(q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) + c.call(ftmPrefix + "_mul", O, N, P), + // Q = K.Frobenius_map(2) // = elt^(q^2 * (12*z^3 + 6*z^2 + 6*z)) + c.call(prefix + "__frobeniusMap2", K, Q), + // R = Q * P // = elt^(q^2 * (12*z^3 + 6*z^2 + 6*z) + q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) + c.call(ftmPrefix + "_mul", Q, P, R), + // S = conj(elt) // = elt^(-1) + c.call(ftmPrefix + "_conjugate", elt, S), + // T = S * L // = elt^(12*z^3 + 6*z^2 + 4*z - 1) + c.call(ftmPrefix + "_mul", S, L, T), + // U = T.Frobenius_map(3) // = elt^(q^3(12*z^3 + 6*z^2 + 4*z - 1)) + c.call(prefix + "__frobeniusMap3", T, U), + // V = U * R // = elt^(q^3(12*z^3 + 6*z^2 + 4*z - 1) + q^2 * (12*z^3 + 6*z^2 + 6*z) + q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) + c.call(ftmPrefix + "_mul", U, R, result), + // result = V + ); + } + + + function buildFinalExponentiation() { + buildFinalExponentiationFirstChunk(); + buildFinalExponentiationLastChunk(); + const f = module.addFunction(prefix+ "_finalExponentiation"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const elt = c.getLocal("x"); + const result = c.getLocal("r"); + const eltToFirstChunk = c.i32_const(module.alloc(ftsize)); + + f.addCode( + c.call(prefix + "__finalExponentiationFirstChunk", elt, eltToFirstChunk ), + c.call(prefix + "__finalExponentiationLastChunk", eltToFirstChunk, result ) + ); + } + + + function buildFinalExponentiationOld() { + const f = module.addFunction(prefix+ "_finalExponentiationOld"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const exponent = 552484233613224096312617126783173147097382103762957654188882734314196910839907541213974502761540629817009608548654680343627701153829446747810907373256841551006201639677726139946029199968412598804882391702273019083653272047566316584365559776493027495458238373902875937659943504873220554161550525926302303331747463515644711876653177129578303191095900909191624817826566688241804408081892785725967931714097716709526092261278071952560171111444072049229123565057483750161460024353346284167282452756217662335528813519139808291170539072125381230815729071544861602750936964829313608137325426383735122175229541155376346436093930287402089517426973178917569713384748081827255472576937471496195752727188261435633271238710131736096299798168852925540549342330775279877006784354801422249722573783561685179618816480037695005515426162362431072245638324744480n; + + const pExponent = module.alloc(utils$2.bigInt2BytesLE( exponent, 352 )); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(ftmPrefix + "_exp", c.getLocal("x"), c.i32_const(pExponent), c.i32_const(352), c.getLocal("r")), + ); + } + + + + + const pPreP = module.alloc(prePSize); + const pPreQ = module.alloc(preQSize); + + function buildPairingEquation(nPairings) { + + const f = module.addFunction(prefix+ "_pairingEq"+nPairings); + for (let i=0; i acc + ( b!=0 ? 1 : 0) ,0); + const ateNCoefs = ateNAddCoefs + ateNDblCoefs + 1; + const prePSize = 3*2*n8q; + const preQSize = 3*n8q*2 + ateNCoefs*ateCoefSize; + const finalExpIsNegative = true; + + const finalExpZ = 15132376222941642752n; + + + module.modules[prefix] = { + n64q: n64q, + n64r: n64r, + n8q: n8q, + n8r: n8r, + pG1gen: pG1gen, + pG1zero: pG1zero, + pG1b: pG1b, + pG2gen: pG2gen, + pG2zero: pG2zero, + pG2b: pG2b, + pq: module.modules["f1m"].pq, + pr: pr, + pOneT: pOneT, + r: r, + q: q, + prePSize: prePSize, + preQSize: preQSize + }; + + + function naf(n) { + let E = n; + const res = []; + while (E > 0n) { + if (isOdd(E)) { + const z = 2 - Number(E % 4n); + res.push( z ); + E = E - BigInt(z); + } else { + res.push( 0 ); + } + E = E >> 1n; + } + return res; + } + + function bits(n) { + let E = n; + const res = []; + while (E > 0n) { + if (isOdd(E)) { + res.push( 1 ); + } else { + res.push( 0 ); + } + E = E >> 1n; + } + return res; + } + + function buildPrepareG1() { + const f = module.addFunction(prefix+ "_prepareG1"); + f.addParam("pP", "i32"); + f.addParam("ppreP", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(g1mPrefix + "_normalize", c.getLocal("pP"), c.getLocal("ppreP")), // TODO Remove if already in affine + ); + } + + + + function buildPrepDoubleStep() { + const f = module.addFunction(prefix+ "_prepDblStep"); + f.addParam("R", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const Rx = c.getLocal("R"); + const Ry = c.i32_add(c.getLocal("R"), c.i32_const(2*n8q)); + const Rz = c.i32_add(c.getLocal("R"), c.i32_const(4*n8q)); + + const t0 = c.getLocal("r"); + const t3 = c.i32_add(c.getLocal("r"), c.i32_const(2*n8q)); + const t6 = c.i32_add(c.getLocal("r"), c.i32_const(4*n8q)); + + + const zsquared = c.i32_const(module.alloc(f2size)); + const t1 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const t4 = c.i32_const(module.alloc(f2size)); + const t5 = c.i32_const(module.alloc(f2size)); + + f.addCode( + + // tmp0 = r.x.square(); + c.call(f2mPrefix + "_square", Rx, t0), + + // tmp1 = r.y.square(); + c.call(f2mPrefix + "_square", Ry, t1), + + // tmp2 = tmp1.square(); + c.call(f2mPrefix + "_square", t1, t2), + + // tmp3 = (tmp1 + r.x).square() - tmp0 - tmp2; + c.call(f2mPrefix + "_add", t1, Rx, t3), + c.call(f2mPrefix + "_square", t3, t3), + c.call(f2mPrefix + "_sub", t3, t0, t3), + c.call(f2mPrefix + "_sub", t3, t2, t3), + + // tmp3 = tmp3 + tmp3; + c.call(f2mPrefix + "_add", t3, t3, t3), + + // tmp4 = tmp0 + tmp0 + tmp0; + c.call(f2mPrefix + "_add", t0, t0, t4), + c.call(f2mPrefix + "_add", t4, t0, t4), + + // tmp6 = r.x + tmp4; + c.call(f2mPrefix + "_add", Rx, t4, t6), + + // tmp5 = tmp4.square(); + c.call(f2mPrefix + "_square", t4, t5), + + // zsquared = r.z.square(); + c.call(f2mPrefix + "_square", Rz, zsquared), + + // r.x = tmp5 - tmp3 - tmp3; + c.call(f2mPrefix + "_sub", t5, t3, Rx), + c.call(f2mPrefix + "_sub", Rx, t3, Rx), + + // r.z = (r.z + r.y).square() - tmp1 - zsquared; + c.call(f2mPrefix + "_add", Rz, Ry, Rz), + c.call(f2mPrefix + "_square", Rz, Rz), + c.call(f2mPrefix + "_sub", Rz, t1, Rz), + c.call(f2mPrefix + "_sub", Rz, zsquared, Rz), + + // r.y = (tmp3 - r.x) * tmp4; + c.call(f2mPrefix + "_sub", t3, Rx, Ry), + c.call(f2mPrefix + "_mul", Ry, t4, Ry), + + // tmp2 = tmp2 + tmp2; + c.call(f2mPrefix + "_add", t2, t2, t2), + + // tmp2 = tmp2 + tmp2; + c.call(f2mPrefix + "_add", t2, t2, t2), + + // tmp2 = tmp2 + tmp2; + c.call(f2mPrefix + "_add", t2, t2, t2), + + // r.y -= tmp2; + c.call(f2mPrefix + "_sub", Ry, t2, Ry), + + // tmp3 = tmp4 * zsquared; + c.call(f2mPrefix + "_mul", t4, zsquared, t3), + + // tmp3 = tmp3 + tmp3; + c.call(f2mPrefix + "_add", t3, t3, t3), + + // tmp3 = -tmp3; + c.call(f2mPrefix + "_neg", t3, t3), + + // tmp6 = tmp6.square() - tmp0 - tmp5; + c.call(f2mPrefix + "_square", t6, t6), + c.call(f2mPrefix + "_sub", t6, t0, t6), + c.call(f2mPrefix + "_sub", t6, t5, t6), + + // tmp1 = tmp1 + tmp1; + c.call(f2mPrefix + "_add", t1, t1, t1), + + // tmp1 = tmp1 + tmp1; + c.call(f2mPrefix + "_add", t1, t1, t1), + + // tmp6 = tmp6 - tmp1; + c.call(f2mPrefix + "_sub", t6, t1, t6), + + // tmp0 = r.z * zsquared; + c.call(f2mPrefix + "_mul", Rz, zsquared, t0), + + // tmp0 = tmp0 + tmp0; + c.call(f2mPrefix + "_add", t0, t0, t0), + + ); + } + + function buildPrepAddStep() { + const f = module.addFunction(prefix+ "_prepAddStep"); + f.addParam("R", "i32"); + f.addParam("Q", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const Rx = c.getLocal("R"); + const Ry = c.i32_add(c.getLocal("R"), c.i32_const(2*n8q)); + const Rz = c.i32_add(c.getLocal("R"), c.i32_const(4*n8q)); + + const Qx = c.getLocal("Q"); + const Qy = c.i32_add(c.getLocal("Q"), c.i32_const(2*n8q)); + + const t10 = c.getLocal("r"); + const t1 = c.i32_add(c.getLocal("r"), c.i32_const(2*n8q)); + const t9 = c.i32_add(c.getLocal("r"), c.i32_const(4*n8q)); + + const zsquared = c.i32_const(module.alloc(f2size)); + const ysquared = c.i32_const(module.alloc(f2size)); + const ztsquared = c.i32_const(module.alloc(f2size)); + const t0 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const t3 = c.i32_const(module.alloc(f2size)); + const t4 = c.i32_const(module.alloc(f2size)); + const t5 = c.i32_const(module.alloc(f2size)); + const t6 = c.i32_const(module.alloc(f2size)); + const t7 = c.i32_const(module.alloc(f2size)); + const t8 = c.i32_const(module.alloc(f2size)); + + f.addCode( + + // zsquared = r.z.square(); + c.call(f2mPrefix + "_square", Rz, zsquared), + + // ysquared = q.y.square(); + c.call(f2mPrefix + "_square", Qy, ysquared), + + // t0 = zsquared * q.x; + c.call(f2mPrefix + "_mul", zsquared, Qx, t0), + + // t1 = ((q.y + r.z).square() - ysquared - zsquared) * zsquared; + c.call(f2mPrefix + "_add", Qy, Rz, t1), + c.call(f2mPrefix + "_square", t1, t1), + c.call(f2mPrefix + "_sub", t1, ysquared, t1), + c.call(f2mPrefix + "_sub", t1, zsquared, t1), + c.call(f2mPrefix + "_mul", t1, zsquared, t1), + + // t2 = t0 - r.x; + c.call(f2mPrefix + "_sub", t0, Rx, t2), + + // t3 = t2.square(); + c.call(f2mPrefix + "_square", t2, t3), + + // t4 = t3 + t3; + c.call(f2mPrefix + "_add", t3, t3, t4), + + // t4 = t4 + t4; + c.call(f2mPrefix + "_add", t4, t4, t4), + + // t5 = t4 * t2; + c.call(f2mPrefix + "_mul", t4, t2, t5), + + // t6 = t1 - r.y - r.y; + c.call(f2mPrefix + "_sub", t1, Ry, t6), + c.call(f2mPrefix + "_sub", t6, Ry, t6), + + // t9 = t6 * q.x; + c.call(f2mPrefix + "_mul", t6, Qx, t9), + + // t7 = t4 * r.x; + c.call(f2mPrefix + "_mul", t4, Rx, t7), + + // r.x = t6.square() - t5 - t7 - t7; + c.call(f2mPrefix + "_square", t6, Rx), + c.call(f2mPrefix + "_sub", Rx, t5, Rx), + c.call(f2mPrefix + "_sub", Rx, t7, Rx), + c.call(f2mPrefix + "_sub", Rx, t7, Rx), + + // r.z = (r.z + t2).square() - zsquared - t3; + c.call(f2mPrefix + "_add", Rz, t2, Rz), + c.call(f2mPrefix + "_square", Rz, Rz), + c.call(f2mPrefix + "_sub", Rz, zsquared, Rz), + c.call(f2mPrefix + "_sub", Rz, t3, Rz), + + // t10 = q.y + r.z; + c.call(f2mPrefix + "_add", Qy, Rz, t10), + + // t8 = (t7 - r.x) * t6; + c.call(f2mPrefix + "_sub", t7, Rx, t8), + c.call(f2mPrefix + "_mul", t8, t6, t8), + + // t0 = r.y * t5; + c.call(f2mPrefix + "_mul", Ry, t5, t0), + + // t0 = t0 + t0; + c.call(f2mPrefix + "_add", t0, t0, t0), + + // r.y = t8 - t0; + c.call(f2mPrefix + "_sub", t8, t0, Ry), + + // t10 = t10.square() - ysquared; + c.call(f2mPrefix + "_square", t10, t10), + c.call(f2mPrefix + "_sub", t10, ysquared, t10), + + // ztsquared = r.z.square(); + c.call(f2mPrefix + "_square", Rz, ztsquared), + + // t10 = t10 - ztsquared; + c.call(f2mPrefix + "_sub", t10, ztsquared, t10), + + // t9 = t9 + t9 - t10; + c.call(f2mPrefix + "_add", t9, t9, t9), + c.call(f2mPrefix + "_sub", t9, t10, t9), + + // t10 = r.z + r.z; + c.call(f2mPrefix + "_add", Rz, Rz, t10), + + // t6 = -t6; + c.call(f2mPrefix + "_neg", t6, t6), + + // t1 = t6 + t6; + c.call(f2mPrefix + "_add", t6, t6, t1), + ); + } + + + function buildPrepareG2() { + const f = module.addFunction(prefix+ "_prepareG2"); + f.addParam("pQ", "i32"); + f.addParam("ppreQ", "i32"); + f.addLocal("pCoef", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + + const Q = c.getLocal("pQ"); + + const pR = module.alloc(f2size*3); + const R = c.i32_const(pR); + + const base = c.getLocal("ppreQ"); + + f.addCode( + c.call(g2mPrefix + "_normalize", Q, base), + c.if( + c.call(g2mPrefix + "_isZero", base), + c.ret([]) + ), + c.call(g2mPrefix + "_copy", base, R), + c.setLocal("pCoef", c.i32_add(c.getLocal("ppreQ"), c.i32_const(f2size*3))), + ); + + f.addCode( + c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), + c.block(c.loop( + + c.call(prefix + "_prepDblStep", R, c.getLocal("pCoef")), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.if( + c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), + [ + ...c.call(prefix + "_prepAddStep", R, base, c.getLocal("pCoef")), + ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + ] + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + + function buildF6Mul1() { + const f = module.addFunction(f6mPrefix+ "_mul1"); + f.addParam("pA", "i32"); // F6 + f.addParam("pC1", "i32"); // F2 + f.addParam("pR", "i32"); // F6 + + const c = f.getCodeBuilder(); + + const A_c0 = c.getLocal("pA"); + const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*2)); + const A_c2 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*4)); + + const c1 = c.getLocal("pC1"); + + const t1 = c.getLocal("pR"); + const t2 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*2)); + const b_b = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*4)); + + const Ac0_Ac1 = c.i32_const(module.alloc(f1size*2)); + const Ac1_Ac2 = c.i32_const(module.alloc(f1size*2)); + + f.addCode( + + c.call(f2mPrefix + "_add", A_c0, A_c1, Ac0_Ac1), + c.call(f2mPrefix + "_add", A_c1, A_c2, Ac1_Ac2), + + // let b_b = self.c1 * c1; + c.call(f2mPrefix + "_mul", A_c1, c1, b_b), + + // let t1 = (self.c1 + self.c2) * c1 - b_b; + c.call(f2mPrefix + "_mul", Ac1_Ac2, c1, t1), + c.call(f2mPrefix + "_sub", t1, b_b, t1), + + // let t1 = t1.mul_by_nonresidue(); + c.call(f2mPrefix + "_mulNR", t1, t1), + + // let t2 = (self.c0 + self.c1) * c1 - b_b; + c.call(f2mPrefix + "_mul", Ac0_Ac1, c1, t2), + c.call(f2mPrefix + "_sub", t2, b_b, t2), + ); + } + buildF6Mul1(); + + function buildF6Mul01() { + const f = module.addFunction(f6mPrefix+ "_mul01"); + f.addParam("pA", "i32"); // F6 + f.addParam("pC0", "i32"); // F2 + f.addParam("pC1", "i32"); // F2 + f.addParam("pR", "i32"); // F6 + + const c = f.getCodeBuilder(); + + const A_c0 = c.getLocal("pA"); + const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*2)); + const A_c2 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*4)); + + const c0 = c.getLocal("pC0"); + const c1 = c.getLocal("pC1"); + + const t1 = c.getLocal("pR"); + const t2 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*2)); + const t3 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*4)); + + const a_a = c.i32_const(module.alloc(f1size*2)); + const b_b = c.i32_const(module.alloc(f1size*2)); + const Ac0_Ac1 = c.i32_const(module.alloc(f1size*2)); + const Ac0_Ac2 = c.i32_const(module.alloc(f1size*2)); + + f.addCode( + // let a_a = self.c0 * c0; + c.call(f2mPrefix + "_mul", A_c0, c0, a_a), + + // let b_b = self.c1 * c1; + c.call(f2mPrefix + "_mul", A_c1, c1, b_b), + + + c.call(f2mPrefix + "_add", A_c0, A_c1, Ac0_Ac1), + c.call(f2mPrefix + "_add", A_c0, A_c2, Ac0_Ac2), + + // let t1 = (self.c1 + self.c2) * c1 - b_b; + c.call(f2mPrefix + "_add", A_c1, A_c2, t1), + c.call(f2mPrefix + "_mul", t1, c1, t1), + c.call(f2mPrefix + "_sub", t1, b_b, t1), + + // let t1 = t1.mul_by_nonresidue() + a_a; + c.call(f2mPrefix + "_mulNR", t1, t1), + c.call(f2mPrefix + "_add", t1, a_a, t1), + + // let t2 = (c0 + c1) * (self.c0 + self.c1) - a_a - b_b; + c.call(f2mPrefix + "_add", c0, c1, t2), + c.call(f2mPrefix + "_mul", t2, Ac0_Ac1, t2), + c.call(f2mPrefix + "_sub", t2, a_a, t2), + c.call(f2mPrefix + "_sub", t2, b_b, t2), + + // let t3 = (self.c0 + self.c2) * c0 - a_a + b_b; + c.call(f2mPrefix + "_mul", Ac0_Ac2, c0, t3), + c.call(f2mPrefix + "_sub", t3, a_a, t3), + c.call(f2mPrefix + "_add", t3, b_b, t3), + + + ); + } + buildF6Mul01(); + + + function buildF12Mul014() { + + const f = module.addFunction(ftmPrefix+ "_mul014"); + f.addParam("pA", "i32"); // F12 + f.addParam("pC0", "i32"); // F2 + f.addParam("pC1", "i32"); // F2 + f.addParam("pC4", "i32"); // F2 + f.addParam("pR", "i32"); // F12 + + const c = f.getCodeBuilder(); + + + const A_c0 = c.getLocal("pA"); + const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*6)); + + const c0 = c.getLocal("pC0"); + const c1 = c.getLocal("pC1"); + const c4 = c.getLocal("pC4"); + + const aa = c.i32_const(module.alloc(f1size*6)); + const bb = c.i32_const(module.alloc(f1size*6)); + const o = c.i32_const(module.alloc(f1size*2)); + + const R_c0 = c.getLocal("pR"); + const R_c1 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*6)); + + f.addCode( + // let aa = self.c0.mul_by_01(c0, c1); + c.call(f6mPrefix + "_mul01", A_c0, c0, c1, aa), + + // let bb = self.c1.mul_by_1(c4); + c.call(f6mPrefix + "_mul1", A_c1, c4, bb), + + // let o = c1 + c4; + c.call(f2mPrefix + "_add", c1, c4, o), + + // let c1 = self.c1 + self.c0; + c.call(f6mPrefix + "_add", A_c1, A_c0, R_c1), + + // let c1 = c1.mul_by_01(c0, &o); + c.call(f6mPrefix + "_mul01", R_c1, c0, o, R_c1), + + // let c1 = c1 - aa - bb; + c.call(f6mPrefix + "_sub", R_c1, aa, R_c1), + c.call(f6mPrefix + "_sub", R_c1, bb, R_c1), + + // let c0 = bb; + c.call(f6mPrefix + "_copy", bb, R_c0), + + // let c0 = c0.mul_by_nonresidue(); + c.call(f6mPrefix + "_mulNR", R_c0, R_c0), + + // let c0 = c0 + aa; + c.call(f6mPrefix + "_add", R_c0, aa, R_c0), + ); + } + buildF12Mul014(); + + + function buildELL() { + const f = module.addFunction(prefix+ "_ell"); + f.addParam("pP", "i32"); + f.addParam("pCoefs", "i32"); + f.addParam("pF", "i32"); + + const c = f.getCodeBuilder(); + + const Px = c.getLocal("pP"); + const Py = c.i32_add(c.getLocal("pP"), c.i32_const(n8q)); + + const F = c.getLocal("pF"); + + const coef0_0 = c.getLocal("pCoefs"); + const coef0_1 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size)); + const coef1_0 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*2)); + const coef1_1 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*3)); + const coef2 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*4)); + + const pc0 = module.alloc(f1size*2); + const c0 = c.i32_const(pc0); + const c0_c0 = c.i32_const(pc0); + const c0_c1 = c.i32_const(pc0+f1size); + + const pc1 = module.alloc(f1size*2); + const c1 = c.i32_const(pc1); + const c1_c0 = c.i32_const(pc1); + const c1_c1 = c.i32_const(pc1+f1size); + f.addCode( + // let mut c0 = coeffs.0; + // let mut c1 = coeffs.1; + // + // c0.c0 *= p.y; + // c0.c1 *= p.y; + // + // c1.c0 *= p.x; + // c1.c1 *= p.x; + // + // f.mul_by_014(&coeffs.2, &c1, &c0) + + c.call(f1mPrefix + "_mul", coef0_0, Py, c0_c0), + c.call(f1mPrefix + "_mul", coef0_1, Py, c0_c1), + c.call(f1mPrefix + "_mul", coef1_0, Px, c1_c0), + c.call(f1mPrefix + "_mul", coef1_1, Px, c1_c1), + + c.call(ftmPrefix + "_mul014", F, coef2, c1, c0, F), + + ); + + } + buildELL(); + + function buildMillerLoop() { + const f = module.addFunction(prefix+ "_millerLoop"); + f.addParam("ppreP", "i32"); + f.addParam("ppreQ", "i32"); + f.addParam("r", "i32"); + f.addLocal("pCoef", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const preP = c.getLocal("ppreP"); + + const coefs = c.getLocal("pCoef"); + + const F = c.getLocal("r"); + + + f.addCode( + c.call(ftmPrefix + "_one", F), + + c.if( + c.call(g1mPrefix + "_isZero", preP), + c.ret([]) + ), + c.if( + c.call(g1mPrefix + "_isZero", c.getLocal("ppreQ")), + c.ret([]) + ), + c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), + + c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), + c.block(c.loop( + + + c.call(prefix + "_ell", preP, coefs, F), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.if( + c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), + [ + ...c.call(prefix + "_ell", preP, coefs, F), + ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + ] + ), + c.call(ftmPrefix + "_square", F, F), + + c.br_if(1, c.i32_eq ( c.getLocal("i"), c.i32_const(1) )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + c.call(prefix + "_ell", preP, coefs, F), + + ); + + + { + f.addCode( + c.call(ftmPrefix + "_conjugate", F, F), + ); + } + } + + + function buildFrobeniusMap(n) { + const F12 = [ + [ + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + ], + [ + [1n, 0n], + [3850754370037169011952147076051364057158807420970682438676050522613628423219637725072182697113062777891589506424760n, 151655185184498381465642749684540099398075398968325446656007613510403227271200139370504932015952886146304766135027n], + [793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620351n, 0n], + [2973677408986561043442465346520108879172042883009249989176415018091420807192182638567116318576472649347015917690530n, 1028732146235106349975324479215795277384839936929757896155643118032610843298655225875571310552543014690878354869257n], + [793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350n, 0n], + [3125332594171059424908108096204648978570118281977575435832422631601824034463382777937621250592425535493320683825557n, 877076961050607968509681729531255177986764537961432449499635504522207616027455086505066378536590128544573588734230n], + [4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786n, 0n], + [151655185184498381465642749684540099398075398968325446656007613510403227271200139370504932015952886146304766135027n, 3850754370037169011952147076051364057158807420970682438676050522613628423219637725072182697113062777891589506424760n], + [4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436n, 0n], + [1028732146235106349975324479215795277384839936929757896155643118032610843298655225875571310552543014690878354869257n, 2973677408986561043442465346520108879172042883009249989176415018091420807192182638567116318576472649347015917690530n], + [4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939437n, 0n], + [877076961050607968509681729531255177986764537961432449499635504522207616027455086505066378536590128544573588734230n, 3125332594171059424908108096204648978570118281977575435832422631601824034463382777937621250592425535493320683825557n], + ] + ]; + + const F6 = [ + [ + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + [1n, 0n], + ], + [ + [1n, 0n], + [0n, 4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436n], + [793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350n, 0n], + [0n, 1n], + [4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436n, 0n], + [0n, 793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350n], + ], + [ + [1n, 0n], + [4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939437n, 0n], + [4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436n, 0n], + [4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786n, 0n], + [793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350n, 0n], + [793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620351n, 0n], + ] + ]; + + const f = module.addFunction(ftmPrefix + "_frobeniusMap"+n); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + for (let i=0; i<6; i++) { + const X = (i==0) ? c.getLocal("x") : c.i32_add(c.getLocal("x"), c.i32_const(i*f2size)); + const Xc0 = X; + const Xc1 = c.i32_add(c.getLocal("x"), c.i32_const(i*f2size + f1size)); + const R = (i==0) ? c.getLocal("r") : c.i32_add(c.getLocal("r"), c.i32_const(i*f2size)); + const Rc0 = R; + const Rc1 = c.i32_add(c.getLocal("r"), c.i32_const(i*f2size + f1size)); + const coef = mul2(F12[Math.floor(i/3)][n%12] , F6[i%3][n%6]); + const pCoef = module.alloc([ + ...utils$1.bigInt2BytesLE(toMontgomery(coef[0]), n8q), + ...utils$1.bigInt2BytesLE(toMontgomery(coef[1]), n8q), + ]); + if (n%2 == 1) { + f.addCode( + c.call(f1mPrefix + "_copy", Xc0, Rc0), + c.call(f1mPrefix + "_neg", Xc1, Rc1), + c.call(f2mPrefix + "_mul", R, c.i32_const(pCoef), R), + ); + } else { + f.addCode(c.call(f2mPrefix + "_mul", X, c.i32_const(pCoef), R)); + } + } + + function mul2(a, b) { + const ac0 = a[0]; + const ac1 = a[1]; + const bc0 = b[0]; + const bc1 = b[1]; + const res = [ + (ac0 * bc0 - (ac1 * bc1)) % q, + (ac0 * bc1 + (ac1 * bc0)) % q, + ]; + if (isNegative$1(res[0])) res[0] = res[0] + q; + return res; + } + + } + + + function buildCyclotomicSquare() { + const f = module.addFunction(prefix+ "__cyclotomicSquare"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x4 = c.i32_add(c.getLocal("x"), c.i32_const(f2size)); + const x3 = c.i32_add(c.getLocal("x"), c.i32_const(2*f2size)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(3*f2size)); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(4*f2size)); + const x5 = c.i32_add(c.getLocal("x"), c.i32_const(5*f2size)); + + const r0 = c.getLocal("r"); + const r4 = c.i32_add(c.getLocal("r"), c.i32_const(f2size)); + const r3 = c.i32_add(c.getLocal("r"), c.i32_const(2*f2size)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(3*f2size)); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(4*f2size)); + const r5 = c.i32_add(c.getLocal("r"), c.i32_const(5*f2size)); + + const t0 = c.i32_const(module.alloc(f2size)); + const t1 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const t3 = c.i32_const(module.alloc(f2size)); + const t4 = c.i32_const(module.alloc(f2size)); + const t5 = c.i32_const(module.alloc(f2size)); + const tmp = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + + f.addCode( + // // t0 + t1*y = (z0 + z1*y)^2 = a^2 + // tmp = z0 * z1; + // t0 = (z0 + z1) * (z0 + my_Fp6::non_residue * z1) - tmp - my_Fp6::non_residue * tmp; + // t1 = tmp + tmp; + c.call(f2mPrefix + "_mul", x0, x1, tmp), + c.call(f2mPrefix + "_mulNR", x1, t0), + c.call(f2mPrefix + "_add", x0, t0, t0), + c.call(f2mPrefix + "_add", x0, x1, AUX), + c.call(f2mPrefix + "_mul", AUX, t0, t0), + c.call(f2mPrefix + "_mulNR", tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t0, AUX, t0), + c.call(f2mPrefix + "_add", tmp, tmp, t1), + + // // t2 + t3*y = (z2 + z3*y)^2 = b^2 + // tmp = z2 * z3; + // t2 = (z2 + z3) * (z2 + my_Fp6::non_residue * z3) - tmp - my_Fp6::non_residue * tmp; + // t3 = tmp + tmp; + c.call(f2mPrefix + "_mul", x2, x3, tmp), + c.call(f2mPrefix + "_mulNR", x3, t2), + c.call(f2mPrefix + "_add", x2, t2, t2), + c.call(f2mPrefix + "_add", x2, x3, AUX), + c.call(f2mPrefix + "_mul", AUX, t2, t2), + c.call(f2mPrefix + "_mulNR", tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t2, AUX, t2), + c.call(f2mPrefix + "_add", tmp, tmp, t3), + + // // t4 + t5*y = (z4 + z5*y)^2 = c^2 + // tmp = z4 * z5; + // t4 = (z4 + z5) * (z4 + my_Fp6::non_residue * z5) - tmp - my_Fp6::non_residue * tmp; + // t5 = tmp + tmp; + c.call(f2mPrefix + "_mul", x4, x5, tmp), + c.call(f2mPrefix + "_mulNR", x5, t4), + c.call(f2mPrefix + "_add", x4, t4, t4), + c.call(f2mPrefix + "_add", x4, x5, AUX), + c.call(f2mPrefix + "_mul", AUX, t4, t4), + c.call(f2mPrefix + "_mulNR", tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t4, AUX, t4), + c.call(f2mPrefix + "_add", tmp, tmp, t5), + + // For A + // z0 = 3 * t0 - 2 * z0 + c.call(f2mPrefix + "_sub", t0, x0, r0), + c.call(f2mPrefix + "_add", r0, r0, r0), + c.call(f2mPrefix + "_add", t0, r0, r0), + // z1 = 3 * t1 + 2 * z1 + c.call(f2mPrefix + "_add", t1, x1, r1), + c.call(f2mPrefix + "_add", r1, r1, r1), + c.call(f2mPrefix + "_add", t1, r1, r1), + + // For B + // z2 = 3 * (xi * t5) + 2 * z2 + c.call(f2mPrefix + "_mul", t5, c.i32_const(pBls12381Twist), AUX), + c.call(f2mPrefix + "_add", AUX, x2, r2), + c.call(f2mPrefix + "_add", r2, r2, r2), + c.call(f2mPrefix + "_add", AUX, r2, r2), + // z3 = 3 * t4 - 2 * z3 + c.call(f2mPrefix + "_sub", t4, x3, r3), + c.call(f2mPrefix + "_add", r3, r3, r3), + c.call(f2mPrefix + "_add", t4, r3, r3), + + // For C + // z4 = 3 * t2 - 2 * z4 + c.call(f2mPrefix + "_sub", t2, x4, r4), + c.call(f2mPrefix + "_add", r4, r4, r4), + c.call(f2mPrefix + "_add", t2, r4, r4), + // z5 = 3 * t3 + 2 * z5 + c.call(f2mPrefix + "_add", t3, x5, r5), + c.call(f2mPrefix + "_add", r5, r5, r5), + c.call(f2mPrefix + "_add", t3, r5, r5), + + ); + } + + + function buildCyclotomicExp(exponent, isExpNegative, fnName) { + const exponentNafBytes = naf(exponent).map( (b) => (b==-1 ? 0xFF: b) ); + const pExponentNafBytes = module.alloc(exponentNafBytes); + // const pExponent = module.alloc(utils.bigInt2BytesLE(exponent, n8)); + + const f = module.addFunction(prefix+ "__cyclotomicExp_"+fnName); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + f.addLocal("bit", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const x = c.getLocal("x"); + + const res = c.getLocal("r"); + + const inverse = c.i32_const(module.alloc(ftsize)); + + + f.addCode( + c.call(ftmPrefix + "_conjugate", x, inverse), + c.call(ftmPrefix + "_one", res), + + c.if( + c.teeLocal("bit", c.i32_load8_s(c.i32_const(exponentNafBytes.length-1), pExponentNafBytes)), + c.if( + c.i32_eq( + c.getLocal("bit"), + c.i32_const(1) + ), + c.call(ftmPrefix + "_mul", res, x, res), + c.call(ftmPrefix + "_mul", res, inverse, res), + ) + ), + + c.setLocal("i", c.i32_const(exponentNafBytes.length-2)), + c.block(c.loop( + c.call(prefix + "__cyclotomicSquare", res, res), + c.if( + c.teeLocal("bit", c.i32_load8_s(c.getLocal("i"), pExponentNafBytes)), + c.if( + c.i32_eq( + c.getLocal("bit"), + c.i32_const(1) + ), + c.call(ftmPrefix + "_mul", res, x, res), + c.call(ftmPrefix + "_mul", res, inverse, res), + ) + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + + if (isExpNegative) { + f.addCode( + c.call(ftmPrefix + "_conjugate", res, res), + ); + } + + } + + function buildFinalExponentiation() { + buildCyclotomicSquare(); + buildCyclotomicExp(finalExpZ, finalExpIsNegative, "w0"); + + const f = module.addFunction(prefix+ "_finalExponentiation"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const elt = c.getLocal("x"); + const res = c.getLocal("r"); + const t0 = c.i32_const(module.alloc(ftsize)); + const t1 = c.i32_const(module.alloc(ftsize)); + const t2 = c.i32_const(module.alloc(ftsize)); + const t3 = c.i32_const(module.alloc(ftsize)); + const t4 = c.i32_const(module.alloc(ftsize)); + const t5 = c.i32_const(module.alloc(ftsize)); + const t6 = c.i32_const(module.alloc(ftsize)); + + f.addCode( + + // let mut t0 = f.frobenius_map(6) + c.call(ftmPrefix + "_frobeniusMap6", elt, t0), + + // let t1 = f.invert() + c.call(ftmPrefix + "_inverse", elt, t1), + + // let mut t2 = t0 * t1; + c.call(ftmPrefix + "_mul", t0, t1, t2), + + // t1 = t2.clone(); + c.call(ftmPrefix + "_copy", t2, t1), + + // t2 = t2.frobenius_map().frobenius_map(); + c.call(ftmPrefix + "_frobeniusMap2", t2, t2), + + // t2 *= t1; + c.call(ftmPrefix + "_mul", t2, t1, t2), + + + // t1 = cyclotomic_square(t2).conjugate(); + c.call(prefix + "__cyclotomicSquare", t2, t1), + c.call(ftmPrefix + "_conjugate", t1, t1), + + // let mut t3 = cycolotomic_exp(t2); + c.call(prefix + "__cyclotomicExp_w0", t2, t3), + + // let mut t4 = cyclotomic_square(t3); + c.call(prefix + "__cyclotomicSquare", t3, t4), + + // let mut t5 = t1 * t3; + c.call(ftmPrefix + "_mul", t1, t3, t5), + + // t1 = cycolotomic_exp(t5); + c.call(prefix + "__cyclotomicExp_w0", t5, t1), + + // t0 = cycolotomic_exp(t1); + c.call(prefix + "__cyclotomicExp_w0", t1, t0), + + // let mut t6 = cycolotomic_exp(t0); + c.call(prefix + "__cyclotomicExp_w0", t0, t6), + + // t6 *= t4; + c.call(ftmPrefix + "_mul", t6, t4, t6), + + // t4 = cycolotomic_exp(t6); + c.call(prefix + "__cyclotomicExp_w0", t6, t4), + + // t5 = t5.conjugate(); + c.call(ftmPrefix + "_conjugate", t5, t5), + + // t4 *= t5 * t2; + c.call(ftmPrefix + "_mul", t4, t5, t4), + c.call(ftmPrefix + "_mul", t4, t2, t4), + + // t5 = t2.conjugate(); + c.call(ftmPrefix + "_conjugate", t2, t5), + + // t1 *= t2; + c.call(ftmPrefix + "_mul", t1, t2, t1), + + // t1 = t1.frobenius_map().frobenius_map().frobenius_map(); + c.call(ftmPrefix + "_frobeniusMap3", t1, t1), + + // t6 *= t5; + c.call(ftmPrefix + "_mul", t6, t5, t6), + + // t6 = t6.frobenius_map(); + c.call(ftmPrefix + "_frobeniusMap1", t6, t6), + + // t3 *= t0; + c.call(ftmPrefix + "_mul", t3, t0, t3), + + // t3 = t3.frobenius_map().frobenius_map(); + c.call(ftmPrefix + "_frobeniusMap2", t3, t3), + + // t3 *= t1; + c.call(ftmPrefix + "_mul", t3, t1, t3), + + // t3 *= t6; + c.call(ftmPrefix + "_mul", t3, t6, t3), + + // f = t3 * t4; + c.call(ftmPrefix + "_mul", t3, t4, res), + + ); + } + + + function buildFinalExponentiationOld() { + const f = module.addFunction(prefix+ "_finalExponentiationOld"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const exponent = 322277361516934140462891564586510139908379969514828494218366688025288661041104682794998680497580008899973249814104447692778988208376779573819485263026159588510513834876303014016798809919343532899164848730280942609956670917565618115867287399623286813270357901731510188149934363360381614501334086825442271920079363289954510565375378443704372994881406797882676971082200626541916413184642520269678897559532260949334760604962086348898118982248842634379637598665468817769075878555493752214492790122785850202957575200176084204422751485957336465472324810982833638490904279282696134323072515220044451592646885410572234451732790590013479358343841220074174848221722017083597872017638514103174122784843925578370430843522959600095676285723737049438346544753168912974976791528535276317256904336520179281145394686565050419250614107803233314658825463117900250701199181529205942363159325765991819433914303908860460720581408201373164047773794825411011922305820065611121544561808414055302212057471395719432072209245600258134364584636810093520285711072578721435517884103526483832733289802426157301542744476740008494780363354305116978805620671467071400711358839553375340724899735460480144599782014906586543813292157922220645089192130209334926661588737007768565838519456601560804957985667880395221049249803753582637708560n; + + const pExponent = module.alloc(utils$1.bigInt2BytesLE( exponent, 544 )); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(ftmPrefix + "_exp", c.getLocal("x"), c.i32_const(pExponent), c.i32_const(544), c.getLocal("r")), + ); + } + + + const pPreP = module.alloc(prePSize); + const pPreQ = module.alloc(preQSize); + + function buildPairingEquation(nPairings) { + + const f = module.addFunction(prefix+ "_pairingEq"+nPairings); + for (let i=0; i. */ -const bigInt = __webpack_require__(2096); +// module.exports.bn128_wasm = require("./build/bn128_wasm.js"); +// module.exports.bls12381_wasm = require("./build/bls12381_wasm.js"); +// module.exports.mnt6753_wasm = require("./build/mnt6753_wasm.js"); -exports.bigInt2BytesLE = function bigInt2BytesLE(_a, len) { - const b = Array(len); - let v = bigInt(_a); - for (let i=0; i { - -"use strict"; - - -var forEach = __webpack_require__(2682); -var availableTypedArrays = __webpack_require__(9209); -var callBind = __webpack_require__(487); -var callBound = __webpack_require__(8075); -var gOPD = __webpack_require__(5795); - -/** @type {(O: object) => string} */ -var $toString = callBound('Object.prototype.toString'); -var hasToStringTag = __webpack_require__(9092)(); - -var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; -var typedArrays = availableTypedArrays(); - -var $slice = callBound('String.prototype.slice'); -var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); - -/** @type {(array: readonly T[], value: unknown) => number} */ -var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) { - for (var i = 0; i < array.length; i += 1) { - if (array[i] === value) { - return i; - } - } - return -1; -}; - -/** @typedef {(receiver: import('.').TypedArray) => string | typeof Uint8Array.prototype.slice.call | typeof Uint8Array.prototype.set.call} Getter */ -/** @type {{ [k in `\$${import('.').TypedArrayName}`]?: Getter } & { __proto__: null }} */ -var cache = { __proto__: null }; -if (hasToStringTag && gOPD && getPrototypeOf) { - forEach(typedArrays, function (typedArray) { - var arr = new g[typedArray](); - if (Symbol.toStringTag in arr) { - var proto = getPrototypeOf(arr); - // @ts-expect-error TS won't narrow inside a closure - var descriptor = gOPD(proto, Symbol.toStringTag); - if (!descriptor) { - var superProto = getPrototypeOf(proto); - // @ts-expect-error TS won't narrow inside a closure - descriptor = gOPD(superProto, Symbol.toStringTag); - } - // @ts-expect-error TODO: fix - cache['$' + typedArray] = callBind(descriptor.get); - } - }); -} else { - forEach(typedArrays, function (typedArray) { - var arr = new g[typedArray](); - var fn = arr.slice || arr.set; - if (fn) { - // @ts-expect-error TODO: fix - cache['$' + typedArray] = callBind(fn); - } - }); -} - -/** @type {(value: object) => false | import('.').TypedArrayName} */ -var tryTypedArrays = function tryAllTypedArrays(value) { - /** @type {ReturnType} */ var found = false; - forEach( - // eslint-disable-next-line no-extra-parens - /** @type {Record<`\$${TypedArrayName}`, Getter>} */ /** @type {any} */ (cache), - /** @type {(getter: Getter, name: `\$${import('.').TypedArrayName}`) => void} */ - function (getter, typedArray) { - if (!found) { - try { - // @ts-expect-error TODO: fix - if ('$' + getter(value) === typedArray) { - found = $slice(typedArray, 1); - } - } catch (e) { /**/ } - } - } - ); - return found; -}; - -/** @type {(value: object) => false | import('.').TypedArrayName} */ -var trySlices = function tryAllSlices(value) { - /** @type {ReturnType} */ var found = false; - forEach( - // eslint-disable-next-line no-extra-parens - /** @type {Record<`\$${TypedArrayName}`, Getter>} */ /** @type {any} */ (cache), - /** @type {(getter: typeof cache, name: `\$${import('.').TypedArrayName}`) => void} */ function (getter, name) { - if (!found) { - try { - // @ts-expect-error TODO: fix - getter(value); - found = $slice(name, 1); - } catch (e) { /**/ } - } - } - ); - return found; -}; - -/** @type {import('.')} */ -module.exports = function whichTypedArray(value) { - if (!value || typeof value !== 'object') { return false; } - if (!hasToStringTag) { - /** @type {string} */ - var tag = $slice($toString(value), 8, -1); - if ($indexOf(typedArrays, tag) > -1) { - return tag; - } - if (tag !== 'Object') { - return false; - } - // node < 0.6 hits here on real Typed Arrays - return trySlices(value); - } - if (!gOPD) { return null; } // unknown engine - return tryTypedArrays(value); -}; - - -/***/ }), - -/***/ 8982: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 7790: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 3776: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 1638: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 2668: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 7965: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 6089: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 9368: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 4688: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 1069: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 5340: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 9838: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 7882: -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ 9209: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -var possibleNames = __webpack_require__(6578); - -var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; - -/** @type {import('.')} */ -module.exports = function availableTypedArrays() { - var /** @type {ReturnType} */ out = []; - for (var i = 0; i < possibleNames.length; i++) { - if (typeof g[possibleNames[i]] === 'function') { - // @ts-expect-error - out[out.length] = possibleNames[i]; - } - } - return out; -}; - - -/***/ }), - -/***/ 3219: -/***/ ((module) => { - -"use strict"; -module.exports = /*#__PURE__*/JSON.parse('{"aes-128-ecb":{"cipher":"AES","key":128,"iv":0,"mode":"ECB","type":"block"},"aes-192-ecb":{"cipher":"AES","key":192,"iv":0,"mode":"ECB","type":"block"},"aes-256-ecb":{"cipher":"AES","key":256,"iv":0,"mode":"ECB","type":"block"},"aes-128-cbc":{"cipher":"AES","key":128,"iv":16,"mode":"CBC","type":"block"},"aes-192-cbc":{"cipher":"AES","key":192,"iv":16,"mode":"CBC","type":"block"},"aes-256-cbc":{"cipher":"AES","key":256,"iv":16,"mode":"CBC","type":"block"},"aes128":{"cipher":"AES","key":128,"iv":16,"mode":"CBC","type":"block"},"aes192":{"cipher":"AES","key":192,"iv":16,"mode":"CBC","type":"block"},"aes256":{"cipher":"AES","key":256,"iv":16,"mode":"CBC","type":"block"},"aes-128-cfb":{"cipher":"AES","key":128,"iv":16,"mode":"CFB","type":"stream"},"aes-192-cfb":{"cipher":"AES","key":192,"iv":16,"mode":"CFB","type":"stream"},"aes-256-cfb":{"cipher":"AES","key":256,"iv":16,"mode":"CFB","type":"stream"},"aes-128-cfb8":{"cipher":"AES","key":128,"iv":16,"mode":"CFB8","type":"stream"},"aes-192-cfb8":{"cipher":"AES","key":192,"iv":16,"mode":"CFB8","type":"stream"},"aes-256-cfb8":{"cipher":"AES","key":256,"iv":16,"mode":"CFB8","type":"stream"},"aes-128-cfb1":{"cipher":"AES","key":128,"iv":16,"mode":"CFB1","type":"stream"},"aes-192-cfb1":{"cipher":"AES","key":192,"iv":16,"mode":"CFB1","type":"stream"},"aes-256-cfb1":{"cipher":"AES","key":256,"iv":16,"mode":"CFB1","type":"stream"},"aes-128-ofb":{"cipher":"AES","key":128,"iv":16,"mode":"OFB","type":"stream"},"aes-192-ofb":{"cipher":"AES","key":192,"iv":16,"mode":"OFB","type":"stream"},"aes-256-ofb":{"cipher":"AES","key":256,"iv":16,"mode":"OFB","type":"stream"},"aes-128-ctr":{"cipher":"AES","key":128,"iv":16,"mode":"CTR","type":"stream"},"aes-192-ctr":{"cipher":"AES","key":192,"iv":16,"mode":"CTR","type":"stream"},"aes-256-ctr":{"cipher":"AES","key":256,"iv":16,"mode":"CTR","type":"stream"},"aes-128-gcm":{"cipher":"AES","key":128,"iv":12,"mode":"GCM","type":"auth"},"aes-192-gcm":{"cipher":"AES","key":192,"iv":12,"mode":"GCM","type":"auth"},"aes-256-gcm":{"cipher":"AES","key":256,"iv":12,"mode":"GCM","type":"auth"}}'); - -/***/ }), - -/***/ 2951: -/***/ ((module) => { - -"use strict"; -module.exports = /*#__PURE__*/JSON.parse('{"sha224WithRSAEncryption":{"sign":"rsa","hash":"sha224","id":"302d300d06096086480165030402040500041c"},"RSA-SHA224":{"sign":"ecdsa/rsa","hash":"sha224","id":"302d300d06096086480165030402040500041c"},"sha256WithRSAEncryption":{"sign":"rsa","hash":"sha256","id":"3031300d060960864801650304020105000420"},"RSA-SHA256":{"sign":"ecdsa/rsa","hash":"sha256","id":"3031300d060960864801650304020105000420"},"sha384WithRSAEncryption":{"sign":"rsa","hash":"sha384","id":"3041300d060960864801650304020205000430"},"RSA-SHA384":{"sign":"ecdsa/rsa","hash":"sha384","id":"3041300d060960864801650304020205000430"},"sha512WithRSAEncryption":{"sign":"rsa","hash":"sha512","id":"3051300d060960864801650304020305000440"},"RSA-SHA512":{"sign":"ecdsa/rsa","hash":"sha512","id":"3051300d060960864801650304020305000440"},"RSA-SHA1":{"sign":"rsa","hash":"sha1","id":"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{"sign":"ecdsa","hash":"sha1","id":""},"sha256":{"sign":"ecdsa","hash":"sha256","id":""},"sha224":{"sign":"ecdsa","hash":"sha224","id":""},"sha384":{"sign":"ecdsa","hash":"sha384","id":""},"sha512":{"sign":"ecdsa","hash":"sha512","id":""},"DSA-SHA":{"sign":"dsa","hash":"sha1","id":""},"DSA-SHA1":{"sign":"dsa","hash":"sha1","id":""},"DSA":{"sign":"dsa","hash":"sha1","id":""},"DSA-WITH-SHA224":{"sign":"dsa","hash":"sha224","id":""},"DSA-SHA224":{"sign":"dsa","hash":"sha224","id":""},"DSA-WITH-SHA256":{"sign":"dsa","hash":"sha256","id":""},"DSA-SHA256":{"sign":"dsa","hash":"sha256","id":""},"DSA-WITH-SHA384":{"sign":"dsa","hash":"sha384","id":""},"DSA-SHA384":{"sign":"dsa","hash":"sha384","id":""},"DSA-WITH-SHA512":{"sign":"dsa","hash":"sha512","id":""},"DSA-SHA512":{"sign":"dsa","hash":"sha512","id":""},"DSA-RIPEMD160":{"sign":"dsa","hash":"rmd160","id":""},"ripemd160WithRSA":{"sign":"rsa","hash":"rmd160","id":"3021300906052b2403020105000414"},"RSA-RIPEMD160":{"sign":"rsa","hash":"rmd160","id":"3021300906052b2403020105000414"},"md5WithRSAEncryption":{"sign":"rsa","hash":"md5","id":"3020300c06082a864886f70d020505000410"},"RSA-MD5":{"sign":"rsa","hash":"md5","id":"3020300c06082a864886f70d020505000410"}}'); - -/***/ }), - -/***/ 4589: -/***/ ((module) => { - -"use strict"; -module.exports = /*#__PURE__*/JSON.parse('{"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}'); - -/***/ }), - -/***/ 3241: -/***/ ((module) => { - -"use strict"; -module.exports = /*#__PURE__*/JSON.parse('{"modp1":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},"modp2":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},"modp5":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},"modp14":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},"modp15":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},"modp16":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},"modp17":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},"modp18":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}}'); - -/***/ }), - -/***/ 1636: -/***/ ((module) => { - -"use strict"; -module.exports = {"rE":"6.5.5"}; - -/***/ }), - -/***/ 5579: -/***/ ((module) => { - -"use strict"; -module.exports = /*#__PURE__*/JSON.parse('{"2.16.840.1.101.3.4.1.1":"aes-128-ecb","2.16.840.1.101.3.4.1.2":"aes-128-cbc","2.16.840.1.101.3.4.1.3":"aes-128-ofb","2.16.840.1.101.3.4.1.4":"aes-128-cfb","2.16.840.1.101.3.4.1.21":"aes-192-ecb","2.16.840.1.101.3.4.1.22":"aes-192-cbc","2.16.840.1.101.3.4.1.23":"aes-192-ofb","2.16.840.1.101.3.4.1.24":"aes-192-cfb","2.16.840.1.101.3.4.1.41":"aes-256-ecb","2.16.840.1.101.3.4.1.42":"aes-256-cbc","2.16.840.1.101.3.4.1.43":"aes-256-ofb","2.16.840.1.101.3.4.1.44":"aes-256-cfb"}'); - -/***/ }) - -/******/ }); -/************************************************************************/ -/******/ // The module cache -/******/ var __webpack_module_cache__ = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ // Check if module is in cache -/******/ var cachedModule = __webpack_module_cache__[moduleId]; -/******/ if (cachedModule !== undefined) { -/******/ return cachedModule.exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = __webpack_module_cache__[moduleId] = { -/******/ id: moduleId, -/******/ loaded: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.loaded = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/************************************************************************/ -/******/ /* webpack/runtime/amd options */ -/******/ (() => { -/******/ __webpack_require__.amdO = {}; -/******/ })(); -/******/ -/******/ /* webpack/runtime/compat get default export */ -/******/ (() => { -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = (module) => { -/******/ var getter = module && module.__esModule ? -/******/ () => (module['default']) : -/******/ () => (module); -/******/ __webpack_require__.d(getter, { a: getter }); -/******/ return getter; -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/define property getters */ -/******/ (() => { -/******/ // define getter functions for harmony exports -/******/ __webpack_require__.d = (exports, definition) => { -/******/ for(var key in definition) { -/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { -/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); -/******/ } -/******/ } -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/global */ -/******/ (() => { -/******/ __webpack_require__.g = (function() { -/******/ if (typeof globalThis === 'object') return globalThis; -/******/ try { -/******/ return this || new Function('return this')(); -/******/ } catch (e) { -/******/ if (typeof window === 'object') return window; -/******/ } -/******/ })(); -/******/ })(); -/******/ -/******/ /* webpack/runtime/hasOwnProperty shorthand */ -/******/ (() => { -/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -/******/ })(); -/******/ -/******/ /* webpack/runtime/make namespace object */ -/******/ (() => { -/******/ // define __esModule on exports -/******/ __webpack_require__.r = (exports) => { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/node module decorator */ -/******/ (() => { -/******/ __webpack_require__.nmd = (module) => { -/******/ module.paths = []; -/******/ if (!module.children) module.children = []; -/******/ return module; -/******/ }; -/******/ })(); -/******/ -/************************************************************************/ -var __webpack_exports__ = {}; -// This entry need to be wrapped in an IIFE because it need to be in strict mode. -(() => { -"use strict"; -// ESM COMPAT FLAG -__webpack_require__.r(__webpack_exports__); - -// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/scalar_native.js -var scalar_native_namespaceObject = {}; -__webpack_require__.r(scalar_native_namespaceObject); -__webpack_require__.d(scalar_native_namespaceObject, { - abs: () => (abs), - add: () => (add), - band: () => (band), - bitLength: () => (bitLength), - bits: () => (bits), - bor: () => (bor), - bxor: () => (bxor), - div: () => (div), - e: () => (e), - eq: () => (eq), - exp: () => (exp), - fromArray: () => (fromArray), - fromString: () => (fromString), - geq: () => (geq), - gt: () => (gt), - isNegative: () => (isNegative), - isOdd: () => (isOdd), - isZero: () => (isZero), - land: () => (land), - leq: () => (leq), - lnot: () => (lnot), - lor: () => (lor), - lt: () => (lt), - mod: () => (mod), - mul: () => (mul), - naf: () => (naf), - neg: () => (neg), - neq: () => (neq), - pow: () => (pow), - shiftLeft: () => (shiftLeft), - shiftRight: () => (shiftRight), - shl: () => (shl), - shr: () => (shr), - square: () => (square), - sub: () => (sub), - toArray: () => (toArray), - toNumber: () => (toNumber) -}); - -// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/scalar_bigint.js -var scalar_bigint_namespaceObject = {}; -__webpack_require__.r(scalar_bigint_namespaceObject); -__webpack_require__.d(scalar_bigint_namespaceObject, { - abs: () => (scalar_bigint_abs), - add: () => (scalar_bigint_add), - band: () => (scalar_bigint_band), - bitLength: () => (scalar_bigint_bitLength), - bits: () => (scalar_bigint_bits), - bor: () => (scalar_bigint_bor), - bxor: () => (scalar_bigint_bxor), - div: () => (scalar_bigint_div), - e: () => (scalar_bigint_e), - eq: () => (scalar_bigint_eq), - exp: () => (scalar_bigint_exp), - fromArray: () => (scalar_bigint_fromArray), - fromString: () => (scalar_bigint_fromString), - geq: () => (scalar_bigint_geq), - gt: () => (scalar_bigint_gt), - isNegative: () => (scalar_bigint_isNegative), - isOdd: () => (scalar_bigint_isOdd), - isZero: () => (scalar_bigint_isZero), - land: () => (scalar_bigint_land), - leq: () => (scalar_bigint_leq), - lnot: () => (scalar_bigint_lnot), - lor: () => (scalar_bigint_lor), - lt: () => (scalar_bigint_lt), - mod: () => (scalar_bigint_mod), - mul: () => (scalar_bigint_mul), - naf: () => (scalar_bigint_naf), - neg: () => (scalar_bigint_neg), - neq: () => (scalar_bigint_neq), - pow: () => (scalar_bigint_pow), - shiftLeft: () => (scalar_bigint_shiftLeft), - shiftRight: () => (scalar_bigint_shiftRight), - shl: () => (scalar_bigint_shl), - shr: () => (scalar_bigint_shr), - square: () => (scalar_bigint_square), - sub: () => (scalar_bigint_sub), - toArray: () => (scalar_bigint_toArray), - toNumber: () => (scalar_bigint_toNumber) -}); - -// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/scalar.js -var scalar_namespaceObject = {}; -__webpack_require__.r(scalar_namespaceObject); -__webpack_require__.d(scalar_namespaceObject, { - abs: () => (scalar_abs), - add: () => (scalar_add), - band: () => (scalar_band), - bitLength: () => (scalar_bitLength), - bits: () => (scalar_bits), - bor: () => (scalar_bor), - bxor: () => (scalar_bxor), - div: () => (scalar_div), - e: () => (scalar_e), - eq: () => (scalar_eq), - exp: () => (scalar_exp), - fromArray: () => (scalar_fromArray), - fromRprBE: () => (fromRprBE), - fromRprLE: () => (fromRprLE), - fromString: () => (scalar_fromString), - geq: () => (scalar_geq), - gt: () => (scalar_gt), - isNegative: () => (scalar_isNegative), - isOdd: () => (scalar_isOdd), - isZero: () => (scalar_isZero), - land: () => (scalar_land), - leq: () => (scalar_leq), - lnot: () => (scalar_lnot), - lor: () => (scalar_lor), - lt: () => (scalar_lt), - mod: () => (scalar_mod), - mul: () => (scalar_mul), - naf: () => (scalar_naf), - neg: () => (scalar_neg), - neq: () => (scalar_neq), - one: () => (one), - pow: () => (scalar_pow), - shiftLeft: () => (scalar_shiftLeft), - shiftRight: () => (scalar_shiftRight), - shl: () => (scalar_shl), - shr: () => (scalar_shr), - square: () => (scalar_square), - sub: () => (scalar_sub), - toArray: () => (scalar_toArray), - toLEBuff: () => (toLEBuff), - toNumber: () => (scalar_toNumber), - toRprBE: () => (toRprBE), - toRprLE: () => (toRprLE), - toString: () => (scalar_toString), - zero: () => (zero) -}); - -// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/utils_native.js -var utils_native_namespaceObject = {}; -__webpack_require__.r(utils_native_namespaceObject); -__webpack_require__.d(utils_native_namespaceObject, { - beBuff2int: () => (beBuff2int), - beInt2Buff: () => (beInt2Buff), - leBuff2int: () => (leBuff2int), - leInt2Buff: () => (leInt2Buff), - stringifyBigInts: () => (stringifyBigInts), - stringifyFElements: () => (stringifyFElements), - unstringifyBigInts: () => (unstringifyBigInts), - unstringifyFElements: () => (unstringifyFElements) -}); - -// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/utils_bigint.js -var utils_bigint_namespaceObject = {}; -__webpack_require__.r(utils_bigint_namespaceObject); -__webpack_require__.d(utils_bigint_namespaceObject, { - beBuff2int: () => (utils_bigint_beBuff2int), - beInt2Buff: () => (utils_bigint_beInt2Buff), - leBuff2int: () => (utils_bigint_leBuff2int), - leInt2Buff: () => (utils_bigint_leInt2Buff), - stringifyBigInts: () => (utils_bigint_stringifyBigInts), - unstringifyBigInts: () => (utils_bigint_unstringifyBigInts) -}); - -// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/utils.js -var utils_namespaceObject = {}; -__webpack_require__.r(utils_namespaceObject); -__webpack_require__.d(utils_namespaceObject, { - array2buffer: () => (array2buffer), - beBuff2int: () => (utils_beBuff2int), - beInt2Buff: () => (utils_beInt2Buff), - bitReverse: () => (bitReverse), - buffReverseBits: () => (buffReverseBits), - buffer2array: () => (buffer2array), - leBuff2int: () => (utils_leBuff2int), - leInt2Buff: () => (utils_leInt2Buff), - log2: () => (utils_log2), - stringifyBigInts: () => (utils_stringifyBigInts), - stringifyFElements: () => (utils_stringifyFElements), - unstringifyBigInts: () => (utils_unstringifyBigInts), - unstringifyFElements: () => (utils_unstringifyFElements) -}); - -// EXTERNAL MODULE: worker_threads (ignored) -var worker_threads_ignored_ = __webpack_require__(7882); -var worker_threads_ignored_default = /*#__PURE__*/__webpack_require__.n(worker_threads_ignored_); -// EXTERNAL MODULE: ./node_modules/@tornado/fixed-merkle-tree/lib/index.js -var lib = __webpack_require__(1217); -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/scalar_native.js /* global BigInt */ -const hexLen = [ 0, 1, 2, 2, 3, 3, 3, 3, 4 ,4 ,4 ,4 ,4 ,4 ,4 ,4]; - -function fromString(s, radix) { - if ((!radix)||(radix==10)) { - return BigInt(s); - } else if (radix==16) { - if (s.slice(0,2) == "0x") { - return BigInt(s); - } else { - return BigInt("0x"+s); - } - } -} - -const e = fromString; - -function fromArray(a, radix) { - let acc =BigInt(0); - radix = BigInt(radix); - for (let i=0; i> BigInt(n); -} - -const shl = shiftLeft; -const shr = shiftRight; - -function isOdd(a) { - return (BigInt(a) & BigInt(1)) == BigInt(1); -} - - -function naf(n) { - let E = BigInt(n); - const res = []; - while (E) { - if (E & BigInt(1)) { - const z = 2 - Number(E % BigInt(4)); - res.push( z ); - E = E - BigInt(z); - } else { - res.push( 0 ); - } - E = E >> BigInt(1); - } - return res; -} - - -function bits(n) { - let E = BigInt(n); - const res = []; - while (E) { - if (E & BigInt(1)) { - res.push(1); - } else { - res.push( 0 ); - } - E = E >> BigInt(1); - } - return res; -} - -function toNumber(s) { - if (s>BigInt(Number.MAX_SAFE_INTEGER )) { - throw new Error("Number too big"); - } - return Number(s); -} - -function toArray(s, radix) { - const res = []; - let rem = BigInt(s); - radix = BigInt(radix); - while (rem) { - res.unshift( Number(rem % radix)); - rem = rem / radix; - } - return res; -} - - -function add(a, b) { - return BigInt(a) + BigInt(b); -} - -function sub(a, b) { - return BigInt(a) - BigInt(b); -} - -function neg(a) { - return -BigInt(a); -} - -function mul(a, b) { - return BigInt(a) * BigInt(b); -} - -function square(a) { - return BigInt(a) * BigInt(a); -} - -function pow(a, b) { - return BigInt(a) ** BigInt(b); -} - -function exp(a, b) { - return BigInt(a) ** BigInt(b); -} - -function abs(a) { - return BigInt(a) >= 0 ? BigInt(a) : -BigInt(a); -} - -function div(a, b) { - return BigInt(a) / BigInt(b); -} - -function mod(a, b) { - return BigInt(a) % BigInt(b); -} - -function eq(a, b) { - return BigInt(a) == BigInt(b); -} - -function neq(a, b) { - return BigInt(a) != BigInt(b); -} - -function lt(a, b) { - return BigInt(a) < BigInt(b); -} - -function gt(a, b) { - return BigInt(a) > BigInt(b); -} - -function leq(a, b) { - return BigInt(a) <= BigInt(b); -} - -function geq(a, b) { - return BigInt(a) >= BigInt(b); -} - -function band(a, b) { - return BigInt(a) & BigInt(b); -} - -function bor(a, b) { - return BigInt(a) | BigInt(b); -} - -function bxor(a, b) { - return BigInt(a) ^ BigInt(b); -} - -function land(a, b) { - return BigInt(a) && BigInt(b); -} - -function lor(a, b) { - return BigInt(a) || BigInt(b); -} - -function lnot(a) { - return !BigInt(a); -} - - -// EXTERNAL MODULE: ./node_modules/big-integer/BigInteger.js -var BigInteger = __webpack_require__(2096); -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/scalar_bigint.js - - -function scalar_bigint_fromString(s, radix) { - if (typeof s == "string") { - if (s.slice(0,2) == "0x") { - return BigInteger(s.slice(2), 16); - } else { - return BigInteger(s,radix); - } - } else { - return BigInteger(s, radix); - } -} - -const scalar_bigint_e = scalar_bigint_fromString; - -function scalar_bigint_fromArray(a, radix) { - return BigInteger.fromArray(a, radix); -} - -function scalar_bigint_bitLength(a) { - return BigInteger(a).bitLength(); -} - -function scalar_bigint_isNegative(a) { - return BigInteger(a).isNegative(); -} - -function scalar_bigint_isZero(a) { - return BigInteger(a).isZero(); -} - -function scalar_bigint_shiftLeft(a, n) { - return BigInteger(a).shiftLeft(n); -} - -function scalar_bigint_shiftRight(a, n) { - return BigInteger(a).shiftRight(n); -} - -const scalar_bigint_shl = scalar_bigint_shiftLeft; -const scalar_bigint_shr = scalar_bigint_shiftRight; - -function scalar_bigint_isOdd(a) { - return BigInteger(a).isOdd(); -} - - -function scalar_bigint_naf(n) { - let E = BigInteger(n); - const res = []; - while (E.gt(BigInteger.zero)) { - if (E.isOdd()) { - const z = 2 - E.mod(4).toJSNumber(); - res.push( z ); - E = E.minus(z); - } else { - res.push( 0 ); - } - E = E.shiftRight(1); - } - return res; -} - -function scalar_bigint_bits(n) { - let E = BigInteger(n); - const res = []; - while (E.gt(BigInteger.zero)) { - if (E.isOdd()) { - res.push(1); - } else { - res.push( 0 ); - } - E = E.shiftRight(1); - } - return res; -} - -function scalar_bigint_toNumber(s) { - if (!s.lt(BigInteger("9007199254740992", 10))) { - throw new Error("Number too big"); - } - return s.toJSNumber(); -} - -function scalar_bigint_toArray(s, radix) { - return BigInteger(s).toArray(radix); -} - -function scalar_bigint_add(a, b) { - return BigInteger(a).add(BigInteger(b)); -} - -function scalar_bigint_sub(a, b) { - return BigInteger(a).minus(BigInteger(b)); -} - -function scalar_bigint_neg(a) { - return BigInteger.zero.minus(BigInteger(a)); -} - -function scalar_bigint_mul(a, b) { - return BigInteger(a).times(BigInteger(b)); -} - -function scalar_bigint_square(a) { - return BigInteger(a).square(); -} - -function scalar_bigint_pow(a, b) { - return BigInteger(a).pow(BigInteger(b)); -} - -function scalar_bigint_exp(a, b) { - return BigInteger(a).pow(BigInteger(b)); -} - -function scalar_bigint_abs(a) { - return BigInteger(a).abs(); -} - -function scalar_bigint_div(a, b) { - return BigInteger(a).divide(BigInteger(b)); -} - -function scalar_bigint_mod(a, b) { - return BigInteger(a).mod(BigInteger(b)); -} - -function scalar_bigint_eq(a, b) { - return BigInteger(a).eq(BigInteger(b)); -} - -function scalar_bigint_neq(a, b) { - return BigInteger(a).neq(BigInteger(b)); -} - -function scalar_bigint_lt(a, b) { - return BigInteger(a).lt(BigInteger(b)); -} - -function scalar_bigint_gt(a, b) { - return BigInteger(a).gt(BigInteger(b)); -} - -function scalar_bigint_leq(a, b) { - return BigInteger(a).leq(BigInteger(b)); -} - -function scalar_bigint_geq(a, b) { - return BigInteger(a).geq(BigInteger(b)); -} - -function scalar_bigint_band(a, b) { - return BigInteger(a).and(BigInteger(b)); -} - -function scalar_bigint_bor(a, b) { - return BigInteger(a).or(BigInteger(b)); -} - -function scalar_bigint_bxor(a, b) { - return BigInteger(a).xor(BigInteger(b)); -} - -function scalar_bigint_land(a, b) { - return (!BigInteger(a).isZero()) && (!BigInteger(b).isZero()); -} - -function scalar_bigint_lor(a, b) { - return (!BigInteger(a).isZero()) || (!BigInteger(b).isZero()); -} - -function scalar_bigint_lnot(a) { - return BigInteger(a).isZero(); -} - - - -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/scalar.js - - - - -const supportsNativeBigInt = typeof BigInt === "function"; - -let scalar_Scalar = {}; -if (supportsNativeBigInt) { - Object.assign(scalar_Scalar, scalar_native_namespaceObject); -} else { - Object.assign(scalar_Scalar, scalar_bigint_namespaceObject); -} - - -// Returns a buffer with Little Endian Representation -scalar_Scalar.toRprLE = function rprBE(buff, o, e, n8) { - const s = "0000000" + e.toString(16); - const v = new Uint32Array(buff.buffer, o, n8/4); - const l = (((s.length-7)*4 - 1) >> 5)+1; // Number of 32bit words; - for (let i=0; i> 5)+1; // Number of 32bit words; - for (let i=0; i a[a.length-i-1] = ch.toString(16).padStart(8,"0") ); - return scalar_Scalar.fromString(a.join(""), 16); -}; - -// Pases a buffer with Big Endian Representation -scalar_Scalar.fromRprBE = function rprLEM(buff, o, n8) { - n8 = n8 || buff.byteLength; - o = o || 0; - const v = new DataView(buff.buffer, buff.byteOffset + o, n8); - const a = new Array(n8/4); - for (let i=0; i. -*/ - -/* - This library does operations on polynomials with coefficients in a field F. - - A polynomial P(x) = p0 + p1 * x + p2 * x^2 + ... + pn * x^n is represented - by the array [ p0, p1, p2, ... , pn ]. - */ - -class PolField { - constructor (F) { - this.F = F; - - let rem = F.sqrt_t; - let s = F.sqrt_s; - - const five = this.F.add(this.F.add(this.F.two, this.F.two), this.F.one); - - this.w = new Array(s+1); - this.wi = new Array(s+1); - this.w[s] = this.F.pow(five, rem); - this.wi[s] = this.F.inv(this.w[s]); - - let n=s-1; - while (n>=0) { - this.w[n] = this.F.square(this.w[n+1]); - this.wi[n] = this.F.square(this.wi[n+1]); - n--; - } - - - this.roots = []; -/* for (let i=0; i<16; i++) { - let r = this.F.one; - n = 1 << i; - const rootsi = new Array(n); - for (let j=0; j this.F.sqrt_s) n = this.s; - for (let i=n; (i>=0) && (!this.roots[i]); i--) { - let r = this.F.one; - const nroots = 1 << i; - const rootsi = new Array(nroots); - for (let j=0; j a.length) { - [b, a] = [a, b]; - } - - if ((b.length <= 2) || (b.length < log2(a.length))) { - return this.mulNormal(a,b); - } else { - return this.mulFFT(a,b); - } - } - - mulNormal(a, b) { - let res = []; - for (let i=0; i0) { - const z = new Array(n).fill(this.F.zero); - return z.concat(p); - } else { - if (-n >= p.length) return []; - return p.slice(-n); - } - } - - eval2(p, x) { - let v = this.F.zero; - let ix = this.F.one; - for (let i=0; i> 1), - F.mul( - x, - _eval(p, newX, offset+step , step << 1, n >> 1))); - return res; - } - } - - lagrange(points) { - let roots = [this.F.one]; - for (let i=0; i> 1; - const p1 = this._fft(pall, bits-1, offset, step*2); - const p2 = this._fft(pall, bits-1, offset+step, step*2); - - const out = new Array(n); - - let m= this.F.one; - for (let i=0; i0 && this.F.eq(p[i], this.F.zero) ) i--; - return p.slice(0, i+1); - } - - eq(a, b) { - const pa = this.reduce(a); - const pb = this.reduce(b); - - if (pa.length != pb.length) return false; - for (let i=0; i=0; i--) { - res[i] = this.F.add(this.F.mul(res[i+1], r), p[i+1]); - } - return res; - } - - _next2Power(v) { - v--; - v |= v >> 1; - v |= v >> 2; - v |= v >> 4; - v |= v >> 8; - v |= v >> 16; - v++; - return v; - } - - toString(p) { - const ap = this.normalize(p); - let S = ""; - for (let i=ap.length-1; i>=0; i--) { - if (!this.F.eq(p[i], this.F.zero)) { - if (S!="") S += " + "; - S = S + p[i].toString(10); - if (i>0) { - S = S + "x"; - if (i>1) { - S = S + "^" +i; - } - } - } - } - return S; - } - - normalize(p) { - const res = new Array(p.length); - for (let i=0; i - // rec = x^(k-2-scaleV)/ v - // - // res = x^m/v = x^(m + (2*k-2 - scaleV) - (2*k-2 - scaleV)) /v => - // res = rec * x^(m - (2*k-2 - scaleV)) => - // res = rec * x^(m - 2*k + 2 + scaleV) - - const rec = this._reciprocal(this.scaleX(v, scaleV), kbits); - const res = this.scaleX(rec, m - 2*k + 2 + scaleV); - - return res; - } - - div(_u, _v) { - if (_u.length < _v.length) return []; - const kbits = log2(_v.length-1)+1; - const k = 1 << kbits; - - const u = this.scaleX(_u, k-_v.length); - const v = this.scaleX(_v, k-_v.length); - - const n = v.length-1; - let m = u.length-1; - - const s = this._reciprocal(v, kbits); - let t; - if (m>2*n) { - t = this.sub(this.scaleX([this.F.one], 2*n), this.mul(s, v)); - } - - let q = []; - let rem = u; - let us, ut; - let finish = false; - - while (!finish) { - us = this.mul(rem, s); - q = this.add(q, this.scaleX(us, -2*n)); - - if ( m > 2*n ) { - ut = this.mul(rem, t); - rem = this.scaleX(ut, -2*n); - m = rem.length-1; - } else { - finish = true; - } - } - - return q; - } - - - // returns the ith nth-root of one - oneRoot(n, i) { - let nbits = log2(n-1)+1; - let res = this.F.one; - let r = i; - - if(i>=n) { - throw new Error("Given 'i' should be lower than 'n'"); - } - else if (1<0) { - if (r & 1 == 1) { - res = this.F.mul(res, this.w[nbits]); - } - r = r >> 1; - nbits --; - } - return res; - } - - computeVanishingPolinomial(bits, t) { - const m = 1 << bits; - return this.F.sub(this.F.pow(t, m), this.F.one); - } - - evaluateLagrangePolynomials(bits, t) { - const m= 1 << bits; - const tm = this.F.pow(t, m); - const u= new Array(m).fill(this.F.zero); - this._setRoots(bits); - const omega = this.w[bits]; - - if (this.F.eq(tm, this.F.one)) { - for (let i = 0; i < m; i++) { - if (this.F.eq(this.roots[bits][0],t)) { // i.e., t equals omega^i - u[i] = this.F.one; - return u; - } - } - } - - const z = this.F.sub(tm, this.F.one); - // let l = this.F.mul(z, this.F.pow(this.F.twoinv, m)); - let l = this.F.mul(z, this.F.inv(this.F.e(m))); - for (let i = 0; i < m; i++) { - u[i] = this.F.mul(l, this.F.inv(this.F.sub(t,this.roots[bits][i]))); - l = this.F.mul(l, omega); - } - - return u; - } - - log2(V) { - return log2(V); - } -} - -function log2( V ) -{ - return( ( ( V & 0xFFFF0000 ) !== 0 ? ( V &= 0xFFFF0000, 16 ) : 0 ) | ( ( V & 0xFF00FF00 ) !== 0 ? ( V &= 0xFF00FF00, 8 ) : 0 ) | ( ( V & 0xF0F0F0F0 ) !== 0 ? ( V &= 0xF0F0F0F0, 4 ) : 0 ) | ( ( V & 0xCCCCCCCC ) !== 0 ? ( V &= 0xCCCCCCCC, 2 ) : 0 ) | ( ( V & 0xAAAAAAAA ) !== 0 ) ); -} - - -function __fft(PF, pall, bits, offset, step) { - - const n = 1 << bits; - if (n==1) { - return [ pall[offset] ]; - } else if (n==2) { - return [ - PF.F.add(pall[offset], pall[offset + step]), - PF.F.sub(pall[offset], pall[offset + step])]; - } - - const ndiv2 = n >> 1; - const p1 = __fft(PF, pall, bits-1, offset, step*2); - const p2 = __fft(PF, pall, bits-1, offset+step, step*2); - - const out = new Array(n); - - for (let i=0; i> 1; - const p1 = __fft2(PF, pall.slice(0, ndiv2), bits-1); - const p2 = __fft2(PF, pall.slice(ndiv2), bits-1); - - const out = new Array(n); - - for (let i=0; i>=1; - } - return res; -} - -function rev(idx, bits) { - return ( - _revTable[idx >>> 24] | - (_revTable[(idx >>> 16) & 0xFF] << 8) | - (_revTable[(idx >>> 8) & 0xFF] << 16) | - (_revTable[idx & 0xFF] << 24) - ) >>> (32-bits); -} - -function __bitReverse(p, bits) { - for (let k=0; kk) { - const tmp= p[k]; - p[k] = p[r]; - p[r] = tmp; - } - } - -} - - - -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/futils.js -/* - Copyright 2018 0kims association. - - This file is part of snarkjs. - - snarkjs is a free software: you can redistribute it and/or - modify it under the terms of the GNU General Public License as published by the - Free Software Foundation, either version 3 of the License, or (at your option) - any later version. - - snarkjs is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - more details. - - You should have received a copy of the GNU General Public License along with - snarkjs. If not, see . -*/ - - - - -function mulScalar(F, base, e) { - let res; - - if (Scalar.isZero(e)) return F.zero; - - const n = Scalar.naf(e); - - if (n[n.length-1] == 1) { - res = base; - } else if (n[n.length-1] == -1) { - res = F.neg(base); - } else { - throw new Error("invlaud NAF"); - } - - for (let i=n.length-2; i>=0; i--) { - - res = F.double(res); - - if (n[i] == 1) { - res = F.add(res, base); - } else if (n[i] == -1) { - res = F.sub(res, base); - } - } - - return res; -} - - -/* -exports.mulScalar = (F, base, e) =>{ - let res = F.zero; - let rem = bigInt(e); - let exp = base; - - while (! rem.eq(bigInt.zero)) { - if (rem.and(bigInt.one).eq(bigInt.one)) { - res = F.add(res, exp); - } - exp = F.double(exp); - rem = rem.shiftRight(1); - } - - return res; -}; -*/ - - -function futils_exp(F, base, e) { - - if (scalar_isZero(e)) return F.one; - - const n = scalar_bits(e); - - if (n.legth==0) return F.one; - - let res = base; - - for (let i=n.length-2; i>=0; i--) { - - res = F.square(res); - - if (n[i]) { - res = F.mul(res, base); - } - } - - return res; -} - - - -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/fsqrt.js - -// Check here: https://eprint.iacr.org/2012/685.pdf - -function fsqrt_buildSqrt (F) { - if ((F.m % 2) == 1) { - if (scalar_eq(scalar_mod(F.p, 4), 1 )) { - if (scalar_eq(scalar_mod(F.p, 8), 1 )) { - if (scalar_eq(scalar_mod(F.p, 16), 1 )) { - // alg7_muller(F); - alg5_tonelliShanks(F); - } else if (scalar_eq(scalar_mod(F.p, 16), 9 )) { - alg4_kong(F); - } else { - throw new Error("Field withot sqrt"); - } - } else if (scalar_eq(scalar_mod(F.p, 8), 5 )) { - alg3_atkin(F); - } else { - throw new Error("Field withot sqrt"); - } - } else if (scalar_eq(scalar_mod(F.p, 4), 3 )) { - alg2_shanks(F); - } - } else { - const pm2mod4 = scalar_mod(scalar_pow(F.p, F.m/2), 4); - if (pm2mod4 == 1) { - alg10_adj(F); - } else if (pm2mod4 == 3) { - alg9_adj(F); - } else { - alg8_complex(F); - } - - } -} - - -function alg5_tonelliShanks(F) { - F.sqrt_q = scalar_pow(F.p, F.m); - - F.sqrt_s = 0; - F.sqrt_t = scalar_sub(F.sqrt_q, 1); - - while (!scalar_isOdd(F.sqrt_t)) { - F.sqrt_s = F.sqrt_s + 1; - F.sqrt_t = scalar_div(F.sqrt_t, 2); - } - - let c0 = F.one; - - while (F.eq(c0, F.one)) { - const c = F.random(); - F.sqrt_z = F.pow(c, F.sqrt_t); - c0 = F.pow(F.sqrt_z, 2 ** (F.sqrt_s-1) ); - } - - F.sqrt_tm1d2 = scalar_div(scalar_sub(F.sqrt_t, 1),2); - - F.sqrt = function(a) { - const F=this; - if (F.isZero(a)) return F.zero; - let w = F.pow(a, F.sqrt_tm1d2); - const a0 = F.pow( F.mul(F.square(w), a), 2 ** (F.sqrt_s-1) ); - if (F.eq(a0, F.negone)) return null; - - let v = F.sqrt_s; - let x = F.mul(a, w); - let b = F.mul(x, w); - let z = F.sqrt_z; - while (!F.eq(b, F.one)) { - let b2k = F.square(b); - let k=1; - while (!F.eq(b2k, F.one)) { - b2k = F.square(b2k); - k++; - } - - w = z; - for (let i=0; i>> 0; - st[d] = (st[d] ^ st[a]) >>> 0; - st[d] = ((st[d] << 16) | ((st[d]>>>16) & 0xFFFF)) >>> 0; - - st[c] = (st[c] + st[d]) >>> 0; - st[b] = (st[b] ^ st[c]) >>> 0; - st[b] = ((st[b] << 12) | ((st[b]>>>20) & 0xFFF)) >>> 0; - - st[a] = (st[a] + st[b]) >>> 0; - st[d] = (st[d] ^ st[a]) >>> 0; - st[d] = ((st[d] << 8) | ((st[d]>>>24) & 0xFF)) >>> 0; - - st[c] = (st[c] + st[d]) >>> 0; - st[b] = (st[b] ^ st[c]) >>> 0; - st[b] = ((st[b] << 7) | ((st[b]>>>25) & 0x7F)) >>> 0; -} - -function doubleRound(st) { - quarterRound(st, 0, 4, 8,12); - quarterRound(st, 1, 5, 9,13); - quarterRound(st, 2, 6,10,14); - quarterRound(st, 3, 7,11,15); - - quarterRound(st, 0, 5,10,15); - quarterRound(st, 1, 6,11,12); - quarterRound(st, 2, 7, 8,13); - quarterRound(st, 3, 4, 9,14); -} - -class ChaCha { - - constructor(seed) { - seed = seed || [0,0,0,0,0,0,0,0]; - this.state = [ - 0x61707865, - 0x3320646E, - 0x79622D32, - 0x6B206574, - seed[0], - seed[1], - seed[2], - seed[3], - seed[4], - seed[5], - seed[6], - seed[7], - 0, - 0, - 0, - 0 - ]; - this.idx = 16; - this.buff = new Array(16); - } - - nextU32() { - if (this.idx == 16) this.update(); - return this.buff[this.idx++]; - } - - nextU64() { - return scalar_add(scalar_mul(this.nextU32(), 0x100000000), this.nextU32()); - } - - nextBool() { - return (this.nextU32() & 1) == 1; - } - - update() { - // Copy the state - for (let i=0; i<16; i++) this.buff[i] = this.state[i]; - - // Apply the rounds - for (let i=0; i<10; i++) doubleRound(this.buff); - - // Add to the initial - for (let i=0; i<16; i++) this.buff[i] = (this.buff[i] + this.state[i]) >>> 0; - - this.idx = 0; - - this.state[12] = (this.state[12] + 1) >>> 0; - if (this.state[12] != 0) return; - this.state[13] = (this.state[13] + 1) >>> 0; - if (this.state[13] != 0) return; - this.state[14] = (this.state[14] + 1) >>> 0; - if (this.state[14] != 0) return; - this.state[15] = (this.state[15] + 1) >>> 0; - } -} - -// EXTERNAL MODULE: ./node_modules/crypto-browserify/index.js -var crypto_browserify = __webpack_require__(1565); -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/random.js -/* provided dependency */ var process = __webpack_require__(5606); - - - -function getRandomBytes(n) { - let array = new Uint8Array(n); - if (process.browser) { // Browser - if (typeof globalThis.crypto !== "undefined") { // Supported - globalThis.crypto.getRandomValues(array); - } else { // fallback - for (let i=0; i>>0; - } - } - } - else { // NodeJS - crypto_browserify.randomFillSync(array); - } - return array; -} - -function getRandomSeed() { - const arr = getRandomBytes(32); - const arrV = new Uint32Array(arr.buffer); - const seed = []; - for (let i=0; i<8; i++) { - seed.push(arrV[i]); - } - return seed; -} - -let threadRng = null; - -function getThreadRng() { - if (threadRng) return threadRng; - threadRng = new ChaCha(getRandomSeed()); - return threadRng; -} - -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/f1field_native.js -/* global BigInt */ - - - - - -class ZqField { - constructor(p) { - this.type="F1"; - this.one = BigInt(1); - this.zero = BigInt(0); - this.p = BigInt(p); - this.m = 1; - this.negone = this.p-this.one; - this.two = BigInt(2); - this.half = this.p >> this.one; - this.bitLength = scalar_bitLength(this.p); - this.mask = (this.one << BigInt(this.bitLength)) - this.one; - - this.n64 = Math.floor((this.bitLength - 1) / 64)+1; - this.n32 = this.n64*2; - this.n8 = this.n64*8; - this.R = this.e(this.one << BigInt(this.n64*64)); - this.Ri = this.inv(this.R); - - const e = this.negone >> this.one; - this.nqr = this.two; - let r = this.pow(this.nqr, e); - while (!this.eq(r, this.negone)) { - this.nqr = this.nqr + this.one; - r = this.pow(this.nqr, e); - } - - - this.s = 0; - this.t = this.negone; - - while ((this.t & this.one) == this.zero) { - this.s = this.s + 1; - this.t = this.t >> this.one; - } - - this.nqr_to_t = this.pow(this.nqr, this.t); - - fsqrt_buildSqrt(this); - } - - e(a,b) { - let res; - if (!b) { - res = BigInt(a); - } else if (b==16) { - res = BigInt("0x"+a); - } - if (res < 0) { - let nres = -res; - if (nres >= this.p) nres = nres % this.p; - return this.p - nres; - } else { - return (res>= this.p) ? res%this.p : res; - } - - } - - add(a, b) { - const res = a + b; - return res >= this.p ? res-this.p : res; - } - - sub(a, b) { - return (a >= b) ? a-b : this.p-b+a; - } - - neg(a) { - return a ? this.p-a : a; - } - - mul(a, b) { - return (a*b)%this.p; - } - - mulScalar(base, s) { - return (base * this.e(s)) % this.p; - } - - square(a) { - return (a*a) % this.p; - } - - eq(a, b) { - return a==b; - } - - neq(a, b) { - return a!=b; - } - - lt(a, b) { - const aa = (a > this.half) ? a - this.p : a; - const bb = (b > this.half) ? b - this.p : b; - return aa < bb; - } - - gt(a, b) { - const aa = (a > this.half) ? a - this.p : a; - const bb = (b > this.half) ? b - this.p : b; - return aa > bb; - } - - leq(a, b) { - const aa = (a > this.half) ? a - this.p : a; - const bb = (b > this.half) ? b - this.p : b; - return aa <= bb; - } - - geq(a, b) { - const aa = (a > this.half) ? a - this.p : a; - const bb = (b > this.half) ? b - this.p : b; - return aa >= bb; - } - - div(a, b) { - return this.mul(a, this.inv(b)); - } - - idiv(a, b) { - if (!b) throw new Error("Division by zero"); - return a / b; - } - - inv(a) { - if (!a) throw new Error("Division by zero"); - - let t = this.zero; - let r = this.p; - let newt = this.one; - let newr = a % this.p; - while (newr) { - let q = r/newr; - [t, newt] = [newt, t-q*newt]; - [r, newr] = [newr, r-q*newr]; - } - if (t= this.p ? res-this.p : res; - } - - bor(a, b) { - const res = ((a | b) & this.mask); - return res >= this.p ? res-this.p : res; - } - - bxor(a, b) { - const res = ((a ^ b) & this.mask); - return res >= this.p ? res-this.p : res; - } - - bnot(a) { - const res = a ^ this.mask; - return res >= this.p ? res-this.p : res; - } - - shl(a, b) { - if (Number(b) < this.bitLength) { - const res = (a << b) & this.mask; - return res >= this.p ? res-this.p : res; - } else { - const nb = this.p - b; - if (Number(nb) < this.bitLength) { - return a >> nb; - } else { - return this.zero; - } - } - } - - shr(a, b) { - if (Number(b) < this.bitLength) { - return a >> b; - } else { - const nb = this.p - b; - if (Number(nb) < this.bitLength) { - const res = (a << nb) & this.mask; - return res >= this.p ? res-this.p : res; - } else { - return 0; - } - } - } - - land(a, b) { - return (a && b) ? this.one : this.zero; - } - - lor(a, b) { - return (a || b) ? this.one : this.zero; - } - - lnot(a) { - return (a) ? this.zero : this.one; - } - - sqrt_old(n) { - - if (n == this.zero) return this.zero; - - // Test that have solution - const res = this.pow(n, this.negone >> this.one); - if ( res != this.one ) return null; - - let m = this.s; - let c = this.nqr_to_t; - let t = this.pow(n, this.t); - let r = this.pow(n, this.add(this.t, this.one) >> this.one ); - - while ( t != this.one ) { - let sq = this.square(t); - let i = 1; - while (sq != this.one ) { - i++; - sq = this.square(sq); - } - - // b = c ^ m-i-1 - let b = c; - for (let j=0; j< m-i-1; j ++) b = this.square(b); - - m = i; - c = this.square(b); - t = this.mul(t, c); - r = this.mul(r, b); - } - - if (r > (this.p >> this.one)) { - r = this.neg(r); - } - - return r; - } - - normalize(a, b) { - a = BigInt(a,b); - if (a < 0) { - let na = -a; - if (na >= this.p) na = na % this.p; - return this.p - na; - } else { - return (a>= this.p) ? a%this.p : a; - } - } - - random() { - const nBytes = (this.bitLength*2 / 8); - let res =this.zero; - for (let i=0; i this.half) { - const v = this.p-a; - vs = "-"+v.toString(base); - } else { - vs = a.toString(base); - } - return vs; - } - - isZero(a) { - return a == this.zero; - } - - fromRng(rng) { - let v; - do { - v=this.zero; - for (let i=0; i= this.p); - v = (v * this.Ri) % this.p; // Convert from montgomery - return v; - } - -} - - -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/f1field_bigint.js - - - - -class f1field_bigint_ZqField { - constructor(p) { - this.type="F1"; - this.one = BigInteger.one; - this.zero = BigInteger.zero; - this.p = BigInteger(p); - this.m = 1; - this.negone = this.p.minus(BigInteger.one); - this.two = BigInteger(2); - this.half = this.p.shiftRight(1); - this.bitLength = this.p.bitLength(); - this.mask = BigInteger.one.shiftLeft(this.bitLength).minus(BigInteger.one); - - this.n64 = Math.floor((this.bitLength - 1) / 64)+1; - this.n32 = this.n64*2; - this.n8 = this.n64*8; - this.R = BigInteger.one.shiftLeft(this.n64*64); - this.Ri = this.inv(this.R); - - const e = this.negone.shiftRight(this.one); - this.nqr = this.two; - let r = this.pow(this.nqr, e); - while (!r.equals(this.negone)) { - this.nqr = this.nqr.add(this.one); - r = this.pow(this.nqr, e); - } - - this.s = this.zero; - this.t = this.negone; - - while (!this.t.isOdd()) { - this.s = this.s.add(this.one); - this.t = this.t.shiftRight(this.one); - } - - this.nqr_to_t = this.pow(this.nqr, this.t); - - fsqrt_buildSqrt(this); - } - - e(a,b) { - - const res = BigInteger(a,b); - - return this.normalize(res); - - } - - add(a, b) { - let res = a.add(b); - if (res.geq(this.p)) { - res = res.minus(this.p); - } - return res; - } - - sub(a, b) { - if (a.geq(b)) { - return a.minus(b); - } else { - return this.p.minus(b.minus(a)); - } - } - - neg(a) { - if (a.isZero()) return a; - return this.p.minus(a); - } - - mul(a, b) { - return a.times(b).mod(this.p); - } - - mulScalar(base, s) { - return base.times(BigInteger(s)).mod(this.p); - } - - square(a) { - return a.square().mod(this.p); - } - - eq(a, b) { - return a.eq(b); - } - - neq(a, b) { - return a.neq(b); - } - - lt(a, b) { - const aa = a.gt(this.half) ? a.minus(this.p) : a; - const bb = b.gt(this.half) ? b.minus(this.p) : b; - return aa.lt(bb); - } - - gt(a, b) { - const aa = a.gt(this.half) ? a.minus(this.p) : a; - const bb = b.gt(this.half) ? b.minus(this.p) : b; - return aa.gt(bb); - } - - leq(a, b) { - const aa = a.gt(this.half) ? a.minus(this.p) : a; - const bb = b.gt(this.half) ? b.minus(this.p) : b; - return aa.leq(bb); - } - - geq(a, b) { - const aa = a.gt(this.half) ? a.minus(this.p) : a; - const bb = b.gt(this.half) ? b.minus(this.p) : b; - return aa.geq(bb); - } - - div(a, b) { - if (b.isZero()) throw new Error("Division by zero"); - return a.times(b.modInv(this.p)).mod(this.p); - } - - idiv(a, b) { - if (b.isZero()) throw new Error("Division by zero"); - return a.divide(b); - } - - inv(a) { - if (a.isZero()) throw new Error("Division by zero"); - return a.modInv(this.p); - } - - mod(a, b) { - return a.mod(b); - } - - pow(a, b) { - return a.modPow(b, this.p); - } - - exp(a, b) { - return a.modPow(b, this.p); - } - - band(a, b) { - return a.and(b).and(this.mask).mod(this.p); - } - - bor(a, b) { - return a.or(b).and(this.mask).mod(this.p); - } - - bxor(a, b) { - return a.xor(b).and(this.mask).mod(this.p); - } - - bnot(a) { - return a.xor(this.mask).mod(this.p); - } - - shl(a, b) { - if (b.lt(this.bitLength)) { - return a.shiftLeft(b).and(this.mask).mod(this.p); - } else { - const nb = this.p.minus(b); - if (nb.lt(this.bitLength)) { - return this.shr(a, nb); - } else { - return BigInteger.zero; - } - } - } - - shr(a, b) { - if (b.lt(this.bitLength)) { - return a.shiftRight(b); - } else { - const nb = this.p.minus(b); - if (nb.lt(this.bitLength)) { - return this.shl(a, nb); - } else { - return BigInteger.zero; - } - } - } - - land(a, b) { - return (a.isZero() || b.isZero()) ? BigInteger.zero : BigInteger.one; - } - - lor(a, b) { - return (a.isZero() && b.isZero()) ? BigInteger.zero : BigInteger.one; - } - - lnot(a) { - return a.isZero() ? BigInteger.one : BigInteger.zero; - } - - sqrt_old(n) { - - if (n.equals(this.zero)) return this.zero; - - // Test that have solution - const res = this.pow(n, this.negone.shiftRight(this.one)); - if (!res.equals(this.one)) return null; - - let m = parseInt(this.s); - let c = this.nqr_to_t; - let t = this.pow(n, this.t); - let r = this.pow(n, this.add(this.t, this.one).shiftRight(this.one) ); - - while (!t.equals(this.one)) { - let sq = this.square(t); - let i = 1; - while (!sq.equals(this.one)) { - i++; - sq = this.square(sq); - } - - // b = c ^ m-i-1 - let b = c; - for (let j=0; j< m-i-1; j ++) b = this.square(b); - - m = i; - c = this.square(b); - t = this.mul(t, c); - r = this.mul(r, b); - } - - if (r.greater(this.p.shiftRight(this.one))) { - r = this.neg(r); - } - - return r; - } - - normalize(a) { - a = BigInteger(a); - if (a.isNegative()) { - return this.p.minus(a.abs().mod(this.p)); - } else { - return a.mod(this.p); - } - } - - random() { - let res = BigInteger(0); - let n = BigInteger(this.p.square()); - while (!n.isZero()) { - res = res.shiftLeft(8).add(BigInteger(getRandomBytes(1)[0])); - n = n.shiftRight(8); - } - return res.mod(this.p); - } - - toString(a, base) { - let vs; - if (!a.lesserOrEquals(this.p.shiftRight(BigInteger(1)))) { - const v = this.p.minus(a); - vs = "-"+v.toString(base); - } else { - vs = a.toString(base); - } - - return vs; - } - - isZero(a) { - return a.isZero(); - } - - fromRng(rng) { - let v; - do { - v = BigInteger(0); - for (let i=0; i. -*/ - - - - -class F2Field { - constructor(F, nonResidue) { - this.type="F2"; - this.F = F; - this.zero = [this.F.zero, this.F.zero]; - this.one = [this.F.one, this.F.zero]; - this.negone = this.neg(this.one); - this.nonResidue = nonResidue; - this.m = F.m*2; - this.p = F.p; - this.n64 = F.n64*2; - this.n32 = this.n64*2; - this.n8 = this.n64*8; - - buildSqrt(this); - } - - _mulByNonResidue(a) { - return this.F.mul(this.nonResidue, a); - } - - copy(a) { - return [this.F.copy(a[0]), this.F.copy(a[1])]; - } - - add(a, b) { - return [ - this.F.add(a[0], b[0]), - this.F.add(a[1], b[1]) - ]; - } - - double(a) { - return this.add(a,a); - } - - sub(a, b) { - return [ - this.F.sub(a[0], b[0]), - this.F.sub(a[1], b[1]) - ]; - } - - neg(a) { - return this.sub(this.zero, a); - } - - conjugate(a) { - return [ - a[0], - this.F.neg(a[1]) - ]; - } - - mul(a, b) { - const aA = this.F.mul(a[0] , b[0]); - const bB = this.F.mul(a[1] , b[1]); - - return [ - this.F.add( aA , this._mulByNonResidue(bB)), - this.F.sub( - this.F.mul( - this.F.add(a[0], a[1]), - this.F.add(b[0], b[1])), - this.F.add(aA, bB))]; - } - - inv(a) { - const t0 = this.F.square(a[0]); - const t1 = this.F.square(a[1]); - const t2 = this.F.sub(t0, this._mulByNonResidue(t1)); - const t3 = this.F.inv(t2); - return [ - this.F.mul(a[0], t3), - this.F.neg(this.F.mul( a[1], t3)) ]; - } - - div(a, b) { - return this.mul(a, this.inv(b)); - } - - square(a) { - const ab = this.F.mul(a[0] , a[1]); - - /* - [ - (a + b) * (a + non_residue * b) - ab - non_residue * ab, - ab + ab - ]; - */ - - return [ - this.F.sub( - this.F.mul( - this.F.add(a[0], a[1]) , - this.F.add( - a[0] , - this._mulByNonResidue(a[1]))), - this.F.add( - ab, - this._mulByNonResidue(ab))), - this.F.add(ab, ab) - ]; - } - - isZero(a) { - return this.F.isZero(a[0]) && this.F.isZero(a[1]); - } - - eq(a, b) { - return this.F.eq(a[0], b[0]) && this.F.eq(a[1], b[1]); - } - - mulScalar(base, e) { - return fUtils.mulScalar(this, base, e); - } - - pow(base, e) { - return fUtils.exp(this, base, e); - } - - exp(base, e) { - return fUtils.exp(this, base, e); - } - - toString(a) { - return `[ ${this.F.toString(a[0])} , ${this.F.toString(a[1])} ]`; - } - - fromRng(rng) { - const c0 = this.F.fromRng(rng); - const c1 = this.F.fromRng(rng); - return [c0, c1]; - } - - gt(a, b) { - if (this.F.gt(a[0], b[0])) return true; - if (this.F.gt(b[0], a[0])) return false; - if (this.F.gt(a[1], b[1])) return true; - return false; - } - - geq(a, b) { - return this.gt(a, b) || this.eq(a, b); - } - - lt(a, b) { - return !this.geq(a,b); - } - - leq(a, b) { - return !this.gt(a,b); - } - - neq(a, b) { - return !this.eq(a,b); - } - - random() { - return [this.F.random(), this.F.random()]; - } - - - toRprLE(buff, o, e) { - this.F.toRprLE(buff, o, e[0]); - this.F.toRprLE(buff, o+this.F.n8, e[1]); - } - - toRprBE(buff, o, e) { - this.F.toRprBE(buff, o, e[1]); - this.F.toRprBE(buff, o+this.F.n8, e[0]); - } - - toRprLEM(buff, o, e) { - this.F.toRprLEM(buff, o, e[0]); - this.F.toRprLEM(buff, o+this.F.n8, e[1]); - } - - - toRprBEM(buff, o, e) { - this.F.toRprBEM(buff, o, e[1]); - this.F.toRprBEM(buff, o+this.F.n8, e[0]); - } - - fromRprLE(buff, o) { - o = o || 0; - const c0 = this.F.fromRprLE(buff, o); - const c1 = this.F.fromRprLE(buff, o+this.F.n8); - return [c0, c1]; - } - - fromRprBE(buff, o) { - o = o || 0; - const c1 = this.F.fromRprBE(buff, o); - const c0 = this.F.fromRprBE(buff, o+this.F.n8); - return [c0, c1]; - } - - fromRprLEM(buff, o) { - o = o || 0; - const c0 = this.F.fromRprLEM(buff, o); - const c1 = this.F.fromRprLEM(buff, o+this.F.n8); - return [c0, c1]; - } - - fromRprBEM(buff, o) { - o = o || 0; - const c1 = this.F.fromRprBEM(buff, o); - const c0 = this.F.fromRprBEM(buff, o+this.F.n8); - return [c0, c1]; - } - -} - - -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/f3field.js -/* - Copyright 2018 0kims association. - - This file is part of snarkjs. - - snarkjs is a free software: you can redistribute it and/or - modify it under the terms of the GNU General Public License as published by the - Free Software Foundation, either version 3 of the License, or (at your option) - any later version. - - snarkjs is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - more details. - - You should have received a copy of the GNU General Public License along with - snarkjs. If not, see . -*/ - - - -class F3Field { - constructor(F, nonResidue) { - this.type="F3"; - this.F = F; - this.zero = [this.F.zero, this.F.zero, this.F.zero]; - this.one = [this.F.one, this.F.zero, this.F.zero]; - this.negone = this.neg(this.one); - this.nonResidue = nonResidue; - this.m = F.m*3; - this.p = F.p; - this.n64 = F.n64*3; - this.n32 = this.n64*2; - this.n8 = this.n64*8; - } - - _mulByNonResidue(a) { - return this.F.mul(this.nonResidue, a); - } - - copy(a) { - return [this.F.copy(a[0]), this.F.copy(a[1]), this.F.copy(a[2])]; - } - - add(a, b) { - return [ - this.F.add(a[0], b[0]), - this.F.add(a[1], b[1]), - this.F.add(a[2], b[2]) - ]; - } - - double(a) { - return this.add(a,a); - } - - sub(a, b) { - return [ - this.F.sub(a[0], b[0]), - this.F.sub(a[1], b[1]), - this.F.sub(a[2], b[2]) - ]; - } - - neg(a) { - return this.sub(this.zero, a); - } - - mul(a, b) { - - const aA = this.F.mul(a[0] , b[0]); - const bB = this.F.mul(a[1] , b[1]); - const cC = this.F.mul(a[2] , b[2]); - - return [ - this.F.add( - aA, - this._mulByNonResidue( - this.F.sub( - this.F.mul( - this.F.add(a[1], a[2]), - this.F.add(b[1], b[2])), - this.F.add(bB, cC)))), // aA + non_residue*((b+c)*(B+C)-bB-cC), - - this.F.add( - this.F.sub( - this.F.mul( - this.F.add(a[0], a[1]), - this.F.add(b[0], b[1])), - this.F.add(aA, bB)), - this._mulByNonResidue( cC)), // (a+b)*(A+B)-aA-bB+non_residue*cC - - this.F.add( - this.F.sub( - this.F.mul( - this.F.add(a[0], a[2]), - this.F.add(b[0], b[2])), - this.F.add(aA, cC)), - bB)]; // (a+c)*(A+C)-aA+bB-cC) - } - - inv(a) { - const t0 = this.F.square(a[0]); // t0 = a^2 ; - const t1 = this.F.square(a[1]); // t1 = b^2 ; - const t2 = this.F.square(a[2]); // t2 = c^2; - const t3 = this.F.mul(a[0],a[1]); // t3 = ab - const t4 = this.F.mul(a[0],a[2]); // t4 = ac - const t5 = this.F.mul(a[1],a[2]); // t5 = bc; - // c0 = t0 - non_residue * t5; - const c0 = this.F.sub(t0, this._mulByNonResidue(t5)); - // c1 = non_residue * t2 - t3; - const c1 = this.F.sub(this._mulByNonResidue(t2), t3); - const c2 = this.F.sub(t1, t4); // c2 = t1-t4 - - // t6 = (a * c0 + non_residue * (c * c1 + b * c2)).inv(); - const t6 = - this.F.inv( - this.F.add( - this.F.mul(a[0], c0), - this._mulByNonResidue( - this.F.add( - this.F.mul(a[2], c1), - this.F.mul(a[1], c2))))); - - return [ - this.F.mul(t6, c0), // t6*c0 - this.F.mul(t6, c1), // t6*c1 - this.F.mul(t6, c2)]; // t6*c2 - } - - div(a, b) { - return this.mul(a, this.inv(b)); - } - - square(a) { - const s0 = this.F.square(a[0]); // s0 = a^2 - const ab = this.F.mul(a[0], a[1]); // ab = a*b - const s1 = this.F.add(ab, ab); // s1 = 2ab; - const s2 = this.F.square( - this.F.add(this.F.sub(a[0],a[1]), a[2])); // s2 = (a - b + c)^2; - const bc = this.F.mul(a[1],a[2]); // bc = b*c - const s3 = this.F.add(bc, bc); // s3 = 2*bc - const s4 = this.F.square(a[2]); // s4 = c^2 - - - return [ - this.F.add( - s0, - this._mulByNonResidue(s3)), // s0 + non_residue * s3, - this.F.add( - s1, - this._mulByNonResidue(s4)), // s1 + non_residue * s4, - this.F.sub( - this.F.add( this.F.add(s1, s2) , s3 ), - this.F.add(s0, s4))]; // s1 + s2 + s3 - s0 - s4 - } - - isZero(a) { - return this.F.isZero(a[0]) && this.F.isZero(a[1]) && this.F.isZero(a[2]); - } - - eq(a, b) { - return this.F.eq(a[0], b[0]) && this.F.eq(a[1], b[1]) && this.F.eq(a[2], b[2]); - } - - affine(a) { - return [this.F.affine(a[0]), this.F.affine(a[1]), this.F.affine(a[2])]; - } - - mulScalar(base, e) { - return fUtils.mulScalar(this, base, e); - } - - pow(base, e) { - return fUtils.exp(this, base, e); - } - - exp(base, e) { - return fUtils.exp(this, base, e); - } - - toString(a) { - return `[ ${this.F.toString(a[0])} , ${this.F.toString(a[1])}, ${this.F.toString(a[2])} ]`; - } - - fromRng(rng) { - const c0 = this.F.fromRng(rng); - const c1 = this.F.fromRng(rng); - const c2 = this.F.fromRng(rng); - return [c0, c1, c2]; - } - - gt(a, b) { - if (this.F.gt(a[0], b[0])) return true; - if (this.F.gt(b[0], a[0])) return false; - if (this.F.gt(a[1], b[1])) return true; - if (this.F.gt(b[1], a[1])) return false; - if (this.F.gt(a[2], b[2])) return true; - return false; - } - - - geq(a, b) { - return this.gt(a, b) || this.eq(a, b); - } - - lt(a, b) { - return !this.geq(a,b); - } - - leq(a, b) { - return !this.gt(a,b); - } - - neq(a, b) { - return !this.eq(a,b); - } - - random() { - return [this.F.random(), this.F.random(), this.F.random()]; - } - - - toRprLE(buff, o, e) { - this.F.toRprLE(buff, o, e[0]); - this.F.toRprLE(buff, o+this.F.n8, e[1]); - this.F.toRprLE(buff, o+this.F.n8*2, e[2]); - } - - toRprBE(buff, o, e) { - this.F.toRprBE(buff, o, e[2]); - this.F.toRprBE(buff, o+this.F.n8, e[1]); - this.F.toRprBE(buff, o+this.F.n8*2, e[0]); - } - - toRprLEM(buff, o, e) { - this.F.toRprLEM(buff, o, e[0]); - this.F.toRprLEM(buff, o+this.F.n8, e[1]); - this.F.toRprLEM(buff, o+this.F.n8*2, e[2]); - } - - - toRprBEM(buff, o, e) { - this.F.toRprBEM(buff, o, e[2]); - this.F.toRprBEM(buff, o+this.F.n8, e[1]); - this.F.toRprBEM(buff, o+this.F.n8*2, e[0]); - } - - fromRprLE(buff, o) { - o = o || 0; - const c0 = this.F.fromRprLE(buff, o); - const c1 = this.F.fromRprLE(buff, o+this.n8); - const c2 = this.F.fromRprLE(buff, o+this.n8*2); - return [c0, c1, c2]; - } - - fromRprBE(buff, o) { - o = o || 0; - const c2 = this.F.fromRprBE(buff, o); - const c1 = this.F.fromRprBE(buff, o+this.n8); - const c0 = this.F.fromRprBE(buff, o+this.n8*2); - return [c0, c1, c2]; - } - - fromRprLEM(buff, o) { - o = o || 0; - const c0 = this.F.fromRprLEM(buff, o); - const c1 = this.F.fromRprLEM(buff, o+this.n8); - const c2 = this.F.fromRprLEM(buff, o+this.n8*2); - return [c0, c1, c2]; - } - - fromRprBEM(buff, o) { - o = o || 0; - const c2 = this.F.fromRprBEM(buff, o); - const c1 = this.F.fromRprBEM(buff, o+this.n8); - const c0 = this.F.fromRprBEM(buff, o+this.n8*2); - return [c0, c1, c2]; - } - -} - -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/ec.js -/* - Copyright 2018 0kims association. - - This file is part of snarkjs. - - snarkjs is a free software: you can redistribute it and/or - modify it under the terms of the GNU General Public License as published by the - Free Software Foundation, either version 3 of the License, or (at your option) - any later version. - - snarkjs is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - more details. - - You should have received a copy of the GNU General Public License along with - snarkjs. If not, see . -*/ - - - - - - - -function isGreatest(F, a) { - if (Array.isArray(a)) { - for (let i=a.length-1; i>=0; i--) { - if (!F.F.isZero(a[i])) { - return isGreatest(F.F, a[i]); - } - } - return 0; - } else { - const na = F.neg(a); - return Scalar.gt(a, na); - } -} - - -class EC { - - constructor(F, g) { - this.F = F; - this.g = g; - if (this.g.length == 2) this.g[2] = this.F.one; - this.zero = [this.F.zero, this.F.one, this.F.zero]; - } - - add(p1, p2) { - - const F = this.F; - - if (this.eq(p1, this.zero)) return p2; - if (this.eq(p2, this.zero)) return p1; - - const res = new Array(3); - - const Z1Z1 = F.square( p1[2] ); - const Z2Z2 = F.square( p2[2] ); - - const U1 = F.mul( p1[0] , Z2Z2 ); // U1 = X1 * Z2Z2 - const U2 = F.mul( p2[0] , Z1Z1 ); // U2 = X2 * Z1Z1 - - const Z1_cubed = F.mul( p1[2] , Z1Z1); - const Z2_cubed = F.mul( p2[2] , Z2Z2); - - const S1 = F.mul( p1[1] , Z2_cubed); // S1 = Y1 * Z2 * Z2Z2 - const S2 = F.mul( p2[1] , Z1_cubed); // S2 = Y2 * Z1 * Z1Z1 - - if (F.eq(U1,U2) && F.eq(S1,S2)) { - return this.double(p1); - } - - const H = F.sub( U2 , U1 ); // H = U2-U1 - - const S2_minus_S1 = F.sub( S2 , S1 ); - - const I = F.square( F.add(H,H) ); // I = (2 * H)^2 - const J = F.mul( H , I ); // J = H * I - - const r = F.add( S2_minus_S1 , S2_minus_S1 ); // r = 2 * (S2-S1) - const V = F.mul( U1 , I ); // V = U1 * I - - res[0] = - F.sub( - F.sub( F.square(r) , J ), - F.add( V , V )); // X3 = r^2 - J - 2 * V - - const S1_J = F.mul( S1 , J ); - - res[1] = - F.sub( - F.mul( r , F.sub(V,res[0])), - F.add( S1_J,S1_J )); // Y3 = r * (V-X3)-2 S1 J - - res[2] = - F.mul( - H, - F.sub( - F.square( F.add(p1[2],p2[2]) ), - F.add( Z1Z1 , Z2Z2 ))); // Z3 = ((Z1+Z2)^2-Z1Z1-Z2Z2) * H - - return res; - } - - neg(p) { - return [p[0], this.F.neg(p[1]), p[2]]; - } - - sub(a, b) { - return this.add(a, this.neg(b)); - } - - double(p) { - const F = this.F; - - const res = new Array(3); - - if (this.eq(p, this.zero)) return p; - - const A = F.square( p[0] ); // A = X1^2 - const B = F.square( p[1] ); // B = Y1^2 - const C = F.square( B ); // C = B^2 - - let D = - F.sub( - F.square( F.add(p[0] , B )), - F.add( A , C)); - D = F.add(D,D); // D = 2 * ((X1 + B)^2 - A - C) - - const E = F.add( F.add(A,A), A); // E = 3 * A - const FF =F.square( E ); // F = E^2 - - res[0] = F.sub( FF , F.add(D,D) ); // X3 = F - 2 D - - let eightC = F.add( C , C ); - eightC = F.add( eightC , eightC ); - eightC = F.add( eightC , eightC ); - - res[1] = - F.sub( - F.mul( - E, - F.sub( D, res[0] )), - eightC); // Y3 = E * (D - X3) - 8 * C - - const Y1Z1 = F.mul( p[1] , p[2] ); - res[2] = F.add( Y1Z1 , Y1Z1 ); // Z3 = 2 * Y1 * Z1 - - return res; - } - - timesScalar(base, e) { - return fUtils.mulScalar(this, base, e); - } - - mulScalar(base, e) { - return fUtils.mulScalar(this, base, e); - } - - affine(p) { - const F = this.F; - if (this.isZero(p)) { - return this.zero; - } else if (F.eq(p[2], F.one)) { - return p; - } else { - const Z_inv = F.inv(p[2]); - const Z2_inv = F.square(Z_inv); - const Z3_inv = F.mul(Z2_inv, Z_inv); - - const res = new Array(3); - res[0] = F.mul(p[0],Z2_inv); - res[1] = F.mul(p[1],Z3_inv); - res[2] = F.one; - - return res; - } - } - - multiAffine(arr) { - const keys = Object.keys(arr); - const F = this.F; - const accMul = new Array(keys.length+1); - accMul[0] = F.one; - for (let i = 0; i< keys.length; i++) { - if (F.eq(arr[keys[i]][2], F.zero)) { - accMul[i+1] = accMul[i]; - } else { - accMul[i+1] = F.mul(accMul[i], arr[keys[i]][2]); - } - } - - accMul[keys.length] = F.inv(accMul[keys.length]); - - for (let i = keys.length-1; i>=0; i--) { - if (F.eq(arr[keys[i]][2], F.zero)) { - accMul[i] = accMul[i+1]; - arr[keys[i]] = this.zero; - } else { - const Z_inv = F.mul(accMul[i], accMul[i+1]); - accMul[i] = F.mul(arr[keys[i]][2], accMul[i+1]); - - const Z2_inv = F.square(Z_inv); - const Z3_inv = F.mul(Z2_inv, Z_inv); - - arr[keys[i]][0] = F.mul(arr[keys[i]][0],Z2_inv); - arr[keys[i]][1] = F.mul(arr[keys[i]][1],Z3_inv); - arr[keys[i]][2] = F.one; - } - } - - } - - eq(p1, p2) { - const F = this.F; - - if (this.F.eq(p1[2], this.F.zero)) return this.F.eq(p2[2], this.F.zero); - if (this.F.eq(p2[2], this.F.zero)) return false; - - const Z1Z1 = F.square( p1[2] ); - const Z2Z2 = F.square( p2[2] ); - - const U1 = F.mul( p1[0] , Z2Z2 ); - const U2 = F.mul( p2[0] , Z1Z1 ); - - const Z1_cubed = F.mul( p1[2] , Z1Z1); - const Z2_cubed = F.mul( p2[2] , Z2Z2); - - const S1 = F.mul( p1[1] , Z2_cubed); - const S2 = F.mul( p2[1] , Z1_cubed); - - return (F.eq(U1,U2) && F.eq(S1,S2)); - } - - isZero(p) { - return this.F.isZero(p[2]); - } - - toString(p) { - const cp = this.affine(p); - return `[ ${this.F.toString(cp[0])} , ${this.F.toString(cp[1])} ]`; - } - - fromRng(rng) { - const F = this.F; - let P = []; - let greatest; - do { - P[0] = F.fromRng(rng); - greatest = rng.nextBool(); - const x3b = F.add(F.mul(F.square(P[0]), P[0]), this.b); - P[1] = F.sqrt(x3b); - } while ((P[1] == null)||(F.isZero[P])); - - const s = isGreatest(F, P[1]); - if (greatest ^ s) P[1] = F.neg(P[1]); - P[2] = F.one; - - if (this.cofactor) { - P = this.mulScalar(P, this.cofactor); - } - - P = this.affine(P); - - return P; - - } - - toRprLE(buff, o, p) { - p = this.affine(p); - if (this.isZero(p)) { - const BuffV = new Uint8Array(buff, o, this.F.n8*2); - BuffV.fill(0); - return; - } - this.F.toRprLE(buff, o, p[0]); - this.F.toRprLE(buff, o+this.F.n8, p[1]); - } - - toRprBE(buff, o, p) { - p = this.affine(p); - if (this.isZero(p)) { - const BuffV = new Uint8Array(buff, o, this.F.n8*2); - BuffV.fill(0); - return; - } - this.F.toRprBE(buff, o, p[0]); - this.F.toRprBE(buff, o+this.F.n8, p[1]); - } - - toRprLEM(buff, o, p) { - p = this.affine(p); - if (this.isZero(p)) { - const BuffV = new Uint8Array(buff, o, this.F.n8*2); - BuffV.fill(0); - return; - } - this.F.toRprLEM(buff, o, p[0]); - this.F.toRprLEM(buff, o+this.F.n8, p[1]); - } - - toRprLEJM(buff, o, p) { - p = this.affine(p); - if (this.isZero(p)) { - const BuffV = new Uint8Array(buff, o, this.F.n8*2); - BuffV.fill(0); - return; - } - this.F.toRprLEM(buff, o, p[0]); - this.F.toRprLEM(buff, o+this.F.n8, p[1]); - this.F.toRprLEM(buff, o+2*this.F.n8, p[2]); - } - - - toRprBEM(buff, o, p) { - p = this.affine(p); - if (this.isZero(p)) { - const BuffV = new Uint8Array(buff, o, this.F.n8*2); - BuffV.fill(0); - return; - } - this.F.toRprBEM(buff, o, p[0]); - this.F.toRprBEM(buff, o+this.F.n8, p[1]); - } - - fromRprLE(buff, o) { - o = o || 0; - const x = this.F.fromRprLE(buff, o); - const y = this.F.fromRprLE(buff, o+this.F.n8); - if (this.F.isZero(x) && this.F.isZero(y)) { - return this.zero; - } - return [x, y, this.F.one]; - } - - fromRprBE(buff, o) { - o = o || 0; - const x = this.F.fromRprBE(buff, o); - const y = this.F.fromRprBE(buff, o+this.F.n8); - if (this.F.isZero(x) && this.F.isZero(y)) { - return this.zero; - } - return [x, y, this.F.one]; - } - - fromRprLEM(buff, o) { - o = o || 0; - const x = this.F.fromRprLEM(buff, o); - const y = this.F.fromRprLEM(buff, o+this.F.n8); - if (this.F.isZero(x) && this.F.isZero(y)) { - return this.zero; - } - return [x, y, this.F.one]; - } - - fromRprLEJM(buff, o) { - o = o || 0; - const x = this.F.fromRprLEM(buff, o); - const y = this.F.fromRprLEM(buff, o+this.F.n8); - const z = this.F.fromRprLEM(buff, o+this.F.n8*2); - if (this.F.isZero(x) && this.F.isZero(y)) { - return this.zero; - } - return [x, y, z]; - } - - fromRprBEM(buff, o) { - o = o || 0; - const x = this.F.fromRprBEM(buff, o); - const y = this.F.fromRprBEM(buff, o+this.F.n8); - if (this.F.isZero(x) && this.F.isZero(y)) { - return this.zero; - } - return [x, y, this.F.one]; - } - - fromRprCompressed(buff, o) { - const F = this.F; - const v = new Uint8Array(buff.buffer, o, F.n8); - if (v[0] & 0x40) return this.zero; - const P = new Array(3); - - const greatest = ((v[0] & 0x80) != 0); - v[0] = v[0] & 0x7F; - P[0] = F.fromRprBE(buff, o); - if (greatest) v[0] = v[0] | 0x80; // set back again the old value - - const x3b = F.add(F.mul(F.square(P[0]), P[0]), this.b); - P[1] = F.sqrt(x3b); - - if (P[1] === null) { - throw new Error("Invalid Point!"); - } - - const s = isGreatest(F, P[1]); - if (greatest ^ s) P[1] = F.neg(P[1]); - P[2] = F.one; - - return P; - } - - toRprCompressed(buff, o, p) { - p = this.affine(p); - const v = new Uint8Array(buff.buffer, o, this.F.n8); - if (this.isZero(p)) { - v.fill(0); - v[0] = 0x40; - return; - } - this.F.toRprBE(buff, o, p[0]); - - if (isGreatest(this.F, p[1])) { - v[0] = v[0] | 0x80; - } - } - - - fromRprUncompressed(buff, o) { - if (buff[0] & 0x40) return this.zero; - - return this.fromRprBE(buff, o); - } - - toRprUncompressed(buff, o, p) { - this.toRprBE(buff, o, p); - - if (this.isZero(p)) { - buff[o] = buff[o] | 0x40; - } - } - - -} - - - -// EXTERNAL MODULE: ./node_modules/wasmcurves/index.js -var wasmcurves = __webpack_require__(189); -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/utils_native.js -/* global BigInt */ - function stringifyBigInts(o) { - if ((typeof(o) == "bigint") || o.eq !== undefined) { + if (typeof o == "bigint" || o.eq !== undefined) { return o.toString(10); } else if (o instanceof Uint8Array) { return fromRprLE(o, 0); @@ -73715,7 +69351,7 @@ function stringifyBigInts(o) { } else if (typeof o == "object") { const res = {}; const keys = Object.keys(o); - keys.forEach( (k) => { + keys.forEach((k) => { res[k] = stringifyBigInts(o[k]); }); return res; @@ -73725,17 +69361,17 @@ function stringifyBigInts(o) { } function unstringifyBigInts(o) { - if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) { + if (typeof o == "string" && /^[0-9]+$/.test(o)) { return BigInt(o); - } else if ((typeof(o) == "string") && (/^0x[0-9a-fA-F]+$/.test(o) )) { + } else if (typeof o == "string" && /^0x[0-9a-fA-F]+$/.test(o)) { return BigInt(o); } else if (Array.isArray(o)) { return o.map(unstringifyBigInts); } else if (typeof o == "object") { - if (o===null) return null; + if (o === null) return null; const res = {}; const keys = Object.keys(o); - keys.forEach( (k) => { + keys.forEach((k) => { res[k] = unstringifyBigInts(o[k]); }); return res; @@ -73749,18 +69385,18 @@ function beBuff2int(buff) { let i = buff.length; let offset = 0; const buffV = new DataView(buff.buffer, buff.byteOffset, buff.byteLength); - while (i>0) { + while (i > 0) { if (i >= 4) { i -= 4; - res += BigInt(buffV.getUint32(i)) << BigInt(offset*8); + res += BigInt(buffV.getUint32(i)) << BigInt(offset * 8); offset += 4; } else if (i >= 2) { i -= 2; - res += BigInt(buffV.getUint16(i)) << BigInt(offset*8); + res += BigInt(buffV.getUint16(i)) << BigInt(offset * 8); offset += 2; } else { i -= 1; - res += BigInt(buffV.getUint8(i)) << BigInt(offset*8); + res += BigInt(buffV.getUint8(i)) << BigInt(offset * 8); offset += 1; } } @@ -73773,17 +69409,17 @@ function beInt2Buff(n, len) { const buffV = new DataView(buff.buffer); let o = len; while (o > 0) { - if (o-4 >= 0) { + if (o - 4 >= 0) { o -= 4; - buffV.setUint32(o, Number(r & BigInt(0xFFFFFFFF))); + buffV.setUint32(o, Number(r & BigInt(0xffffffff))); r = r >> BigInt(32); - } else if (o-2 >= 0) { + } else if (o - 2 >= 0) { o -= 2; - buffV.setUint16(o, Number(r & BigInt(0xFFFF))); + buffV.setUint16(o, Number(r & BigInt(0xffff))); r = r >> BigInt(16); } else { o -= 1; - buffV.setUint8(o, Number(r & BigInt(0xFF))); + buffV.setUint8(o, Number(r & BigInt(0xff))); r = r >> BigInt(8); } } @@ -73793,20 +69429,19 @@ function beInt2Buff(n, len) { return buff; } - function leBuff2int(buff) { let res = BigInt(0); let i = 0; const buffV = new DataView(buff.buffer, buff.byteOffset, buff.byteLength); - while (i> BigInt(32); - } else if (o+2 <= len) { - buffV.setUint16(Number(o, r & BigInt(0xFFFF)), true ); + } else if (o + 2 <= len) { + buffV.setUint16(o, Number(r & BigInt(0xffff)), true); o += 2; r = r >> BigInt(16); } else { - buffV.setUint8(Number(o, r & BigInt(0xFF)), true ); + buffV.setUint8(o, Number(r & BigInt(0xff)), true); o += 1; r = r >> BigInt(8); } @@ -73843,18 +69478,17 @@ function leInt2Buff(n, len) { return buff; } - function stringifyFElements(F, o) { - if ((typeof(o) == "bigint") || o.eq !== undefined) { + if (typeof o == "bigint" || o.eq !== undefined) { return o.toString(10); } else if (o instanceof Uint8Array) { return F.toString(F.e(o)); } else if (Array.isArray(o)) { - return o.map(stringifyFElements.bind(this,F)); + return o.map(stringifyFElements.bind(this, F)); } else if (typeof o == "object") { const res = {}; const keys = Object.keys(o); - keys.forEach( (k) => { + keys.forEach((k) => { res[k] = stringifyFElements(F, o[k]); }); return res; @@ -73863,19 +69497,18 @@ function stringifyFElements(F, o) { } } - function unstringifyFElements(F, o) { - if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) { + if (typeof o == "string" && /^[0-9]+$/.test(o)) { return F.e(o); - } else if ((typeof(o) == "string") && (/^0x[0-9a-fA-F]+$/.test(o) )) { + } else if (typeof o == "string" && /^0x[0-9a-fA-F]+$/.test(o)) { return F.e(o); } else if (Array.isArray(o)) { - return o.map(unstringifyFElements.bind(this,F)); + return o.map(unstringifyFElements.bind(this, F)); } else if (typeof o == "object") { - if (o===null) return null; + if (o === null) return null; const res = {}; const keys = Object.keys(o); - keys.forEach( (k) => { + keys.forEach((k) => { res[k] = unstringifyFElements(F, o[k]); }); return res; @@ -73884,195 +69517,93 @@ function unstringifyFElements(F, o) { } } -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/utils_bigint.js - - -function utils_bigint_stringifyBigInts(o) { - if ((typeof(o) == "bigint") || o.eq !== undefined) { - return o.toString(10); - } else if (Array.isArray(o)) { - return o.map(utils_bigint_stringifyBigInts); - } else if (typeof o == "object") { - const res = {}; - const keys = Object.keys(o); - keys.forEach( (k) => { - res[k] = utils_bigint_stringifyBigInts(o[k]); - }); - return res; - } else { - return o; - } +const _revTable = []; +for (let i = 0; i < 256; i++) { + _revTable[i] = _revSlow(i, 8); } -function utils_bigint_unstringifyBigInts(o) { - if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) { - return BigInteger(o); - } else if ((typeof(o) == "string") && (/^0x[0-9a-fA-F]+$/.test(o) )) { - return BigInteger(o); - } else if (Array.isArray(o)) { - return o.map(utils_bigint_unstringifyBigInts); - } else if (typeof o == "object") { - const res = {}; - const keys = Object.keys(o); - keys.forEach( (k) => { - res[k] = utils_bigint_unstringifyBigInts(o[k]); - }); - return res; - } else { - return o; - } -} - -function utils_bigint_beBuff2int(buff) { - let res = BigInteger.zero; - for (let i=0; i=0)) { - let c = Number(r.and(BigInteger("255"))); - buff[o] = c; - o--; - r = r.shiftRight(8); - } - if (!r.eq(BigInteger.zero)) { - throw new Error("Number does not fit in this length"); - } - return buff; -} - - -function utils_bigint_leBuff2int (buff) { - let res = BigInteger.zero; - for (let i=0; i>=1; + res = res | (a & 1); + a >>= 1; } return res; } -utils.bitReverse = function bitReverse(idx, bits) { +function bitReverse(idx, bits) { return ( - utils_revTable[idx >>> 24] | - (utils_revTable[(idx >>> 16) & 0xFF] << 8) | - (utils_revTable[(idx >>> 8) & 0xFF] << 16) | - (utils_revTable[idx & 0xFF] << 24) - ) >>> (32-bits); -}; + (_revTable[idx >>> 24] | + (_revTable[(idx >>> 16) & 0xff] << 8) | + (_revTable[(idx >>> 8) & 0xff] << 16) | + (_revTable[idx & 0xff] << 24)) >>> + (32 - bits) + ); +} +function log2(V) { + return ( + ((V & 0xffff0000) !== 0 ? ((V &= 0xffff0000), 16) : 0) | + ((V & 0xff00ff00) !== 0 ? ((V &= 0xff00ff00), 8) : 0) | + ((V & 0xf0f0f0f0) !== 0 ? ((V &= 0xf0f0f0f0), 4) : 0) | + ((V & 0xcccccccc) !== 0 ? ((V &= 0xcccccccc), 2) : 0) | + ((V & 0xaaaaaaaa) !== 0) + ); +} -utils.log2 = function log2( V ) -{ - return( ( ( V & 0xFFFF0000 ) !== 0 ? ( V &= 0xFFFF0000, 16 ) : 0 ) | ( ( V & 0xFF00FF00 ) !== 0 ? ( V &= 0xFF00FF00, 8 ) : 0 ) | ( ( V & 0xF0F0F0F0 ) !== 0 ? ( V &= 0xF0F0F0F0, 4 ) : 0 ) | ( ( V & 0xCCCCCCCC ) !== 0 ? ( V &= 0xCCCCCCCC, 2 ) : 0 ) | ( ( V & 0xAAAAAAAA ) !== 0 ) ); -}; - -utils.buffReverseBits = function buffReverseBits(buff, eSize) { - const n = buff.byteLength /eSize; - const bits = utils.log2(n); - if (n != (1 << bits)) { +function buffReverseBits(buff, eSize) { + const n = buff.byteLength / eSize; + const bits = log2(n); + if (n != 1 << bits) { throw new Error("Invalid number of pointers"); } - for (let i=0; ir) { - const tmp = buff.slice(i*eSize, (i+1)*eSize); - buff.set( buff.slice(r*eSize, (r+1)*eSize), i*eSize); - buff.set(tmp, r*eSize); + for (let i = 0; i < n; i++) { + const r = bitReverse(i, bits); + if (i > r) { + const tmp = buff.slice(i * eSize, (i + 1) * eSize); + buff.set(buff.slice(r * eSize, (r + 1) * eSize), i * eSize); + buff.set(tmp, r * eSize); } } -}; +} +function array2buffer(arr, sG) { + const buff = new Uint8Array(sG * arr.length); -utils.array2buffer = function(arr, sG) { - const buff = new Uint8Array(sG*arr.length); - - for (let i=0; i { @@ -75512,14 +70996,12 @@ function sleep(ms) { } function stringToBase64(str) { - if (threadman_process.browser) { + { return globalThis.btoa(str); - } else { - return Buffer.from(str).toString("base64"); } } -const threadSource = stringToBase64("(" + thread.toString() + ")(self)"); +const threadSource = stringToBase64("(" + "function thread(self) {\n const MAXMEM = 32767;\n let instance;\n let memory;\n\n if (self) {\n self.onmessage = function(e) {\n let data;\n if (e.data) {\n data = e.data;\n } else {\n data = e;\n }\n\n if (data[0].cmd == \"INIT\") {\n init(data[0]).then(function() {\n self.postMessage(data.result);\n });\n } else if (data[0].cmd == \"TERMINATE\") {\n self.close();\n } else {\n const res = runTask(data);\n self.postMessage(res);\n }\n };\n }\n\n async function init(data) {\n const code = new Uint8Array(data.code);\n const wasmModule = await WebAssembly.compile(code);\n memory = new WebAssembly.Memory({initial:data.init, maximum: MAXMEM});\n\n instance = await WebAssembly.instantiate(wasmModule, {\n env: {\n \"memory\": memory\n }\n });\n }\n\n\n\n function alloc(length) {\n const u32 = new Uint32Array(memory.buffer, 0, 1);\n while (u32[0] & 3) u32[0]++; // Return always aligned pointers\n const res = u32[0];\n u32[0] += length;\n if (u32[0] + length > memory.buffer.byteLength) {\n const currentPages = memory.buffer.byteLength / 0x10000;\n let requiredPages = Math.floor((u32[0] + length) / 0x10000)+1;\n if (requiredPages>MAXMEM) requiredPages=MAXMEM;\n memory.grow(requiredPages-currentPages);\n }\n return res;\n }\n\n function allocBuffer(buffer) {\n const p = alloc(buffer.byteLength);\n setBuffer(p, buffer);\n return p;\n }\n\n function getBuffer(pointer, length) {\n const u8 = new Uint8Array(memory.buffer);\n return new Uint8Array(u8.buffer, u8.byteOffset + pointer, length);\n }\n\n function setBuffer(pointer, buffer) {\n const u8 = new Uint8Array(memory.buffer);\n u8.set(new Uint8Array(buffer), pointer);\n }\n\n function runTask(task) {\n if (task[0].cmd == \"INIT\") {\n return init(task[0]);\n }\n const ctx = {\n vars: [],\n out: []\n };\n const u32a = new Uint32Array(memory.buffer, 0, 1);\n const oldAlloc = u32a[0];\n for (let i=0; i. +*/ + +function toNumber(n) { + return BigInt(n); +} + +function isNegative(n) { + return n < 0n; +} + +function isZero(n) { + return n === 0n; +} + +function bitLength(n) { + if (isNegative(n)) { + return n.toString(2).length - 1; // discard the - sign + } else { + return n.toString(2).length; + } +} + +function u32(n) { + const b = []; + const v = toNumber(n); + b.push(Number(v & 0xFFn)); + b.push(Number(v >> 8n & 0xFFn)); + b.push(Number(v >> 16n & 0xFFn)); + b.push(Number(v >> 24n & 0xFFn)); + return b; +} + +function toUTF8Array(str) { + var utf8 = []; + for (var i=0; i < str.length; i++) { + var charcode = str.charCodeAt(i); + if (charcode < 0x80) utf8.push(charcode); + else if (charcode < 0x800) { + utf8.push(0xc0 | (charcode >> 6), + 0x80 | (charcode & 0x3f)); + } + else if (charcode < 0xd800 || charcode >= 0xe000) { + utf8.push(0xe0 | (charcode >> 12), + 0x80 | ((charcode>>6) & 0x3f), + 0x80 | (charcode & 0x3f)); + } + // surrogate pair + else { + i++; + // UTF-16 encodes 0x10000-0x10FFFF by + // subtracting 0x10000 and splitting the + // 20 bits of 0x0-0xFFFFF into two halves + charcode = 0x10000 + (((charcode & 0x3ff)<<10) + | (str.charCodeAt(i) & 0x3ff)); + utf8.push(0xf0 | (charcode >>18), + 0x80 | ((charcode>>12) & 0x3f), + 0x80 | ((charcode>>6) & 0x3f), + 0x80 | (charcode & 0x3f)); + } + } + return utf8; +} + +function string(str) { + const bytes = toUTF8Array(str); + return [ ...varuint32(bytes.length), ...bytes ]; +} + +function varuint(n) { + const code = []; + let v = toNumber(n); + if (isNegative(v)) throw new Error("Number cannot be negative"); + while (!isZero(v)) { + code.push(Number(v & 0x7Fn)); + v = v >> 7n; + } + if (code.length==0) code.push(0); + for (let i=0; i 0xFFFFFFFFn) throw new Error("Number too big"); + if (v > 0x7FFFFFFFn) v = v - 0x100000000n; + // bigInt("-80000000", 16) as base10 + if (v < -2147483648n) throw new Error("Number too small"); + return varint(v); +} + +function varint64(n) { + let v = toNumber(n); + if (v > 0xFFFFFFFFFFFFFFFFn) throw new Error("Number too big"); + if (v > 0x7FFFFFFFFFFFFFFFn) v = v - 0x10000000000000000n; + // bigInt("-8000000000000000", 16) as base10 + if (v < -9223372036854775808n) throw new Error("Number too small"); + return varint(v); +} + +function varuint32(n) { + let v = toNumber(n); + if (v > 0xFFFFFFFFn) throw new Error("Number too big"); + return varuint(v); +} + +function toHexString(byteArray) { + return Array.from(byteArray, function(byte) { + return ("0" + (byte & 0xFF).toString(16)).slice(-2); + }).join(""); +} + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ -// EXTERNAL MODULE: ./node_modules/wasmbuilder/index.js -var wasmbuilder = __webpack_require__(4400); -;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/bn128.js +class CodeBuilder { + constructor(func) { + this.func = func; + this.functionName = func.functionName; + this.module = func.module; + } + + setLocal(localName, valCode) { + const idx = this.func.localIdxByName[localName]; + if (idx === undefined) + throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); + return [...valCode, 0x21, ...varuint32( idx )]; + } + + teeLocal(localName, valCode) { + const idx = this.func.localIdxByName[localName]; + if (idx === undefined) + throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); + return [...valCode, 0x22, ...varuint32( idx )]; + } + + getLocal(localName) { + const idx = this.func.localIdxByName[localName]; + if (idx === undefined) + throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); + return [0x20, ...varuint32( idx )]; + } + + i64_load8_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 0 : _align; // 8 bits alignment by default + return [...idxCode, 0x30, align, ...varuint32(offset)]; + } + + i64_load8_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 0 : _align; // 8 bits alignment by default + return [...idxCode, 0x31, align, ...varuint32(offset)]; + } + + i64_load16_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 1 : _align; // 16 bits alignment by default + return [...idxCode, 0x32, align, ...varuint32(offset)]; + } + + i64_load16_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 1 : _align; // 16 bits alignment by default + return [...idxCode, 0x33, align, ...varuint32(offset)]; + } + + i64_load32_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default + return [...idxCode, 0x34, align, ...varuint32(offset)]; + } + + i64_load32_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default + return [...idxCode, 0x35, align, ...varuint32(offset)]; + } + + i64_load(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 3 : _align; // 64 bits alignment by default + return [...idxCode, 0x29, align, ...varuint32(offset)]; + } + i64_store(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 3; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 3; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x37, align, ...varuint32(offset)]; + } + + i64_store32(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 2; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 2; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3e, align, ...varuint32(offset)]; + } + i64_store16(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 1; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 1; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3d, align, ...varuint32(offset)]; + } + + + i64_store8(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 0; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 0; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3c, align, ...varuint32(offset)]; + } + + i32_load8_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default + return [...idxCode, 0x2c, align, ...varuint32(offset)]; + } + + i32_load8_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default + return [...idxCode, 0x2d, align, ...varuint32(offset)]; + } + + i32_load16_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default + return [...idxCode, 0x2e, align, ...varuint32(offset)]; + } + + i32_load16_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default + return [...idxCode, 0x2f, align, ...varuint32(offset)]; + } + + i32_load(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default + return [...idxCode, 0x28, align, ...varuint32(offset)]; + } + + i32_store(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 2; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 2; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x36, align, ...varuint32(offset)]; + } + + + i32_store16(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 1; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 1; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3b, align, ...varuint32(offset)]; + } + + i32_store8(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 0; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 0; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3a, align, ...varuint32(offset)]; + } + + call(fnName, ...args) { + const idx = this.module.functionIdxByName[fnName]; + if (idx === undefined) + throw new Error(`Function not defined: Function: ${fnName}`); + return [...[].concat(...args), 0x10, ...varuint32(idx)]; + } + + call_indirect(fnIdx, ...args) { + return [...[].concat(...args), ...fnIdx, 0x11, 0, 0]; + } + + if(condCode, thenCode, elseCode) { + if (elseCode) { + return [...condCode, 0x04, 0x40, ...thenCode, 0x05, ...elseCode, 0x0b]; + } else { + return [...condCode, 0x04, 0x40, ...thenCode, 0x0b]; + } + } + + block(bCode) { return [0x02, 0x40, ...bCode, 0x0b]; } + loop(...args) { + return [0x03, 0x40, ...[].concat(...[...args]), 0x0b]; + } + br_if(relPath, condCode) { return [...condCode, 0x0d, ...varuint32(relPath)]; } + br(relPath) { return [0x0c, ...varuint32(relPath)]; } + ret(rCode) { return [...rCode, 0x0f]; } + drop(dCode) { return [...dCode, 0x1a]; } + + i64_const(num) { return [0x42, ...varint64(num)]; } + i32_const(num) { return [0x41, ...varint32(num)]; } + + + i64_eqz(opcode) { return [...opcode, 0x50]; } + i64_eq(op1code, op2code) { return [...op1code, ...op2code, 0x51]; } + i64_ne(op1code, op2code) { return [...op1code, ...op2code, 0x52]; } + i64_lt_s(op1code, op2code) { return [...op1code, ...op2code, 0x53]; } + i64_lt_u(op1code, op2code) { return [...op1code, ...op2code, 0x54]; } + i64_gt_s(op1code, op2code) { return [...op1code, ...op2code, 0x55]; } + i64_gt_u(op1code, op2code) { return [...op1code, ...op2code, 0x56]; } + i64_le_s(op1code, op2code) { return [...op1code, ...op2code, 0x57]; } + i64_le_u(op1code, op2code) { return [...op1code, ...op2code, 0x58]; } + i64_ge_s(op1code, op2code) { return [...op1code, ...op2code, 0x59]; } + i64_ge_u(op1code, op2code) { return [...op1code, ...op2code, 0x5a]; } + i64_add(op1code, op2code) { return [...op1code, ...op2code, 0x7c]; } + i64_sub(op1code, op2code) { return [...op1code, ...op2code, 0x7d]; } + i64_mul(op1code, op2code) { return [...op1code, ...op2code, 0x7e]; } + i64_div_s(op1code, op2code) { return [...op1code, ...op2code, 0x7f]; } + i64_div_u(op1code, op2code) { return [...op1code, ...op2code, 0x80]; } + i64_rem_s(op1code, op2code) { return [...op1code, ...op2code, 0x81]; } + i64_rem_u(op1code, op2code) { return [...op1code, ...op2code, 0x82]; } + i64_and(op1code, op2code) { return [...op1code, ...op2code, 0x83]; } + i64_or(op1code, op2code) { return [...op1code, ...op2code, 0x84]; } + i64_xor(op1code, op2code) { return [...op1code, ...op2code, 0x85]; } + i64_shl(op1code, op2code) { return [...op1code, ...op2code, 0x86]; } + i64_shr_s(op1code, op2code) { return [...op1code, ...op2code, 0x87]; } + i64_shr_u(op1code, op2code) { return [...op1code, ...op2code, 0x88]; } + i64_extend_i32_s(op1code) { return [...op1code, 0xac]; } + i64_extend_i32_u(op1code) { return [...op1code, 0xad]; } + i64_clz(op1code) { return [...op1code, 0x79]; } + i64_ctz(op1code) { return [...op1code, 0x7a]; } + + i32_eqz(op1code) { return [...op1code, 0x45]; } + i32_eq(op1code, op2code) { return [...op1code, ...op2code, 0x46]; } + i32_ne(op1code, op2code) { return [...op1code, ...op2code, 0x47]; } + i32_lt_s(op1code, op2code) { return [...op1code, ...op2code, 0x48]; } + i32_lt_u(op1code, op2code) { return [...op1code, ...op2code, 0x49]; } + i32_gt_s(op1code, op2code) { return [...op1code, ...op2code, 0x4a]; } + i32_gt_u(op1code, op2code) { return [...op1code, ...op2code, 0x4b]; } + i32_le_s(op1code, op2code) { return [...op1code, ...op2code, 0x4c]; } + i32_le_u(op1code, op2code) { return [...op1code, ...op2code, 0x4d]; } + i32_ge_s(op1code, op2code) { return [...op1code, ...op2code, 0x4e]; } + i32_ge_u(op1code, op2code) { return [...op1code, ...op2code, 0x4f]; } + i32_add(op1code, op2code) { return [...op1code, ...op2code, 0x6a]; } + i32_sub(op1code, op2code) { return [...op1code, ...op2code, 0x6b]; } + i32_mul(op1code, op2code) { return [...op1code, ...op2code, 0x6c]; } + i32_div_s(op1code, op2code) { return [...op1code, ...op2code, 0x6d]; } + i32_div_u(op1code, op2code) { return [...op1code, ...op2code, 0x6e]; } + i32_rem_s(op1code, op2code) { return [...op1code, ...op2code, 0x6f]; } + i32_rem_u(op1code, op2code) { return [...op1code, ...op2code, 0x70]; } + i32_and(op1code, op2code) { return [...op1code, ...op2code, 0x71]; } + i32_or(op1code, op2code) { return [...op1code, ...op2code, 0x72]; } + i32_xor(op1code, op2code) { return [...op1code, ...op2code, 0x73]; } + i32_shl(op1code, op2code) { return [...op1code, ...op2code, 0x74]; } + i32_shr_s(op1code, op2code) { return [...op1code, ...op2code, 0x75]; } + i32_shr_u(op1code, op2code) { return [...op1code, ...op2code, 0x76]; } + i32_rotl(op1code, op2code) { return [...op1code, ...op2code, 0x77]; } + i32_rotr(op1code, op2code) { return [...op1code, ...op2code, 0x78]; } + i32_wrap_i64(op1code) { return [...op1code, 0xa7]; } + i32_clz(op1code) { return [...op1code, 0x67]; } + i32_ctz(op1code) { return [...op1code, 0x68]; } + + unreachable() { return [ 0x0 ]; } + + current_memory() { return [ 0x3f, 0]; } + + comment() { return []; } +} + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ + + +const typeCodes = { + "i32": 0x7f, + "i64": 0x7e, + "f32": 0x7d, + "f64": 0x7c, + "anyfunc": 0x70, + "func": 0x60, + "emptyblock": 0x40 +}; + + +class FunctionBuilder { + + constructor (module, fnName, fnType, moduleName, fieldName) { + if (fnType == "import") { + this.fnType = "import"; + this.moduleName = moduleName; + this.fieldName = fieldName; + } else if (fnType == "internal") { + this.fnType = "internal"; + } else { + throw new Error("Invalid function fnType: " + fnType); + } + this.module = module; + this.fnName = fnName; + this.params = []; + this.locals = []; + this.localIdxByName = {}; + this.code = []; + this.returnType = null; + this.nextLocal =0; + } + + addParam(paramName, paramType) { + if (this.localIdxByName[paramName]) + throw new Error(`param already exists. Function: ${this.fnName}, Param: ${paramName} `); + const idx = this.nextLocal++; + this.localIdxByName[paramName] = idx; + this.params.push({ + type: paramType + }); + } + + addLocal(localName, localType, _length) { + const length = _length || 1; + if (this.localIdxByName[localName]) + throw new Error(`local already exists. Function: ${this.fnName}, Param: ${localName} `); + const idx = this.nextLocal++; + this.localIdxByName[localName] = idx; + this.locals.push({ + type: localType, + length: length + }); + } + + setReturnType(returnType) { + if (this.returnType) + throw new Error(`returnType already defined. Function: ${this.fnName}`); + this.returnType = returnType; + } + + getSignature() { + const params = [...varuint32(this.params.length), ...this.params.map((p) => typeCodes[p.type])]; + const returns = this.returnType ? [0x01, typeCodes[this.returnType]] : [0]; + return [0x60, ...params, ...returns]; + } + + getBody() { + const locals = this.locals.map((l) => [ + ...varuint32(l.length), + typeCodes[l.type] + ]); + + const body = [ + ...varuint32(this.locals.length), + ...[].concat(...locals), + ...this.code, + 0x0b + ]; + return [ + ...varuint32(body.length), + ...body + ]; + } + + addCode(...code) { + this.code.push(...[].concat(...[...code])); + } + + getCodeBuilder() { + return new CodeBuilder(this); + } +} + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ + + +class ModuleBuilder { + + constructor() { + this.functions = []; + this.functionIdxByName = {}; + this.nImportFunctions = 0; + this.nInternalFunctions =0; + this.memory = { + pagesSize: 1, + moduleName: "env", + fieldName: "memory" + }; + this.free = 8; + this.datas = []; + this.modules = {}; + this.exports = []; + this.functionsTable = []; + } + + build() { + this._setSignatures(); + return new Uint8Array([ + ...u32(0x6d736100), + ...u32(1), + ...this._buildType(), + ...this._buildImport(), + ...this._buildFunctionDeclarations(), + ...this._buildFunctionsTable(), + ...this._buildExports(), + ...this._buildElements(), + ...this._buildCode(), + ...this._buildData() + ]); + } + + addFunction(fnName) { + if (typeof(this.functionIdxByName[fnName]) !== "undefined") + throw new Error(`Function already defined: ${fnName}`); + + const idx = this.functions.length; + this.functionIdxByName[fnName] = idx; + + this.functions.push(new FunctionBuilder(this, fnName, "internal")); + + this.nInternalFunctions++; + return this.functions[idx]; + } + + addIimportFunction(fnName, moduleName, _fieldName) { + if (typeof(this.functionIdxByName[fnName]) !== "undefined") + throw new Error(`Function already defined: ${fnName}`); + + if ( (this.functions.length>0) + &&(this.functions[this.functions.length-1].type == "internal")) + throw new Error(`Import functions must be declared before internal: ${fnName}`); + + let fieldName = _fieldName || fnName; + + const idx = this.functions.length; + this.functionIdxByName[fnName] = idx; + + this.functions.push(new FunctionBuilder(this, fnName, "import", moduleName, fieldName)); + + this.nImportFunctions ++; + return this.functions[idx]; + } + + setMemory(pagesSize, moduleName, fieldName) { + this.memory = { + pagesSize: pagesSize, + moduleName: moduleName || "env", + fieldName: fieldName || "memory" + }; + } + + exportFunction(fnName, _exportName) { + const exportName = _exportName || fnName; + if (typeof(this.functionIdxByName[fnName]) === "undefined") + throw new Error(`Function not defined: ${fnName}`); + const idx = this.functionIdxByName[fnName]; + if (exportName != fnName) { + this.functionIdxByName[exportName] = idx; + } + this.exports.push({ + exportName: exportName, + idx: idx + }); + } + + addFunctionToTable(fnName) { + const idx = this.functionIdxByName[fnName]; + this.functionsTable.push(idx); + } + + addData(offset, bytes) { + this.datas.push({ + offset: offset, + bytes: bytes + }); + } + + alloc(a, b) { + let size; + let bytes; + if ((Array.isArray(a) || ArrayBuffer.isView(a)) && (typeof(b) === "undefined")) { + size = a.length; + bytes = a; + } else { + size = a; + bytes = b; + } + size = (((size-1)>>3) +1)<<3; // Align to 64 bits. + const p = this.free; + this.free += size; + if (bytes) { + this.addData(p, bytes); + } + return p; + } + + allocString(s) { + const encoder = new globalThis.TextEncoder(); + const uint8array = encoder.encode(s); + return this.alloc([...uint8array, 0]); + } + + _setSignatures() { + this.signatures = []; + const signatureIdxByName = {}; + if (this.functionsTable.length>0) { + const signature = this.functions[this.functionsTable[0]].getSignature(); + const signatureName = "s_"+toHexString(signature); + signatureIdxByName[signatureName] = 0; + this.signatures.push(signature); + } + for (let i=0; i= 0) { - curve = await bn128_buildBn128(singleThread, plugins); + curve = await buildBn128(singleThread, plugins); } else if (["BLS12381"].indexOf(normName) >= 0) { - curve = await bls12381_buildBls12381(singleThread, plugins); + curve = await buildBls12381(singleThread, plugins); } else { throw new Error(`Curve not supported: ${name}`); } @@ -77145,29 +73498,8 @@ async function curves_getCurveFromName(name, singleThread, plugins) { } -;// CONCATENATED MODULE: ./node_modules/ffjavascript/main.js - - -const main_Scalar=scalar_namespaceObject; - - - - - - - - - - - - - - -const main_utils = utils_namespaceObject; - - - - +const browser_esm_Scalar=_Scalar; +const utils = _utils; @@ -77317,7 +73649,7 @@ var node_modules_blake2b = __webpack_require__(2206); // EXTERNAL MODULE: ./node_modules/blake-hash/js.js var js = __webpack_require__(654); ;// CONCATENATED MODULE: ./node_modules/circomlibjs/src/pedersen_hash.js -/* provided dependency */ var pedersen_hash_Buffer = __webpack_require__(8287)["Buffer"]; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; @@ -77343,7 +73675,7 @@ class PedersenHash { if (type == "blake") { return createBlakeHash("blake256").update(S).digest(); } else if (type == "blake2b") { - return pedersen_hash_Buffer.from(blake2b(32).update(pedersen_hash_Buffer.from(S)).digest()); + return Buffer.from(blake2b(32).update(Buffer.from(S)).digest()); } } @@ -102785,7 +99117,6 @@ var sha3_default = /*#__PURE__*/__webpack_require__.n(sha3); const version = "logger/5.7.0"; //# sourceMappingURL=_version.js.map ;// CONCATENATED MODULE: ./node_modules/@ethersproject/logger/lib.esm/index.js -/* provided dependency */ var console = __webpack_require__(6763); let _permanentCensorErrors = false; let _censorErrors = false; @@ -103822,7 +100153,7 @@ const mimcsponge_SEED = "mimcsponge"; const mimcsponge_NROUNDS = 220; async function mimcsponge_buildMimcSponge() { - const bn128 = await curves_getCurveFromName("bn128", true); + const bn128 = await browser_esm_getCurveFromName("bn128", true); return new MimcSponge(bn128.Fr); } @@ -103836,7 +100167,7 @@ class MimcSponge { const F = this.F; if (typeof seed === "undefined") seed = mimcsponge_SEED; const c = keccak256(toUtf8Bytes(seed+"_iv")); - const cn = main_Scalar.e(c); + const cn = browser_esm_Scalar.e(c); const iv = cn.mod(F.p); return iv; }; @@ -104872,7 +101203,7 @@ const mimcsponge_gencontract_abi = [ -const { unstringifyBigInts: poseidon_gencontract_unstringifyBigInts } = main_utils; +const { unstringifyBigInts: poseidon_gencontract_unstringifyBigInts } = utils; @@ -105689,17 +102020,18 @@ class Mimc { } const mimc = new Mimc(); +// EXTERNAL MODULE: ./node_modules/crypto-browserify/index.js +var crypto_browserify = __webpack_require__(1565); // EXTERNAL MODULE: ./node_modules/bn.js/lib/bn.js var bn = __webpack_require__(9404); ;// CONCATENATED MODULE: ./src/utils.ts -/* provided dependency */ var utils_process = __webpack_require__(5606); BigInt.prototype.toJSON = function() { return this.toString(); }; -const isNode = !utils_process.browser && typeof globalThis.window === "undefined"; +const isNode = !process.browser && typeof globalThis.window === "undefined"; const utils_crypto = isNode ? crypto_browserify.webcrypto : globalThis.crypto; const chunk = (arr, size) => [...Array(Math.ceil(arr.length / size))].map((_, i) => arr.slice(size * i, size + size * i)); function utils_sleep(ms) { @@ -105762,7 +102094,7 @@ function bnToBytes(bigint) { function leBuff2Int(bytes) { return new BN(bytes, 16, "le"); } -function src_utils_leInt2Buff(bigint) { +function utils_leInt2Buff(bigint) { return Uint8Array.from(new BN(bigint).toArray("le", 31)); } function toFixedHex(numberish, length = 32) { diff --git a/dist/networkConfig.d.ts b/dist/networkConfig.d.ts index 51b4503..a8b375d 100644 --- a/dist/networkConfig.d.ts +++ b/dist/networkConfig.d.ts @@ -67,8 +67,6 @@ export type Config = { registryContract?: string; aggregatorContract?: string; reverseRecordsContract?: string; - gasPriceOracleContract?: string; - gasStationApi?: string; ovmGasPriceOracleContract?: string; tornadoSubgraph: string; registrySubgraph?: string; @@ -90,7 +88,7 @@ export type networkConfig = { [key in NetIdType]: Config; }; export declare const defaultConfig: networkConfig; -export declare const enabledChains: number[]; +export declare const enabledChains: NetIdType[]; /** * Custom config object to extend default config * diff --git a/dist/providers.d.ts b/dist/providers.d.ts index d85ddd1..ee5bb88 100644 --- a/dist/providers.d.ts +++ b/dist/providers.d.ts @@ -1,9 +1,6 @@ -/// -/// -/// import type { EventEmitter } from 'stream'; import type { RequestOptions } from 'http'; -import { JsonRpcApiProvider, JsonRpcProvider, Wallet, FetchGetUrlFunc, Provider, SigningKey, TransactionRequest, JsonRpcSigner, BrowserProvider, Networkish, Eip1193Provider, VoidSigner, FetchUrlFeeDataNetworkPlugin } from 'ethers'; +import { JsonRpcApiProvider, JsonRpcProvider, Wallet, FetchGetUrlFunc, Provider, SigningKey, TransactionRequest, JsonRpcSigner, BrowserProvider, Networkish, Eip1193Provider, VoidSigner } from 'ethers'; import type { RequestInfo, RequestInit, Response, HeadersInit } from 'node-fetch'; import type { Config, NetIdType } from './networkConfig'; declare global { @@ -36,10 +33,7 @@ export declare function fetchData(url: string, options?: fetchDataOptions): Prom export declare const fetchGetUrlFunc: (options?: fetchDataOptions) => FetchGetUrlFunc; export type getProviderOptions = fetchDataOptions & { pollingInterval?: number; - gasPriceOracle?: string; - gasStationApi?: string; }; -export declare function getGasOraclePlugin(networkKey: string, fetchOptions?: getProviderOptions): FetchUrlFeeDataNetworkPlugin; export declare function getProvider(rpcUrl: string, fetchOptions?: getProviderOptions): Promise; export declare function getProviderWithNetId(netId: NetIdType, rpcUrl: string, config: Config, fetchOptions?: getProviderOptions): JsonRpcProvider; export declare const populateTransaction: (signer: TornadoWallet | TornadoVoidSigner | TornadoRpcSigner, tx: TransactionRequest) => Promise; diff --git a/dist/typechain/factories/index.d.ts b/dist/typechain/factories/index.d.ts index ab90b86..1283210 100644 --- a/dist/typechain/factories/index.d.ts +++ b/dist/typechain/factories/index.d.ts @@ -1,6 +1,5 @@ export { ENS__factory } from "./ENS__factory"; export { ERC20__factory } from "./ERC20__factory"; -export { GasPriceOracle__factory } from "./GasPriceOracle__factory"; export { Multicall__factory } from "./Multicall__factory"; export { OffchainOracle__factory } from "./OffchainOracle__factory"; export { OvmGasPriceOracle__factory } from "./OvmGasPriceOracle__factory"; diff --git a/dist/typechain/index.d.ts b/dist/typechain/index.d.ts index 7f5f66e..5190643 100644 --- a/dist/typechain/index.d.ts +++ b/dist/typechain/index.d.ts @@ -1,6 +1,5 @@ export type { ENS } from "./ENS"; export type { ERC20 } from "./ERC20"; -export type { GasPriceOracle } from "./GasPriceOracle"; export type { Multicall } from "./Multicall"; export type { OffchainOracle } from "./OffchainOracle"; export type { OvmGasPriceOracle } from "./OvmGasPriceOracle"; @@ -8,7 +7,6 @@ export type { ReverseRecords } from "./ReverseRecords"; export * as factories from "./factories"; export { ENS__factory } from "./factories/ENS__factory"; export { ERC20__factory } from "./factories/ERC20__factory"; -export { GasPriceOracle__factory } from "./factories/GasPriceOracle__factory"; export { Multicall__factory } from "./factories/Multicall__factory"; export { OffchainOracle__factory } from "./factories/OffchainOracle__factory"; export { OvmGasPriceOracle__factory } from "./factories/OvmGasPriceOracle__factory"; diff --git a/dist/utils.d.ts b/dist/utils.d.ts index 8ffe743..f373618 100644 --- a/dist/utils.d.ts +++ b/dist/utils.d.ts @@ -1,5 +1,3 @@ -/// -/// import { webcrypto } from 'crypto'; import BN from 'bn.js'; import type { BigNumberish } from 'ethers'; diff --git a/package.json b/package.json index 36f94d2..490a02e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@tornado/core", - "version": "1.0.2", + "version": "1.0.3", "description": "An SDK for building applications on top of Privacy Pools", "main": "./dist/index.js", "module": "./dist/index.mjs", @@ -31,46 +31,44 @@ "yarn.lock" ], "dependencies": { - "@metamask/eth-sig-util": "^7.0.1", - "@tornado/contracts": "^1.0.0", - "@tornado/fixed-merkle-tree": "^0.7.3", - "@tornado/snarkjs": "^0.1.20", - "@tornado/websnark": "^0.0.4", - "ajv": "^8.12.0", + "@metamask/eth-sig-util": "^7.0.3", + "@tornado/contracts": "git+https://codeberg.org/tornadocash/tornado-contracts.git#6741664a898c1654e742459a2c20e52e4bc104fa", + "@tornado/fixed-merkle-tree": "git+https://codeberg.org/tornadocash/fixed-merkle-tree.git#5c3fca4cb11255760ad5f4fd95d7c6eb45c1fc99", + "@tornado/snarkjs": "git+https://codeberg.org/tornadocash/snarkjs.git#d3915a760c437cde7bd317f9ea2c627954900656", + "@tornado/websnark": "git+https://codeberg.org/tornadocash/websnark.git#b0c9fce5359ceba55167a2ad01a29d1e137843ec", + "ajv": "^8.17.1", "bn.js": "^5.2.1", "circomlibjs": "0.1.7", "cross-fetch": "^4.0.0", - "ethers": "^6.4.0", + "ethers": "^6.13.2", "ffjavascript": "0.2.48", "fflate": "^0.8.2" }, - "optionalDependencies": {}, "devDependencies": { - "@rollup/plugin-commonjs": "^25.0.7", + "@rollup/plugin-commonjs": "^26.0.1", "@rollup/plugin-json": "^6.1.0", "@rollup/plugin-node-resolve": "^15.2.3", "@typechain/ethers-v6": "^0.5.1", - "@types/bn.js": "^5.1.5", + "@types/bn.js": "^5.1.6", "@types/circomlibjs": "^0.1.6", - "@types/node": "^20.12.5", + "@types/node": "^22.5.5", "@types/node-fetch": "^2.6.11", - "@typescript-eslint/eslint-plugin": "^7.6.0", - "@typescript-eslint/parser": "^7.6.0", - "esbuild": "^0.20.2", - "esbuild-loader": "^4.1.0", - "eslint": "^8.57.0", + "@typescript-eslint/eslint-plugin": "8.6.0", + "@typescript-eslint/parser": "^8.6.0", + "esbuild-loader": "^4.2.2", + "eslint": "8.57.0", "eslint-config-prettier": "^9.1.0", - "eslint-import-resolver-typescript": "^3.6.1", - "eslint-plugin-import": "^2.29.1", - "eslint-plugin-prettier": "^5.1.3", - "node-polyfill-webpack-plugin": "^3.0.0", - "prettier": "^3.2.5", - "rollup": "^4.14.1", + "eslint-import-resolver-typescript": "^3.6.3", + "eslint-plugin-import": "^2.30.0", + "eslint-plugin-prettier": "^5.2.1", + "node-polyfill-webpack-plugin": "^4.0.0", + "prettier": "^3.3.3", + "rollup": "^4.22.0", "rollup-plugin-esbuild": "^6.1.1", "tsc": "^2.0.4", "typechain": "^8.3.2", - "typescript": "^5.4.4", - "webpack": "^5.91.0", + "typescript": "^5.6.2", + "webpack": "^5.94.0", "webpack-cli": "^5.1.4" } } diff --git a/rollup.config.mjs b/rollup.config.mjs index a8f7b5f..f240b1a 100644 --- a/rollup.config.mjs +++ b/rollup.config.mjs @@ -7,7 +7,7 @@ import { readFileSync } from 'fs'; const pkgJson = JSON.parse(readFileSync("./package.json")); const external = Object.keys(pkgJson.dependencies).concat( - Object.keys(pkgJson.optionalDependencies), + Object.keys(pkgJson.optionalDependencies || {}), [ 'http-proxy-agent', 'https-proxy-agent', diff --git a/src/abi/GasPriceOracle.json b/src/abi/GasPriceOracle.json deleted file mode 100644 index 2ef8f09..0000000 --- a/src/abi/GasPriceOracle.json +++ /dev/null @@ -1,189 +0,0 @@ -[ - { - "inputs": [], - "stateMutability": "nonpayable", - "type": "constructor" - }, - { - "inputs": [], - "name": "GAS_UNIT", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint32", - "name": "_derivationThresold", - "type": "uint32" - } - ], - "name": "changeDerivationThresold", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint32", - "name": "_gasUnit", - "type": "uint32" - } - ], - "name": "changeGasUnit", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint32", - "name": "_heartbeat", - "type": "uint32" - } - ], - "name": "changeHeartbeat", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "_owner", - "type": "address" - } - ], - "name": "changeOwnership", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "derivationThresold", - "outputs": [ - { - "internalType": "uint32", - "name": "", - "type": "uint32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "gasPrice", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "heartbeat", - "outputs": [ - { - "internalType": "uint32", - "name": "", - "type": "uint32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "maxFeePerGas", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "maxPriorityFeePerGas", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "owner", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "pastGasPrice", - "outputs": [ - { - "internalType": "uint32", - "name": "", - "type": "uint32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint32", - "name": "_gasPrice", - "type": "uint32" - } - ], - "name": "setGasPrice", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "timestamp", - "outputs": [ - { - "internalType": "uint32", - "name": "", - "type": "uint32" - } - ], - "stateMutability": "view", - "type": "function" - } -] \ No newline at end of file diff --git a/src/events/base.ts b/src/events/base.ts index 507f140..aa34158 100644 --- a/src/events/base.ts +++ b/src/events/base.ts @@ -19,6 +19,7 @@ import { fetchDataOptions } from '../providers'; import type { NetIdType } from '../networkConfig'; import type { BaseEvents, + CachedEvents, MinimalEvents, DepositsEvents, WithdrawalsEvents, @@ -77,8 +78,6 @@ export class BaseEventsService { batchEventsService: BatchEventsService; fetchDataOptions?: fetchDataOptions; - saveEventsPromise?: Promise; - constructor({ netId, provider, @@ -153,14 +152,18 @@ export class BaseEventsService { }; } - async getEventsFromCache(): Promise> { + /** + * Events from remote cache (Either from local cache, CDN, or from IPFS) + */ + async getEventsFromCache(): Promise> { return { events: [], lastBlock: null, + fromCache: true, }; } - async getSavedEvents(): Promise> { + async getSavedEvents(): Promise | CachedEvents> { let cachedEvents = await this.getEventsFromDB(); if (!cachedEvents || !cachedEvents.events.length) { @@ -317,7 +320,10 @@ export class BaseEventsService { this.validateEvents({ events: allEvents, lastBlock }); - this.saveEventsPromise = this.saveEvents({ events: allEvents, lastBlock }); + // If the events are loaded from cache or we have found new events, save them + if ((savedEvents as CachedEvents).fromCache || newEvents.events.length) { + await this.saveEvents({ events: allEvents, lastBlock }); + } return { events: allEvents, diff --git a/src/events/types.ts b/src/events/types.ts index 3a2ed69..a8be918 100644 --- a/src/events/types.ts +++ b/src/events/types.ts @@ -5,6 +5,10 @@ export interface BaseEvents { lastBlock: number | null; } +export interface CachedEvents extends BaseEvents { + fromCache: boolean; +} + export interface BaseGraphEvents { events: T[]; lastSyncBlock: number; diff --git a/src/networkConfig.ts b/src/networkConfig.ts index 2cdc4b4..a064e23 100644 --- a/src/networkConfig.ts +++ b/src/networkConfig.ts @@ -78,8 +78,6 @@ export type Config = { registryContract?: string; aggregatorContract?: string; reverseRecordsContract?: string; - gasPriceOracleContract?: string; - gasStationApi?: string; ovmGasPriceOracleContract?: string; tornadoSubgraph: string; registrySubgraph?: string; @@ -314,7 +312,6 @@ export const defaultConfig: networkConfig = { routerContract: '0x0D5550d52428E7e3175bfc9550207e4ad3859b17', echoContract: '0xa75BF2815618872f155b7C4B0C81bF990f5245E4', offchainOracleContract: '0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8', - gasPriceOracleContract: '0xF81A8D8D3581985D3969fe53bFA67074aDFa8F3C', tornadoSubgraph: 'tornadocash/matic-tornado-subgraph', subgraphs: { tornado, diff --git a/src/providers.ts b/src/providers.ts index e409c98..5c54ecf 100644 --- a/src/providers.ts +++ b/src/providers.ts @@ -17,17 +17,15 @@ import { Eip1193Provider, VoidSigner, Network, - parseUnits, - FetchUrlFeeDataNetworkPlugin, FeeData, EnsPlugin, GasCostPlugin, } from 'ethers'; import type { RequestInfo, RequestInit, Response, HeadersInit } from 'node-fetch'; -import { GasPriceOracle, GasPriceOracle__factory, Multicall, Multicall__factory } from './typechain'; +// Temporary workaround until @types/node-fetch is compatible with @types/node +import type { AbortSignal as FetchAbortSignal } from 'node-fetch/externals'; import { isNode, sleep } from './utils'; import type { Config, NetIdType } from './networkConfig'; -import { multicall } from './multicall'; declare global { interface Window { @@ -51,7 +49,7 @@ export type fetchDataOptions = RequestInit & { timeout?: number; proxy?: string; torPort?: number; - // eslint-disable-next-line @typescript-eslint/ban-types + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type debug?: Function; returnResponse?: boolean; }; @@ -69,11 +67,11 @@ export function getHttpAgent({ torPort?: number; retry: number; }): NodeAgent | undefined { - /* eslint-disable @typescript-eslint/no-var-requires */ + /* eslint-disable @typescript-eslint/no-require-imports */ const { HttpProxyAgent } = require('http-proxy-agent'); const { HttpsProxyAgent } = require('https-proxy-agent'); const { SocksProxyAgent } = require('socks-proxy-agent'); - /* eslint-enable @typescript-eslint/no-var-requires */ + /* eslint-enable @typescript-eslint/no-require-imports */ if (torPort) { return new SocksProxyAgent(`socks5h://tor${retry}@127.0.0.1:${torPort}`); @@ -128,7 +126,8 @@ export async function fetchData(url: string, options: fetchDataOptions = {}) { if (!options.signal && options.timeout) { const controller = new AbortController(); - options.signal = controller.signal; + // Temporary workaround until @types/node-fetch is compatible with @types/node + options.signal = controller.signal as FetchAbortSignal; // Define timeout in seconds timeout = setTimeout(() => { @@ -223,7 +222,8 @@ export const fetchGetUrlFunc = if (_signal) { const controller = new AbortController(); - signal = controller.signal; + // Temporary workaround until @types/node-fetch is compatible with @types/node + signal = controller.signal as FetchAbortSignal; _signal.addListener(() => { controller.abort(); }); @@ -257,113 +257,18 @@ export const fetchGetUrlFunc = }; /* eslint-enable @typescript-eslint/no-explicit-any */ -// caching to improve performance -const oracleMapper = new Map(); -const multicallMapper = new Map(); - export type getProviderOptions = fetchDataOptions & { pollingInterval?: number; - gasPriceOracle?: string; - gasStationApi?: string; }; -export function getGasOraclePlugin(networkKey: string, fetchOptions?: getProviderOptions) { - const gasStationApi = fetchOptions?.gasStationApi || 'https://gasstation.polygon.technology/v2'; - - // eslint-disable-next-line @typescript-eslint/no-unused-vars - return new FetchUrlFeeDataNetworkPlugin(gasStationApi, async (fetchFeeData, provider, request) => { - if (!oracleMapper.has(networkKey)) { - oracleMapper.set(networkKey, GasPriceOracle__factory.connect(fetchOptions?.gasPriceOracle as string, provider)); - } - if (!multicallMapper.has(networkKey)) { - multicallMapper.set( - networkKey, - Multicall__factory.connect('0xcA11bde05977b3631167028862bE2a173976CA11', provider), - ); - } - const Oracle = oracleMapper.get(networkKey) as GasPriceOracle; - const Multicall = multicallMapper.get(networkKey) as Multicall; - - const [timestamp, heartbeat, feePerGas, priorityFeePerGas] = await multicall(Multicall, [ - { - contract: Oracle, - name: 'timestamp', - }, - { - contract: Oracle, - name: 'heartbeat', - }, - { - contract: Oracle, - name: 'maxFeePerGas', - }, - { - contract: Oracle, - name: 'maxPriorityFeePerGas', - }, - ]); - - const isOutdated = Number(timestamp) <= Date.now() / 1000 - Number(heartbeat); - - if (!isOutdated) { - const maxPriorityFeePerGas = (priorityFeePerGas * BigInt(13)) / BigInt(10); - const maxFeePerGas = feePerGas * BigInt(2) + maxPriorityFeePerGas; - - return { - gasPrice: maxFeePerGas, - maxFeePerGas, - maxPriorityFeePerGas, - }; - } - - const fetchReq = new FetchRequest(gasStationApi); - fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); - if (isNode) { - // Prevent Cloudflare from blocking our request in node.js - fetchReq.setHeader('User-Agent', 'ethers'); - } - - const [ - { - bodyJson: { fast }, - }, - { gasPrice }, - ] = await Promise.all([fetchReq.send(), fetchFeeData()]); - - return { - gasPrice, - maxFeePerGas: parseUnits(`${fast.maxFee}`, 9), - maxPriorityFeePerGas: parseUnits(`${fast.maxPriorityFee}`, 9), - }; - }); -} - export async function getProvider(rpcUrl: string, fetchOptions?: getProviderOptions): Promise { const fetchReq = new FetchRequest(rpcUrl); fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); - // omit network plugins and mimic registerEth function (required for polygon) - const _staticNetwork = await new JsonRpcProvider(fetchReq).getNetwork(); - const ensPlugin = _staticNetwork.getPlugin('org.ethers.plugins.network.Ens'); - const gasCostPlugin = _staticNetwork.getPlugin('org.ethers.plugins.network.GasCost'); - const gasStationPlugin = ( - _staticNetwork.getPlugin('org.ethers.plugins.network.FetchUrlFeeDataPlugin') - ); - const staticNetwork = new Network(_staticNetwork.name, _staticNetwork.chainId); - if (ensPlugin) { - staticNetwork.attachPlugin(ensPlugin); - } - if (gasCostPlugin) { - staticNetwork.attachPlugin(gasCostPlugin); - } - if (fetchOptions?.gasPriceOracle) { - staticNetwork.attachPlugin(getGasOraclePlugin(`${_staticNetwork.chainId}_${rpcUrl}`, fetchOptions)); - } else if (gasStationPlugin) { - staticNetwork.attachPlugin(gasStationPlugin); - } + const staticNetwork = await new JsonRpcProvider(fetchReq).getNetwork(); const provider = new JsonRpcProvider(fetchReq, staticNetwork, { staticNetwork, + pollingInterval: fetchOptions?.pollingInterval || 1000, }); - provider.pollingInterval = fetchOptions?.pollingInterval || 1000; return provider; } @@ -373,7 +278,7 @@ export function getProviderWithNetId( config: Config, fetchOptions?: getProviderOptions, ): JsonRpcProvider { - const { networkName, reverseRecordsContract, gasPriceOracleContract, gasStationApi, pollInterval } = config; + const { networkName, reverseRecordsContract, pollInterval } = config; const hasEns = Boolean(reverseRecordsContract); const fetchReq = new FetchRequest(rpcUrl); @@ -382,24 +287,13 @@ export function getProviderWithNetId( if (hasEns) { staticNetwork.attachPlugin(new EnsPlugin(null, Number(netId))); } - staticNetwork.attachPlugin(new GasCostPlugin()); - if (gasPriceOracleContract) { - staticNetwork.attachPlugin( - getGasOraclePlugin(`${netId}_${rpcUrl}`, { - gasPriceOracle: gasPriceOracleContract, - gasStationApi, - }), - ); - } - const provider = new JsonRpcProvider(fetchReq, staticNetwork, { staticNetwork, + pollingInterval: fetchOptions?.pollingInterval || pollInterval * 1000, }); - provider.pollingInterval = fetchOptions?.pollingInterval || pollInterval * 1000; - return provider; } diff --git a/src/schemas/index.ts b/src/schemas/index.ts index b7059a2..bfbc360 100644 --- a/src/schemas/index.ts +++ b/src/schemas/index.ts @@ -10,7 +10,7 @@ ajv.addKeyword({ try { BigInt(data); return true; - } catch (e) { + } catch { return false; } }, diff --git a/src/typechain/factories/index.ts b/src/typechain/factories/index.ts index b959d05..10920b7 100644 --- a/src/typechain/factories/index.ts +++ b/src/typechain/factories/index.ts @@ -3,7 +3,6 @@ /* eslint-disable */ export { ENS__factory } from "./ENS__factory"; export { ERC20__factory } from "./ERC20__factory"; -export { GasPriceOracle__factory } from "./GasPriceOracle__factory"; export { Multicall__factory } from "./Multicall__factory"; export { OffchainOracle__factory } from "./OffchainOracle__factory"; export { OvmGasPriceOracle__factory } from "./OvmGasPriceOracle__factory"; diff --git a/src/typechain/index.ts b/src/typechain/index.ts index 7267d3c..b028a66 100644 --- a/src/typechain/index.ts +++ b/src/typechain/index.ts @@ -3,7 +3,6 @@ /* eslint-disable */ export type { ENS } from "./ENS"; export type { ERC20 } from "./ERC20"; -export type { GasPriceOracle } from "./GasPriceOracle"; export type { Multicall } from "./Multicall"; export type { OffchainOracle } from "./OffchainOracle"; export type { OvmGasPriceOracle } from "./OvmGasPriceOracle"; @@ -11,7 +10,6 @@ export type { ReverseRecords } from "./ReverseRecords"; export * as factories from "./factories"; export { ENS__factory } from "./factories/ENS__factory"; export { ERC20__factory } from "./factories/ERC20__factory"; -export { GasPriceOracle__factory } from "./factories/GasPriceOracle__factory"; export { Multicall__factory } from "./factories/Multicall__factory"; export { OffchainOracle__factory } from "./factories/OffchainOracle__factory"; export { OvmGasPriceOracle__factory } from "./factories/OvmGasPriceOracle__factory"; diff --git a/tsconfig.json b/tsconfig.json index 8fd0f0f..ae01d22 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -15,7 +15,7 @@ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ /* Language and Environment */ - "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + "target": "es2018", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ // "jsx": "preserve", /* Specify what JSX code is generated. */ // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ diff --git a/webpack.config.js b/webpack.config.js index 07d7e8e..89b7609 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -1,4 +1,3 @@ -const esbuild = require('esbuild'); const path = require('path'); const NodePolyfillPlugin = require('node-polyfill-webpack-plugin'); @@ -8,7 +7,6 @@ const esbuildLoader = { options: { loader: 'ts', target: 'es2016', - implementation: esbuild } } diff --git a/yarn.lock b/yarn.lock index 3103d8d..59f2b28 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2,35 +2,30 @@ # yarn lockfile v1 -"@aashutoshrathi/word-wrap@^1.2.3": - version "1.2.6" - resolved "https://registry.yarnpkg.com/@aashutoshrathi/word-wrap/-/word-wrap-1.2.6.tgz#bd9154aec9983f77b3a034ecaa015c2e4201f6cf" - integrity sha512-1Yjs2SvM8TflER/OD3cOjhWWOZb58A2t7wpE2S9XfBYTiIl+XFhQG2bjy4Pu1I+EAlCNUzRDYDdFwFYUKvXcIA== - "@adraffy/ens-normalize@1.10.1": version "1.10.1" resolved "https://registry.yarnpkg.com/@adraffy/ens-normalize/-/ens-normalize-1.10.1.tgz#63430d04bd8c5e74f8d7d049338f1cd9d4f02069" integrity sha512-96Z2IP3mYmF1Xg2cDm8f1gWGf/HUVedQ3FMifV4kG/PQ4yEP51xDtRAEfhVNt5f/uzpNkZHwWQuUcu6D6K+Ekw== "@babel/code-frame@^7.0.0": - version "7.24.2" - resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.24.2.tgz#718b4b19841809a58b29b68cde80bc5e1aa6d9ae" - integrity sha512-y5+tLQyV8pg3fsiln67BVLD1P13Eg4lh5RW9mF0zUuvLrv9uIQ4MCL+CRT+FTsBlBjcIan6PGsLcBN0m3ClUyQ== + version "7.24.7" + resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.24.7.tgz#882fd9e09e8ee324e496bd040401c6f046ef4465" + integrity sha512-BcYH1CVJBO9tvyIZ2jVeXgSIMvGZ2FDRvDdOIVQyuklNKSsx+eppDEBq/g47Ayw+RqNFE+URvOShmf+f/qwAlA== dependencies: - "@babel/highlight" "^7.24.2" + "@babel/highlight" "^7.24.7" picocolors "^1.0.0" -"@babel/helper-validator-identifier@^7.22.20": - version "7.22.20" - resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz#c4ae002c61d2879e724581d96665583dbc1dc0e0" - integrity sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A== +"@babel/helper-validator-identifier@^7.24.7": + version "7.24.7" + resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.24.7.tgz#75b889cfaf9e35c2aaf42cf0d72c8e91719251db" + integrity sha512-rR+PBcQ1SMQDDyF6X0wxtG8QyLCgUB0eRAGguqRLfkCA87l7yAP7ehq8SNj96OOGTO8OBV70KhuFYcIkHXOg0w== -"@babel/highlight@^7.24.2": - version "7.24.2" - resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.24.2.tgz#3f539503efc83d3c59080a10e6634306e0370d26" - integrity sha512-Yac1ao4flkTxTteCDZLEvdxg2fZfz1v8M4QpaGypq/WPDqg3ijHYbDfs+LG5hvzSoqaSZ9/Z9lKSP3CjZjv+pA== +"@babel/highlight@^7.24.7": + version "7.24.7" + resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.24.7.tgz#a05ab1df134b286558aae0ed41e6c5f731bf409d" + integrity sha512-EStJpq4OuY8xYfhGVXngigBJRWxftKX9ksiGDnmlY3o7B/V7KIAc9X4oiK87uPJSc/vs5L869bem5fhZa8caZw== dependencies: - "@babel/helper-validator-identifier" "^7.22.20" + "@babel/helper-validator-identifier" "^7.24.7" chalk "^2.4.2" js-tokens "^4.0.0" picocolors "^1.0.0" @@ -40,120 +35,120 @@ resolved "https://registry.yarnpkg.com/@discoveryjs/json-ext/-/json-ext-0.5.7.tgz#1d572bfbbe14b7704e0ba0f39b74815b84870d70" integrity sha512-dBVuXR082gk3jsFp7Rd/JI4kytwGHecnCoTtXFb7DB6CNHp4rg5k1bhg0nWdLGLnOV71lmDzGQaLMy8iPLY0pw== -"@esbuild/aix-ppc64@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/aix-ppc64/-/aix-ppc64-0.20.2.tgz#a70f4ac11c6a1dfc18b8bbb13284155d933b9537" - integrity sha512-D+EBOJHXdNZcLJRBkhENNG8Wji2kgc9AZ9KiPr1JuZjsNtyHzrsfLRrY0tk2H2aoFu6RANO1y1iPPUCDYWkb5g== +"@esbuild/aix-ppc64@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz#c7184a326533fcdf1b8ee0733e21c713b975575f" + integrity sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ== -"@esbuild/android-arm64@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/android-arm64/-/android-arm64-0.20.2.tgz#db1c9202a5bc92ea04c7b6840f1bbe09ebf9e6b9" - integrity sha512-mRzjLacRtl/tWU0SvD8lUEwb61yP9cqQo6noDZP/O8VkwafSYwZ4yWy24kan8jE/IMERpYncRt2dw438LP3Xmg== +"@esbuild/android-arm64@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz#09d9b4357780da9ea3a7dfb833a1f1ff439b4052" + integrity sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A== -"@esbuild/android-arm@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/android-arm/-/android-arm-0.20.2.tgz#3b488c49aee9d491c2c8f98a909b785870d6e995" - integrity sha512-t98Ra6pw2VaDhqNWO2Oph2LXbz/EJcnLmKLGBJwEwXX/JAN83Fym1rU8l0JUWK6HkIbWONCSSatf4sf2NBRx/w== +"@esbuild/android-arm@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/android-arm/-/android-arm-0.21.5.tgz#9b04384fb771926dfa6d7ad04324ecb2ab9b2e28" + integrity sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg== -"@esbuild/android-x64@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/android-x64/-/android-x64-0.20.2.tgz#3b1628029e5576249d2b2d766696e50768449f98" - integrity sha512-btzExgV+/lMGDDa194CcUQm53ncxzeBrWJcncOBxuC6ndBkKxnHdFJn86mCIgTELsooUmwUm9FkhSp5HYu00Rg== +"@esbuild/android-x64@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/android-x64/-/android-x64-0.21.5.tgz#29918ec2db754cedcb6c1b04de8cd6547af6461e" + integrity sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA== -"@esbuild/darwin-arm64@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/darwin-arm64/-/darwin-arm64-0.20.2.tgz#6e8517a045ddd86ae30c6608c8475ebc0c4000bb" - integrity sha512-4J6IRT+10J3aJH3l1yzEg9y3wkTDgDk7TSDFX+wKFiWjqWp/iCfLIYzGyasx9l0SAFPT1HwSCR+0w/h1ES/MjA== +"@esbuild/darwin-arm64@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz#e495b539660e51690f3928af50a76fb0a6ccff2a" + integrity sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ== -"@esbuild/darwin-x64@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/darwin-x64/-/darwin-x64-0.20.2.tgz#90ed098e1f9dd8a9381695b207e1cff45540a0d0" - integrity sha512-tBcXp9KNphnNH0dfhv8KYkZhjc+H3XBkF5DKtswJblV7KlT9EI2+jeA8DgBjp908WEuYll6pF+UStUCfEpdysA== +"@esbuild/darwin-x64@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz#c13838fa57372839abdddc91d71542ceea2e1e22" + integrity sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw== -"@esbuild/freebsd-arm64@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/freebsd-arm64/-/freebsd-arm64-0.20.2.tgz#d71502d1ee89a1130327e890364666c760a2a911" - integrity sha512-d3qI41G4SuLiCGCFGUrKsSeTXyWG6yem1KcGZVS+3FYlYhtNoNgYrWcvkOoaqMhwXSMrZRl69ArHsGJ9mYdbbw== +"@esbuild/freebsd-arm64@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz#646b989aa20bf89fd071dd5dbfad69a3542e550e" + integrity sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g== -"@esbuild/freebsd-x64@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/freebsd-x64/-/freebsd-x64-0.20.2.tgz#aa5ea58d9c1dd9af688b8b6f63ef0d3d60cea53c" - integrity sha512-d+DipyvHRuqEeM5zDivKV1KuXn9WeRX6vqSqIDgwIfPQtwMP4jaDsQsDncjTDDsExT4lR/91OLjRo8bmC1e+Cw== +"@esbuild/freebsd-x64@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz#aa615cfc80af954d3458906e38ca22c18cf5c261" + integrity sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ== -"@esbuild/linux-arm64@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/linux-arm64/-/linux-arm64-0.20.2.tgz#055b63725df678379b0f6db9d0fa85463755b2e5" - integrity sha512-9pb6rBjGvTFNira2FLIWqDk/uaf42sSyLE8j1rnUpuzsODBq7FvpwHYZxQ/It/8b+QOS1RYfqgGFNLRI+qlq2A== +"@esbuild/linux-arm64@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz#70ac6fa14f5cb7e1f7f887bcffb680ad09922b5b" + integrity sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q== -"@esbuild/linux-arm@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/linux-arm/-/linux-arm-0.20.2.tgz#76b3b98cb1f87936fbc37f073efabad49dcd889c" - integrity sha512-VhLPeR8HTMPccbuWWcEUD1Az68TqaTYyj6nfE4QByZIQEQVWBB8vup8PpR7y1QHL3CpcF6xd5WVBU/+SBEvGTg== +"@esbuild/linux-arm@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz#fc6fd11a8aca56c1f6f3894f2bea0479f8f626b9" + integrity sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA== -"@esbuild/linux-ia32@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/linux-ia32/-/linux-ia32-0.20.2.tgz#c0e5e787c285264e5dfc7a79f04b8b4eefdad7fa" - integrity sha512-o10utieEkNPFDZFQm9CoP7Tvb33UutoJqg3qKf1PWVeeJhJw0Q347PxMvBgVVFgouYLGIhFYG0UGdBumROyiig== +"@esbuild/linux-ia32@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz#3271f53b3f93e3d093d518d1649d6d68d346ede2" + integrity sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg== -"@esbuild/linux-loong64@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/linux-loong64/-/linux-loong64-0.20.2.tgz#a6184e62bd7cdc63e0c0448b83801001653219c5" - integrity sha512-PR7sp6R/UC4CFVomVINKJ80pMFlfDfMQMYynX7t1tNTeivQ6XdX5r2XovMmha/VjR1YN/HgHWsVcTRIMkymrgQ== +"@esbuild/linux-loong64@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz#ed62e04238c57026aea831c5a130b73c0f9f26df" + integrity sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg== -"@esbuild/linux-mips64el@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/linux-mips64el/-/linux-mips64el-0.20.2.tgz#d08e39ce86f45ef8fc88549d29c62b8acf5649aa" - integrity sha512-4BlTqeutE/KnOiTG5Y6Sb/Hw6hsBOZapOVF6njAESHInhlQAghVVZL1ZpIctBOoTFbQyGW+LsVYZ8lSSB3wkjA== +"@esbuild/linux-mips64el@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz#e79b8eb48bf3b106fadec1ac8240fb97b4e64cbe" + integrity sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg== -"@esbuild/linux-ppc64@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/linux-ppc64/-/linux-ppc64-0.20.2.tgz#8d252f0b7756ffd6d1cbde5ea67ff8fd20437f20" - integrity sha512-rD3KsaDprDcfajSKdn25ooz5J5/fWBylaaXkuotBDGnMnDP1Uv5DLAN/45qfnf3JDYyJv/ytGHQaziHUdyzaAg== +"@esbuild/linux-ppc64@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz#5f2203860a143b9919d383ef7573521fb154c3e4" + integrity sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w== -"@esbuild/linux-riscv64@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/linux-riscv64/-/linux-riscv64-0.20.2.tgz#19f6dcdb14409dae607f66ca1181dd4e9db81300" - integrity sha512-snwmBKacKmwTMmhLlz/3aH1Q9T8v45bKYGE3j26TsaOVtjIag4wLfWSiZykXzXuE1kbCE+zJRmwp+ZbIHinnVg== +"@esbuild/linux-riscv64@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz#07bcafd99322d5af62f618cb9e6a9b7f4bb825dc" + integrity sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA== -"@esbuild/linux-s390x@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/linux-s390x/-/linux-s390x-0.20.2.tgz#3c830c90f1a5d7dd1473d5595ea4ebb920988685" - integrity sha512-wcWISOobRWNm3cezm5HOZcYz1sKoHLd8VL1dl309DiixxVFoFe/o8HnwuIwn6sXre88Nwj+VwZUvJf4AFxkyrQ== +"@esbuild/linux-s390x@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz#b7ccf686751d6a3e44b8627ababc8be3ef62d8de" + integrity sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A== -"@esbuild/linux-x64@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/linux-x64/-/linux-x64-0.20.2.tgz#86eca35203afc0d9de0694c64ec0ab0a378f6fff" - integrity sha512-1MdwI6OOTsfQfek8sLwgyjOXAu+wKhLEoaOLTjbijk6E2WONYpH9ZU2mNtR+lZ2B4uwr+usqGuVfFT9tMtGvGw== +"@esbuild/linux-x64@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz#6d8f0c768e070e64309af8004bb94e68ab2bb3b0" + integrity sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ== -"@esbuild/netbsd-x64@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/netbsd-x64/-/netbsd-x64-0.20.2.tgz#e771c8eb0e0f6e1877ffd4220036b98aed5915e6" - integrity sha512-K8/DhBxcVQkzYc43yJXDSyjlFeHQJBiowJ0uVL6Tor3jGQfSGHNNJcWxNbOI8v5k82prYqzPuwkzHt3J1T1iZQ== +"@esbuild/netbsd-x64@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz#bbe430f60d378ecb88decb219c602667387a6047" + integrity sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg== -"@esbuild/openbsd-x64@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/openbsd-x64/-/openbsd-x64-0.20.2.tgz#9a795ae4b4e37e674f0f4d716f3e226dd7c39baf" - integrity sha512-eMpKlV0SThJmmJgiVyN9jTPJ2VBPquf6Kt/nAoo6DgHAoN57K15ZghiHaMvqjCye/uU4X5u3YSMgVBI1h3vKrQ== +"@esbuild/openbsd-x64@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz#99d1cf2937279560d2104821f5ccce220cb2af70" + integrity sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow== -"@esbuild/sunos-x64@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/sunos-x64/-/sunos-x64-0.20.2.tgz#7df23b61a497b8ac189def6e25a95673caedb03f" - integrity sha512-2UyFtRC6cXLyejf/YEld4Hajo7UHILetzE1vsRcGL3earZEW77JxrFjH4Ez2qaTiEfMgAXxfAZCm1fvM/G/o8w== +"@esbuild/sunos-x64@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz#08741512c10d529566baba837b4fe052c8f3487b" + integrity sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg== -"@esbuild/win32-arm64@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/win32-arm64/-/win32-arm64-0.20.2.tgz#f1ae5abf9ca052ae11c1bc806fb4c0f519bacf90" - integrity sha512-GRibxoawM9ZCnDxnP3usoUDO9vUkpAxIIZ6GQI+IlVmr5kP3zUq+l17xELTHMWTWzjxa2guPNyrpq1GWmPvcGQ== +"@esbuild/win32-arm64@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz#675b7385398411240735016144ab2e99a60fc75d" + integrity sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A== -"@esbuild/win32-ia32@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/win32-ia32/-/win32-ia32-0.20.2.tgz#241fe62c34d8e8461cd708277813e1d0ba55ce23" - integrity sha512-HfLOfn9YWmkSKRQqovpnITazdtquEW8/SoHW7pWpuEeguaZI4QnCRW6b+oZTztdBnZOS2hqJ6im/D5cPzBTTlQ== +"@esbuild/win32-ia32@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz#1bfc3ce98aa6ca9a0969e4d2af72144c59c1193b" + integrity sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA== -"@esbuild/win32-x64@0.20.2": - version "0.20.2" - resolved "https://registry.yarnpkg.com/@esbuild/win32-x64/-/win32-x64-0.20.2.tgz#9c907b21e30a52db959ba4f80bb01a0cc403d5cc" - integrity sha512-N49X4lJX27+l9jbLKSqZ6bKNjzQvHaT8IIFUy+YIqmXQdjYCToGWwOItDrfby14c78aDd5NHQl29xingXfCdLQ== +"@esbuild/win32-x64@0.21.5": + version "0.21.5" + resolved "https://registry.yarnpkg.com/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz#acad351d582d157bb145535db2a6ff53dd514b5c" + integrity sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw== "@eslint-community/eslint-utils@^4.2.0", "@eslint-community/eslint-utils@^4.4.0": version "4.4.0" @@ -163,9 +158,9 @@ eslint-visitor-keys "^3.3.0" "@eslint-community/regexpp@^4.10.0", "@eslint-community/regexpp@^4.6.1": - version "4.10.0" - resolved "https://registry.yarnpkg.com/@eslint-community/regexpp/-/regexpp-4.10.0.tgz#548f6de556857c8bb73bbee70c35dc82a2e74d63" - integrity sha512-Cu96Sd2By9mCNTx2iyKOmq10v22jUVQv0lQnlGNy16oE9589yE+QADPbrMGCkA51cKZSg3Pu/aTJVTGfL/qjUA== + version "4.11.1" + resolved "https://registry.yarnpkg.com/@eslint-community/regexpp/-/regexpp-4.11.1.tgz#a547badfc719eb3e5f4b556325e542fbe9d7a18f" + integrity sha512-m4DVN9ZqskZoLU5GlWZadwDnYo3vAEydiUayB9widCl9ffWx2IvPnp6n3on5rJmziJSw9Bv+Z3ChDVdMwXCY8Q== "@eslint/eslintrc@^2.1.4": version "2.1.4" @@ -580,6 +575,18 @@ resolved "https://registry.yarnpkg.com/@humanwhocodes/object-schema/-/object-schema-2.0.3.tgz#4a2868d75d6d6963e423bcf90b7fd1be343409d3" integrity sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA== +"@isaacs/cliui@^8.0.2": + version "8.0.2" + resolved "https://registry.yarnpkg.com/@isaacs/cliui/-/cliui-8.0.2.tgz#b37667b7bc181c168782259bab42474fbf52b550" + integrity sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA== + dependencies: + string-width "^5.1.2" + string-width-cjs "npm:string-width@^4.2.0" + strip-ansi "^7.0.1" + strip-ansi-cjs "npm:strip-ansi@^6.0.1" + wrap-ansi "^8.1.0" + wrap-ansi-cjs "npm:wrap-ansi@^7.0.0" + "@jridgewell/gen-mapping@^0.3.5": version "0.3.5" resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.5.tgz#dcce6aff74bdf6dad1a95802b69b04a2fcb1fb36" @@ -607,10 +614,10 @@ "@jridgewell/gen-mapping" "^0.3.5" "@jridgewell/trace-mapping" "^0.3.25" -"@jridgewell/sourcemap-codec@^1.4.10", "@jridgewell/sourcemap-codec@^1.4.14", "@jridgewell/sourcemap-codec@^1.4.15": - version "1.4.15" - resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz#d7c6e6755c78567a951e04ab52ef0fd26de59f32" - integrity sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg== +"@jridgewell/sourcemap-codec@^1.4.10", "@jridgewell/sourcemap-codec@^1.4.14", "@jridgewell/sourcemap-codec@^1.5.0": + version "1.5.0" + resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz#3188bcb273a414b0d215fd22a58540b989b9409a" + integrity sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ== "@jridgewell/trace-mapping@^0.3.20", "@jridgewell/trace-mapping@^0.3.24", "@jridgewell/trace-mapping@^0.3.25": version "0.3.25" @@ -620,39 +627,44 @@ "@jridgewell/resolve-uri" "^3.1.0" "@jridgewell/sourcemap-codec" "^1.4.14" -"@metamask/abi-utils@^2.0.2": - version "2.0.2" - resolved "https://registry.yarnpkg.com/@metamask/abi-utils/-/abi-utils-2.0.2.tgz#ad394e9cb8a95ac177cad942daadd88a246c0de8" - integrity sha512-B/A1dY/w4F/t6cDHUscklO6ovb/ztFsrsTXFd8QlqSByk/vyy+QbPE3VVpmmyI/7RX+PA1AJcvBdzCIz+r9dVQ== +"@metamask/abi-utils@^2.0.4": + version "2.0.4" + resolved "https://registry.yarnpkg.com/@metamask/abi-utils/-/abi-utils-2.0.4.tgz#20908c1d910f7a17a89fdf5778a5c59d5cb8b8be" + integrity sha512-StnIgUB75x7a7AgUhiaUZDpCsqGp7VkNnZh2XivXkJ6mPkE83U8ARGQj5MbRis7VJY8BC5V1AbB1fjdh0hupPQ== dependencies: - "@metamask/utils" "^8.0.0" - superstruct "^1.0.3" + "@metamask/superstruct" "^3.1.0" + "@metamask/utils" "^9.0.0" -"@metamask/eth-sig-util@^7.0.1": - version "7.0.1" - resolved "https://registry.yarnpkg.com/@metamask/eth-sig-util/-/eth-sig-util-7.0.1.tgz#ad3227d6120f15f9293478de7dd9685a5c329586" - integrity sha512-59GSrMyFH2fPfu7nKeIQdZ150zxXNNhAQIUaFRUW+MGtVA4w/ONbiQobcRBLi+jQProfIyss51G8pfLPcQ0ylg== +"@metamask/eth-sig-util@^7.0.3": + version "7.0.3" + resolved "https://registry.yarnpkg.com/@metamask/eth-sig-util/-/eth-sig-util-7.0.3.tgz#be9e444fe0b8474c04e2ff42fd983173767f6ac0" + integrity sha512-PAtGnOkYvh90k2lEZldq/FK7GTLF6WxE+2bV85PoA3pqlJnmJCAY62tuvxHSwnVngSKlc4mcNvjnUg2eYO6JGg== dependencies: "@ethereumjs/util" "^8.1.0" - "@metamask/abi-utils" "^2.0.2" - "@metamask/utils" "^8.1.0" + "@metamask/abi-utils" "^2.0.4" + "@metamask/utils" "^9.0.0" + "@scure/base" "~1.1.3" ethereum-cryptography "^2.1.2" tweetnacl "^1.0.3" - tweetnacl-util "^0.15.1" -"@metamask/utils@^8.0.0", "@metamask/utils@^8.1.0": - version "8.4.0" - resolved "https://registry.yarnpkg.com/@metamask/utils/-/utils-8.4.0.tgz#f44812c96467a4e1b70b2edff6ee89a9caa4e354" - integrity sha512-dbIc3C7alOe0agCuBHM1h71UaEaEqOk2W8rAtEn8QGz4haH2Qq7MoK6i7v2guzvkJVVh79c+QCzIqphC3KvrJg== +"@metamask/superstruct@^3.1.0": + version "3.1.0" + resolved "https://registry.yarnpkg.com/@metamask/superstruct/-/superstruct-3.1.0.tgz#148f786a674fba3ac885c1093ab718515bf7f648" + integrity sha512-N08M56HdOgBfRKkrgCMZvQppkZGcArEop3kixNEtVbJKm6P9Cfg0YkI6X0s1g78sNrj2fWUwvJADdZuzJgFttA== + +"@metamask/utils@^9.0.0": + version "9.2.1" + resolved "https://registry.yarnpkg.com/@metamask/utils/-/utils-9.2.1.tgz#d9f84706ff97e0c8d1bde5778549365b14269e81" + integrity sha512-/u663aUaB6+Xe75i3Mt/1cCljm41HDYIsna5oBrwGvgkY2zH7/9k9Zjd706cxoAbxN7QgLSVAReUiGnuxCuXrQ== dependencies: "@ethereumjs/tx" "^4.2.0" + "@metamask/superstruct" "^3.1.0" "@noble/hashes" "^1.3.1" "@scure/base" "^1.1.3" "@types/debug" "^4.1.7" debug "^4.3.4" pony-cause "^2.1.10" semver "^7.5.4" - superstruct "^1.0.3" uuid "^9.0.1" "@noble/curves@1.2.0": @@ -662,28 +674,28 @@ dependencies: "@noble/hashes" "1.3.2" -"@noble/curves@1.3.0", "@noble/curves@~1.3.0": - version "1.3.0" - resolved "https://registry.yarnpkg.com/@noble/curves/-/curves-1.3.0.tgz#01be46da4fd195822dab821e72f71bf4aeec635e" - integrity sha512-t01iSXPuN+Eqzb4eBX0S5oubSqXbK/xXa1Ne18Hj8f9pStxztHCE2gfboSp/dZRLSqfuLpRK2nDXDK+W9puocA== +"@noble/curves@1.4.2", "@noble/curves@~1.4.0": + version "1.4.2" + resolved "https://registry.yarnpkg.com/@noble/curves/-/curves-1.4.2.tgz#40309198c76ed71bc6dbf7ba24e81ceb4d0d1fe9" + integrity sha512-TavHr8qycMChk8UwMld0ZDRvatedkzWfH8IiaeGCfymOP5i0hSCozz9vHOL0nkwk7HRMlFnAiKpS2jrUmSybcw== dependencies: - "@noble/hashes" "1.3.3" + "@noble/hashes" "1.4.0" "@noble/hashes@1.3.2": version "1.3.2" resolved "https://registry.yarnpkg.com/@noble/hashes/-/hashes-1.3.2.tgz#6f26dbc8fbc7205873ce3cee2f690eba0d421b39" integrity sha512-MVC8EAQp7MvEcm30KWENFjgR+Mkmf+D189XJTkFIlwohU5hcBbn1ZkKq7KVTi2Hme3PMGF390DaL52beVrIihQ== -"@noble/hashes@1.3.3", "@noble/hashes@~1.3.2": - version "1.3.3" - resolved "https://registry.yarnpkg.com/@noble/hashes/-/hashes-1.3.3.tgz#39908da56a4adc270147bb07968bf3b16cfe1699" - integrity sha512-V7/fPHgl+jsVPXqqeOzT8egNj2iBIVt+ECeMMG8TdcnTikP3oaBtUVqpT/gYCR68aEBJSF+XbYUxStjbFMqIIA== - -"@noble/hashes@^1.3.1": +"@noble/hashes@1.4.0", "@noble/hashes@~1.4.0": version "1.4.0" resolved "https://registry.yarnpkg.com/@noble/hashes/-/hashes-1.4.0.tgz#45814aa329f30e4fe0ba49426f49dfccdd066426" integrity sha512-V1JJ1WTRUqHHrOSh597hURcMqVKVGL/ea3kv0gSnEdsEZ0/+VyPghM1lMNGc00z7CIQorSvbKpuJkxvuHbvdbg== +"@noble/hashes@^1.3.1": + version "1.5.0" + resolved "https://registry.yarnpkg.com/@noble/hashes/-/hashes-1.5.0.tgz#abadc5ca20332db2b1b2aa3e496e9af1213570b0" + integrity sha512-1j6kQFb7QRru7eKN3ZDvRcP13rugwdxZqCjbiAVZfIJwgj2A65UmT4TgARXGlXgnRkORLTDTrO19ZErt7+QXgA== + "@nodelib/fs.scandir@2.1.5": version "2.1.5" resolved "https://registry.yarnpkg.com/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz#7619c2eb21b25483f6d167548b4cfd5a7488c3d5" @@ -705,6 +717,11 @@ "@nodelib/fs.scandir" "2.1.5" fastq "^1.6.0" +"@nolyfill/is-core-module@1.0.39": + version "1.0.39" + resolved "https://registry.yarnpkg.com/@nolyfill/is-core-module/-/is-core-module-1.0.39.tgz#3dc35ba0f1e66b403c00b39344f870298ebb1c8e" + integrity sha512-nn5ozdjYQpUCZlWGuxcJY/KpxkWQs4DcbMCmKojjyrYDEAGy4Ce19NN4v5MduafTwJlbKc99UA8YhSVqq9yPZA== + "@openzeppelin/contracts-v3@npm:@openzeppelin/contracts@3.2.0-rc.0": version "3.2.0-rc.0" resolved "https://registry.yarnpkg.com/@openzeppelin/contracts/-/contracts-3.2.0-rc.0.tgz#1f39e49df5f7a7b42fd49343ac1d758bbd24b826" @@ -715,20 +732,25 @@ resolved "https://registry.yarnpkg.com/@openzeppelin/contracts/-/contracts-5.0.2.tgz#b1d03075e49290d06570b2fd42154d76c2a5d210" integrity sha512-ytPc6eLGcHHnapAZ9S+5qsdomhjo6QBHTDRRBFfTxXIpsicMhVPouPgmUPebZZZGX7vt9USA+Z+0M0dSVtSUEA== +"@pkgjs/parseargs@^0.11.0": + version "0.11.0" + resolved "https://registry.yarnpkg.com/@pkgjs/parseargs/-/parseargs-0.11.0.tgz#a77ea742fab25775145434eb1d2328cf5013ac33" + integrity sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg== + "@pkgr/core@^0.1.0": version "0.1.1" resolved "https://registry.yarnpkg.com/@pkgr/core/-/core-0.1.1.tgz#1ec17e2edbec25c8306d424ecfbf13c7de1aaa31" integrity sha512-cq8o4cWH0ibXh9VGi5P20Tu9XF/0fFXl9EUinr9QfTM7a7p0oTA4iJRCQWppXR1Pg8dSM0UCItCkPwsk9qWWYA== -"@rollup/plugin-commonjs@^25.0.7": - version "25.0.7" - resolved "https://registry.yarnpkg.com/@rollup/plugin-commonjs/-/plugin-commonjs-25.0.7.tgz#145cec7589ad952171aeb6a585bbeabd0fd3b4cf" - integrity sha512-nEvcR+LRjEjsaSsc4x3XZfCCvZIaSMenZu/OiwOKGN2UhQpAYI7ru7czFvyWbErlpoGjnSX3D5Ch5FcMA3kRWQ== +"@rollup/plugin-commonjs@^26.0.1": + version "26.0.1" + resolved "https://registry.yarnpkg.com/@rollup/plugin-commonjs/-/plugin-commonjs-26.0.1.tgz#16d4d6e54fa63021249a292b50f27c0b0f1a30d8" + integrity sha512-UnsKoZK6/aGIH6AdkptXhNvhaqftcjq3zZdT+LY5Ftms6JR06nADcDsYp5hTU9E2lbJUEOhdlY5J4DNTneM+jQ== dependencies: "@rollup/pluginutils" "^5.0.1" commondir "^1.0.1" estree-walker "^2.0.2" - glob "^8.0.3" + glob "^10.4.1" is-reference "1.2.1" magic-string "^0.30.3" @@ -760,121 +782,128 @@ estree-walker "^2.0.2" picomatch "^2.3.1" -"@rollup/rollup-android-arm-eabi@4.14.1": - version "4.14.1" - resolved "https://registry.yarnpkg.com/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.14.1.tgz#ca0501dd836894216cb9572848c5dde4bfca3bec" - integrity sha512-fH8/o8nSUek8ceQnT7K4EQbSiV7jgkHq81m9lWZFIXjJ7lJzpWXbQFpT/Zh6OZYnpFykvzC3fbEvEAFZu03dPA== +"@rollup/rollup-android-arm-eabi@4.22.0": + version "4.22.0" + resolved "https://registry.yarnpkg.com/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.22.0.tgz#e8c16c336f060b4cb592f62eb4f0e543d79d51fe" + integrity sha512-/IZQvg6ZR0tAkEi4tdXOraQoWeJy9gbQ/cx4I7k9dJaCk9qrXEcdouxRVz5kZXt5C2bQ9pILoAA+KB4C/d3pfw== -"@rollup/rollup-android-arm64@4.14.1": - version "4.14.1" - resolved "https://registry.yarnpkg.com/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.14.1.tgz#154ca7e4f815d2e442ffc62ee7f64aee8b2547b0" - integrity sha512-Y/9OHLjzkunF+KGEoJr3heiD5X9OLa8sbT1lm0NYeKyaM3oMhhQFvPB0bNZYJwlq93j8Z6wSxh9+cyKQaxS7PQ== +"@rollup/rollup-android-arm64@4.22.0": + version "4.22.0" + resolved "https://registry.yarnpkg.com/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.22.0.tgz#7a44160a14017fa744912d7037c7d81d6f8a46e7" + integrity sha512-ETHi4bxrYnvOtXeM7d4V4kZWixib2jddFacJjsOjwbgYSRsyXYtZHC4ht134OsslPIcnkqT+TKV4eU8rNBKyyQ== -"@rollup/rollup-darwin-arm64@4.14.1": - version "4.14.1" - resolved "https://registry.yarnpkg.com/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.14.1.tgz#02b522ab6ccc2c504634651985ff8e657b42c055" - integrity sha512-+kecg3FY84WadgcuSVm6llrABOdQAEbNdnpi5X3UwWiFVhZIZvKgGrF7kmLguvxHNQy+UuRV66cLVl3S+Rkt+Q== +"@rollup/rollup-darwin-arm64@4.22.0": + version "4.22.0" + resolved "https://registry.yarnpkg.com/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.22.0.tgz#6122dc37d4a09521d8abe18925956d3b46cfbac9" + integrity sha512-ZWgARzhSKE+gVUX7QWaECoRQsPwaD8ZR0Oxb3aUpzdErTvlEadfQpORPXkKSdKbFci9v8MJfkTtoEHnnW9Ulng== -"@rollup/rollup-darwin-x64@4.14.1": - version "4.14.1" - resolved "https://registry.yarnpkg.com/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.14.1.tgz#217737f9f73de729fdfd7d529afebb6c8283f554" - integrity sha512-2pYRzEjVqq2TB/UNv47BV/8vQiXkFGVmPFwJb+1E0IFFZbIX8/jo1olxqqMbo6xCXf8kabANhp5bzCij2tFLUA== +"@rollup/rollup-darwin-x64@4.22.0": + version "4.22.0" + resolved "https://registry.yarnpkg.com/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.22.0.tgz#453f345899cbf544aa0d6f5808d24d2e42f605b7" + integrity sha512-h0ZAtOfHyio8Az6cwIGS+nHUfRMWBDO5jXB8PQCARVF6Na/G6XS2SFxDl8Oem+S5ZsHQgtsI7RT4JQnI1qrlaw== -"@rollup/rollup-linux-arm-gnueabihf@4.14.1": - version "4.14.1" - resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.14.1.tgz#a87e478ab3f697c7f4e74c8b1cac1e0667f8f4be" - integrity sha512-mS6wQ6Do6/wmrF9aTFVpIJ3/IDXhg1EZcQFYHZLHqw6AzMBjTHWnCG35HxSqUNphh0EHqSM6wRTT8HsL1C0x5g== +"@rollup/rollup-linux-arm-gnueabihf@4.22.0": + version "4.22.0" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.22.0.tgz#3a32fa4e80a62a6d733014838b1123fe76b060fe" + integrity sha512-9pxQJSPwFsVi0ttOmqLY4JJ9pg9t1gKhK0JDbV1yUEETSx55fdyCjt39eBQ54OQCzAF0nVGO6LfEH1KnCPvelA== -"@rollup/rollup-linux-arm64-gnu@4.14.1": - version "4.14.1" - resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.14.1.tgz#4da6830eca27e5f4ca15f9197e5660952ca185c6" - integrity sha512-p9rGKYkHdFMzhckOTFubfxgyIO1vw//7IIjBBRVzyZebWlzRLeNhqxuSaZ7kCEKVkm/kuC9fVRW9HkC/zNRG2w== +"@rollup/rollup-linux-arm-musleabihf@4.22.0": + version "4.22.0" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.22.0.tgz#55d3953c54419e93efe124882a3103c8a2f65641" + integrity sha512-YJ5Ku5BmNJZb58A4qSEo3JlIG4d3G2lWyBi13ABlXzO41SsdnUKi3HQHe83VpwBVG4jHFTW65jOQb8qyoR+qzg== -"@rollup/rollup-linux-arm64-musl@4.14.1": - version "4.14.1" - resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.14.1.tgz#0b0ed35720aebc8f5e501d370a9ea0f686ead1e0" - integrity sha512-nDY6Yz5xS/Y4M2i9JLQd3Rofh5OR8Bn8qe3Mv/qCVpHFlwtZSBYSPaU4mrGazWkXrdQ98GB//H0BirGR/SKFSw== +"@rollup/rollup-linux-arm64-gnu@4.22.0": + version "4.22.0" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.22.0.tgz#cd626963b9962baf8e09d792e67b87269a5bcfff" + integrity sha512-U4G4u7f+QCqHlVg1Nlx+qapZy+QoG+NV6ux+upo/T7arNGwKvKP2kmGM4W5QTbdewWFgudQxi3kDNST9GT1/mg== -"@rollup/rollup-linux-powerpc64le-gnu@4.14.1": - version "4.14.1" - resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.14.1.tgz#024ad04d162726f25e62915851f7df69a9677c17" - integrity sha512-im7HE4VBL+aDswvcmfx88Mp1soqL9OBsdDBU8NqDEYtkri0qV0THhQsvZtZeNNlLeCUQ16PZyv7cqutjDF35qw== +"@rollup/rollup-linux-arm64-musl@4.22.0": + version "4.22.0" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.22.0.tgz#ad209270c9937a27346fce5b0670cbdfb1e6a0a6" + integrity sha512-aQpNlKmx3amwkA3a5J6nlXSahE1ijl0L9KuIjVOUhfOh7uw2S4piR3mtpxpRtbnK809SBtyPsM9q15CPTsY7HQ== -"@rollup/rollup-linux-riscv64-gnu@4.14.1": - version "4.14.1" - resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.14.1.tgz#180694d1cd069ddbe22022bb5b1bead3b7de581c" - integrity sha512-RWdiHuAxWmzPJgaHJdpvUUlDz8sdQz4P2uv367T2JocdDa98iRw2UjIJ4QxSyt077mXZT2X6pKfT2iYtVEvOFw== +"@rollup/rollup-linux-powerpc64le-gnu@4.22.0": + version "4.22.0" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.22.0.tgz#fdd173929a5bba8b7e8b37314380213d9604088f" + integrity sha512-9fx6Zj/7vve/Fp4iexUFRKb5+RjLCff6YTRQl4CoDhdMfDoobWmhAxQWV3NfShMzQk1Q/iCnageFyGfqnsmeqQ== -"@rollup/rollup-linux-s390x-gnu@4.14.1": - version "4.14.1" - resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.14.1.tgz#f7b4e2b0ca49be4e34f9ef0b548c926d94edee87" - integrity sha512-VMgaGQ5zRX6ZqV/fas65/sUGc9cPmsntq2FiGmayW9KMNfWVG/j0BAqImvU4KTeOOgYSf1F+k6at1UfNONuNjA== +"@rollup/rollup-linux-riscv64-gnu@4.22.0": + version "4.22.0" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.22.0.tgz#90b11314fbf45d04083f658e08dc3b32fd713061" + integrity sha512-VWQiCcN7zBgZYLjndIEh5tamtnKg5TGxyZPWcN9zBtXBwfcGSZ5cHSdQZfQH/GB4uRxk0D3VYbOEe/chJhPGLQ== -"@rollup/rollup-linux-x64-gnu@4.14.1": - version "4.14.1" - resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.14.1.tgz#0aaf79e5b9ccf7db3084fe6c3f2d2873a27d5af4" - integrity sha512-9Q7DGjZN+hTdJomaQ3Iub4m6VPu1r94bmK2z3UeWP3dGUecRC54tmVu9vKHTm1bOt3ASoYtEz6JSRLFzrysKlA== +"@rollup/rollup-linux-s390x-gnu@4.22.0": + version "4.22.0" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.22.0.tgz#46bb2f1135aeec646b720d6032d7c86915f8b2ec" + integrity sha512-EHmPnPWvyYqncObwqrosb/CpH3GOjE76vWVs0g4hWsDRUVhg61hBmlVg5TPXqF+g+PvIbqkC7i3h8wbn4Gp2Fg== -"@rollup/rollup-linux-x64-musl@4.14.1": - version "4.14.1" - resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.14.1.tgz#38f0a37ca5015eb07dff86a1b6f94279c179f4ed" - integrity sha512-JNEG/Ti55413SsreTguSx0LOVKX902OfXIKVg+TCXO6Gjans/k9O6ww9q3oLGjNDaTLxM+IHFMeXy/0RXL5R/g== +"@rollup/rollup-linux-x64-gnu@4.22.0": + version "4.22.0" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.22.0.tgz#d731a19af5f05eabcba871bda2eeb2fa8c8adb67" + integrity sha512-tsSWy3YQzmpjDKnQ1Vcpy3p9Z+kMFbSIesCdMNgLizDWFhrLZIoN21JSq01g+MZMDFF+Y1+4zxgrlqPjid5ohg== -"@rollup/rollup-win32-arm64-msvc@4.14.1": - version "4.14.1" - resolved "https://registry.yarnpkg.com/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.14.1.tgz#84d48c55740ede42c77373f76e85f368633a0cc3" - integrity sha512-ryS22I9y0mumlLNwDFYZRDFLwWh3aKaC72CWjFcFvxK0U6v/mOkM5Up1bTbCRAhv3kEIwW2ajROegCIQViUCeA== +"@rollup/rollup-linux-x64-musl@4.22.0": + version "4.22.0" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.22.0.tgz#5438b2dc38fe467444cf769146098be083022d0f" + integrity sha512-anr1Y11uPOQrpuU8XOikY5lH4Qu94oS6j0xrulHk3NkLDq19MlX8Ng/pVipjxBJ9a2l3+F39REZYyWQFkZ4/fw== -"@rollup/rollup-win32-ia32-msvc@4.14.1": - version "4.14.1" - resolved "https://registry.yarnpkg.com/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.14.1.tgz#c1e0bc39e20e760f0a526ddf14ae0543af796605" - integrity sha512-TdloItiGk+T0mTxKx7Hp279xy30LspMso+GzQvV2maYePMAWdmrzqSNZhUpPj3CGw12aGj57I026PgLCTu8CGg== +"@rollup/rollup-win32-arm64-msvc@4.22.0": + version "4.22.0" + resolved "https://registry.yarnpkg.com/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.22.0.tgz#6bd66c198f80c8e7050cfd901701cfb9555d768a" + integrity sha512-7LB+Bh+Ut7cfmO0m244/asvtIGQr5pG5Rvjz/l1Rnz1kDzM02pSX9jPaS0p+90H5I1x4d1FkCew+B7MOnoatNw== -"@rollup/rollup-win32-x64-msvc@4.14.1": - version "4.14.1" - resolved "https://registry.yarnpkg.com/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.14.1.tgz#299eee74b7d87e116083ac5b1ce8dd9434668294" - integrity sha512-wQGI+LY/Py20zdUPq+XCem7JcPOyzIJBm3dli+56DJsQOHbnXZFEwgmnC6el1TPAfC8lBT3m+z69RmLykNUbew== +"@rollup/rollup-win32-ia32-msvc@4.22.0": + version "4.22.0" + resolved "https://registry.yarnpkg.com/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.22.0.tgz#58daea1f1e65143c44c8f3311f30ff8eefa62bae" + integrity sha512-+3qZ4rer7t/QsC5JwMpcvCVPRcJt1cJrYS/TMJZzXIJbxWFQEVhrIc26IhB+5Z9fT9umfVc+Es2mOZgl+7jdJQ== -"@scure/base@^1.1.3", "@scure/base@~1.1.4": - version "1.1.6" - resolved "https://registry.yarnpkg.com/@scure/base/-/base-1.1.6.tgz#8ce5d304b436e4c84f896e0550c83e4d88cb917d" - integrity sha512-ok9AWwhcgYuGG3Zfhyqg+zwl+Wn5uE+dwC0NV/2qQkx4dABbb/bx96vWu8NSj+BNjjSjno+JRYRjle1jV08k3g== +"@rollup/rollup-win32-x64-msvc@4.22.0": + version "4.22.0" + resolved "https://registry.yarnpkg.com/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.22.0.tgz#956948629f6b87de0bdf526b28d940221540bbb6" + integrity sha512-YdicNOSJONVx/vuPkgPTyRoAPx3GbknBZRCOUkK84FJ/YTfs/F0vl/YsMscrB6Y177d+yDRcj+JWMPMCgshwrA== -"@scure/bip32@1.3.3": - version "1.3.3" - resolved "https://registry.yarnpkg.com/@scure/bip32/-/bip32-1.3.3.tgz#a9624991dc8767087c57999a5d79488f48eae6c8" - integrity sha512-LJaN3HwRbfQK0X1xFSi0Q9amqOgzQnnDngIt+ZlsBC3Bm7/nE7K0kwshZHyaru79yIVRv/e1mQAjZyuZG6jOFQ== +"@rtsao/scc@^1.1.0": + version "1.1.0" + resolved "https://registry.yarnpkg.com/@rtsao/scc/-/scc-1.1.0.tgz#927dd2fae9bc3361403ac2c7a00c32ddce9ad7e8" + integrity sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g== + +"@scure/base@^1.1.3", "@scure/base@~1.1.3", "@scure/base@~1.1.6": + version "1.1.9" + resolved "https://registry.yarnpkg.com/@scure/base/-/base-1.1.9.tgz#e5e142fbbfe251091f9c5f1dd4c834ac04c3dbd1" + integrity sha512-8YKhl8GHiNI/pU2VMaofa2Tor7PJRAjwQLBBuilkJ9L5+13yVbC7JO/wS7piioAvPSwR3JKM1IJ/u4xQzbcXKg== + +"@scure/bip32@1.4.0": + version "1.4.0" + resolved "https://registry.yarnpkg.com/@scure/bip32/-/bip32-1.4.0.tgz#4e1f1e196abedcef395b33b9674a042524e20d67" + integrity sha512-sVUpc0Vq3tXCkDGYVWGIZTRfnvu8LoTDaev7vbwh0omSvVORONr960MQWdKqJDCReIEmTj3PAr73O3aoxz7OPg== dependencies: - "@noble/curves" "~1.3.0" - "@noble/hashes" "~1.3.2" - "@scure/base" "~1.1.4" + "@noble/curves" "~1.4.0" + "@noble/hashes" "~1.4.0" + "@scure/base" "~1.1.6" -"@scure/bip39@1.2.2": - version "1.2.2" - resolved "https://registry.yarnpkg.com/@scure/bip39/-/bip39-1.2.2.tgz#f3426813f4ced11a47489cbcf7294aa963966527" - integrity sha512-HYf9TUXG80beW+hGAt3TRM8wU6pQoYur9iNypTROm42dorCGmLnFe3eWjz3gOq6G62H2WRh0FCzAR1PI+29zIA== +"@scure/bip39@1.3.0": + version "1.3.0" + resolved "https://registry.yarnpkg.com/@scure/bip39/-/bip39-1.3.0.tgz#0f258c16823ddd00739461ac31398b4e7d6a18c3" + integrity sha512-disdg7gHuTDZtY+ZdkmLpPCk7fxZSu3gBiEGuoC1XYxv9cGx3Z6cpTggCgW6odSOOIXCiDjuGejW+aJKCY/pIQ== dependencies: - "@noble/hashes" "~1.3.2" - "@scure/base" "~1.1.4" + "@noble/hashes" "~1.4.0" + "@scure/base" "~1.1.6" -"@tornado/contracts@^1.0.0": +"@tornado/contracts@git+https://codeberg.org/tornadocash/tornado-contracts.git#6741664a898c1654e742459a2c20e52e4bc104fa": version "1.0.0" - resolved "https://git.tornado.ws/api/packages/tornado-packages/npm/%40tornado%2Fcontracts/-/1.0.0/contracts-1.0.0.tgz#4ee8aada3d12bca94b641fbb3d6f552ec3838cbe" - integrity sha512-kdYoEV+9Wm6sTpY4x4I1AB1cNYZ5yS/DehDxzv0cq06a6/80vncnpG22gM9CxkKqqsQb40O8yDSPxIDEFFwi3w== + resolved "git+https://codeberg.org/tornadocash/tornado-contracts.git#6741664a898c1654e742459a2c20e52e4bc104fa" dependencies: "@openzeppelin/contracts" "5.0.2" "@openzeppelin/contracts-v3" "npm:@openzeppelin/contracts@3.2.0-rc.0" ethers "^6.4.0" -"@tornado/fixed-merkle-tree@^0.7.3": +"@tornado/fixed-merkle-tree@git+https://codeberg.org/tornadocash/fixed-merkle-tree.git#5c3fca4cb11255760ad5f4fd95d7c6eb45c1fc99": version "0.7.3" - resolved "https://git.tornado.ws/api/packages/tornado-packages/npm/%40tornado%2Ffixed-merkle-tree/-/0.7.3/fixed-merkle-tree-0.7.3.tgz#6636ce9d334553c5f17e5a564fd22f2e9ec04472" - integrity sha512-8UWvIzz0/rMGBkzXACwmCv/5I1VJmnshAKc4C+nkTfOdmnX8Pf1bBa0GlxUIZ25ZFGiU/h2IKEHYckmHovwzEA== + resolved "git+https://codeberg.org/tornadocash/fixed-merkle-tree.git#5c3fca4cb11255760ad5f4fd95d7c6eb45c1fc99" -"@tornado/snarkjs@^0.1.20": +"@tornado/snarkjs@git+https://codeberg.org/tornadocash/snarkjs.git#d3915a760c437cde7bd317f9ea2c627954900656": version "0.1.20" - resolved "https://git.tornado.ws/api/packages/tornado-packages/npm/%40tornado%2Fsnarkjs/-/0.1.20/snarkjs-0.1.20.tgz#d7610cd3c8dc10598da7dc3e40e5d7470c3aa8c7" - integrity sha512-mn+ePoQjqOHyDyK8AMy8SXYqNSxJWVswWVmMYvuc75/9bBtJ7SNtwrTByxmfWjrf4S3BM3IrGfHqBHEXY6gR4Q== + resolved "git+https://codeberg.org/tornadocash/snarkjs.git#d3915a760c437cde7bd317f9ea2c627954900656" dependencies: big-integer "^1.6.43" chai "^4.2.0" @@ -883,12 +912,11 @@ keccak "^2.0.0" yargs "^12.0.5" -"@tornado/websnark@^0.0.4": +"@tornado/websnark@git+https://codeberg.org/tornadocash/websnark.git#b0c9fce5359ceba55167a2ad01a29d1e137843ec": version "0.0.4" - resolved "https://git.tornado.ws/api/packages/tornado-packages/npm/%40tornado%2Fwebsnark/-/0.0.4/websnark-0.0.4.tgz#4c603259b71172225a70e3d454344fa172710970" - integrity sha512-dHbaS41ILPq5NyVBDW8AmUPoSKvamtkTeIhyuKKmoyOrZMAUhJ9y1B2zRcejUKfhCZkIjAgCt9bvdzdOGGswwQ== + resolved "git+https://codeberg.org/tornadocash/websnark.git#b0c9fce5359ceba55167a2ad01a29d1e137843ec" dependencies: - "@tornado/snarkjs" "^0.1.20" + "@tornado/snarkjs" "git+https://codeberg.org/tornadocash/snarkjs.git#d3915a760c437cde7bd317f9ea2c627954900656" big-integer "1.6.42" "@typechain/ethers-v6@^0.5.1": @@ -899,10 +927,10 @@ lodash "^4.17.15" ts-essentials "^7.0.1" -"@types/bn.js@^5.1.5": - version "5.1.5" - resolved "https://registry.yarnpkg.com/@types/bn.js/-/bn.js-5.1.5.tgz#2e0dacdcce2c0f16b905d20ff87aedbc6f7b4bf0" - integrity sha512-V46N0zwKRF5Q00AZ6hWtN0T8gGmDUaUzLWQvHFo5yThtVwK/VCenFY3wXVbOvNfajEpsTfQM4IN9k/d6gUVX3A== +"@types/bn.js@^5.1.6": + version "5.1.6" + resolved "https://registry.yarnpkg.com/@types/bn.js/-/bn.js-5.1.6.tgz#9ba818eec0c85e4d3c679518428afdf611d03203" + integrity sha512-Xh8vSwUeMKeYYrj3cX4lGQgFSF/N03r+tv4AiLl1SucqV+uTQpxRcnM8AkXKHwYP9ZPXOYXRr2KPXpVlIvqh9w== dependencies: "@types/node" "*" @@ -918,28 +946,17 @@ dependencies: "@types/ms" "*" -"@types/eslint-scope@^3.7.3": - version "3.7.7" - resolved "https://registry.yarnpkg.com/@types/eslint-scope/-/eslint-scope-3.7.7.tgz#3108bd5f18b0cdb277c867b3dd449c9ed7079ac5" - integrity sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg== - dependencies: - "@types/eslint" "*" - "@types/estree" "*" +"@types/estree@*", "@types/estree@^1.0.0", "@types/estree@^1.0.5": + version "1.0.6" + resolved "https://registry.yarnpkg.com/@types/estree/-/estree-1.0.6.tgz#628effeeae2064a1b4e79f78e81d87b7e5fc7b50" + integrity sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw== -"@types/eslint@*": - version "8.56.10" - resolved "https://registry.yarnpkg.com/@types/eslint/-/eslint-8.56.10.tgz#eb2370a73bf04a901eeba8f22595c7ee0f7eb58d" - integrity sha512-Shavhk87gCtY2fhXDctcfS3e6FdxWkCx1iUZ9eEUbh7rTqlZT0/IzOkCOVt0fCjcFuZ9FPYfuezTBImfHCDBGQ== - dependencies: - "@types/estree" "*" - "@types/json-schema" "*" - -"@types/estree@*", "@types/estree@1.0.5", "@types/estree@^1.0.0", "@types/estree@^1.0.5": +"@types/estree@1.0.5": version "1.0.5" resolved "https://registry.yarnpkg.com/@types/estree/-/estree-1.0.5.tgz#a6ce3e556e00fd9895dd872dd172ad0d4bd687f4" integrity sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw== -"@types/json-schema@*", "@types/json-schema@^7.0.15", "@types/json-schema@^7.0.8": +"@types/json-schema@^7.0.8": version "7.0.15" resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.15.tgz#596a1747233694d50f6ad8a7869fcb6f56cf5841" integrity sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA== @@ -962,12 +979,12 @@ "@types/node" "*" form-data "^4.0.0" -"@types/node@*", "@types/node@^20.12.5": - version "20.12.5" - resolved "https://registry.yarnpkg.com/@types/node/-/node-20.12.5.tgz#74c4f31ab17955d0b5808cdc8fd2839526ad00b3" - integrity sha512-BD+BjQ9LS/D8ST9p5uqBxghlN+S42iuNxjsUGjeZobe/ciXzk2qb1B6IXc6AnRLS+yFJRpN2IPEHMzwspfDJNw== +"@types/node@*", "@types/node@^22.5.5": + version "22.5.5" + resolved "https://registry.yarnpkg.com/@types/node/-/node-22.5.5.tgz#52f939dd0f65fc552a4ad0b392f3c466cc5d7a44" + integrity sha512-Xjs4y5UPO/CLdzpgR6GirZJx36yScjh73+2NlLlkFRSoQN8B0DpfXPdZGnvVmLRLOsqDpOfTNv7D9trgGhmOIA== dependencies: - undici-types "~5.26.4" + undici-types "~6.19.2" "@types/node@18.15.13": version "18.15.13" @@ -984,95 +1001,85 @@ resolved "https://registry.yarnpkg.com/@types/resolve/-/resolve-1.20.2.tgz#97d26e00cd4a0423b4af620abecf3e6f442b7975" integrity sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q== -"@types/semver@^7.5.8": - version "7.5.8" - resolved "https://registry.yarnpkg.com/@types/semver/-/semver-7.5.8.tgz#8268a8c57a3e4abd25c165ecd36237db7948a55e" - integrity sha512-I8EUhyrgfLrcTkzV3TSsGyl1tSuPrEDzr0yd5m90UgNxQkyDXULk3b6MlQqTCpZpNtWe1K0hzclnZkTcLBe2UQ== - -"@typescript-eslint/eslint-plugin@^7.6.0": - version "7.6.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.6.0.tgz#1f5df5cda490a0bcb6fbdd3382e19f1241024242" - integrity sha512-gKmTNwZnblUdnTIJu3e9kmeRRzV2j1a/LUO27KNNAnIC5zjy1aSvXSRp4rVNlmAoHlQ7HzX42NbKpcSr4jF80A== +"@typescript-eslint/eslint-plugin@8.6.0": + version "8.6.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.6.0.tgz#20049754ff9f6d3a09bf240297f029ce04290999" + integrity sha512-UOaz/wFowmoh2G6Mr9gw60B1mm0MzUtm6Ic8G2yM1Le6gyj5Loi/N+O5mocugRGY+8OeeKmkMmbxNqUCq3B4Sg== dependencies: "@eslint-community/regexpp" "^4.10.0" - "@typescript-eslint/scope-manager" "7.6.0" - "@typescript-eslint/type-utils" "7.6.0" - "@typescript-eslint/utils" "7.6.0" - "@typescript-eslint/visitor-keys" "7.6.0" - debug "^4.3.4" + "@typescript-eslint/scope-manager" "8.6.0" + "@typescript-eslint/type-utils" "8.6.0" + "@typescript-eslint/utils" "8.6.0" + "@typescript-eslint/visitor-keys" "8.6.0" graphemer "^1.4.0" ignore "^5.3.1" natural-compare "^1.4.0" - semver "^7.6.0" ts-api-utils "^1.3.0" -"@typescript-eslint/parser@^7.6.0": - version "7.6.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-7.6.0.tgz#0aca5de3045d68b36e88903d15addaf13d040a95" - integrity sha512-usPMPHcwX3ZoPWnBnhhorc14NJw9J4HpSXQX4urF2TPKG0au0XhJoZyX62fmvdHONUkmyUe74Hzm1//XA+BoYg== +"@typescript-eslint/parser@^8.6.0": + version "8.6.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-8.6.0.tgz#02e092b9dc8b4e319172af620d0d39b337d948f6" + integrity sha512-eQcbCuA2Vmw45iGfcyG4y6rS7BhWfz9MQuk409WD47qMM+bKCGQWXxvoOs1DUp+T7UBMTtRTVT+kXr7Sh4O9Ow== dependencies: - "@typescript-eslint/scope-manager" "7.6.0" - "@typescript-eslint/types" "7.6.0" - "@typescript-eslint/typescript-estree" "7.6.0" - "@typescript-eslint/visitor-keys" "7.6.0" + "@typescript-eslint/scope-manager" "8.6.0" + "@typescript-eslint/types" "8.6.0" + "@typescript-eslint/typescript-estree" "8.6.0" + "@typescript-eslint/visitor-keys" "8.6.0" debug "^4.3.4" -"@typescript-eslint/scope-manager@7.6.0": - version "7.6.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-7.6.0.tgz#1e9972f654210bd7500b31feadb61a233f5b5e9d" - integrity sha512-ngttyfExA5PsHSx0rdFgnADMYQi+Zkeiv4/ZxGYUWd0nLs63Ha0ksmp8VMxAIC0wtCFxMos7Lt3PszJssG/E6w== +"@typescript-eslint/scope-manager@8.6.0": + version "8.6.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-8.6.0.tgz#28cc2fc26a84b75addf45091a2c6283e29e2c982" + integrity sha512-ZuoutoS5y9UOxKvpc/GkvF4cuEmpokda4wRg64JEia27wX+PysIE9q+lzDtlHHgblwUWwo5/Qn+/WyTUvDwBHw== dependencies: - "@typescript-eslint/types" "7.6.0" - "@typescript-eslint/visitor-keys" "7.6.0" + "@typescript-eslint/types" "8.6.0" + "@typescript-eslint/visitor-keys" "8.6.0" -"@typescript-eslint/type-utils@7.6.0": - version "7.6.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/type-utils/-/type-utils-7.6.0.tgz#644f75075f379827d25fe0713e252ccd4e4a428c" - integrity sha512-NxAfqAPNLG6LTmy7uZgpK8KcuiS2NZD/HlThPXQRGwz6u7MDBWRVliEEl1Gj6U7++kVJTpehkhZzCJLMK66Scw== +"@typescript-eslint/type-utils@8.6.0": + version "8.6.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/type-utils/-/type-utils-8.6.0.tgz#d4347e637478bef88cee1db691fcfa20ade9b8a0" + integrity sha512-dtePl4gsuenXVwC7dVNlb4mGDcKjDT/Ropsk4za/ouMBPplCLyznIaR+W65mvCvsyS97dymoBRrioEXI7k0XIg== dependencies: - "@typescript-eslint/typescript-estree" "7.6.0" - "@typescript-eslint/utils" "7.6.0" + "@typescript-eslint/typescript-estree" "8.6.0" + "@typescript-eslint/utils" "8.6.0" debug "^4.3.4" ts-api-utils "^1.3.0" -"@typescript-eslint/types@7.6.0": - version "7.6.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-7.6.0.tgz#53dba7c30c87e5f10a731054266dd905f1fbae38" - integrity sha512-h02rYQn8J+MureCvHVVzhl69/GAfQGPQZmOMjG1KfCl7o3HtMSlPaPUAPu6lLctXI5ySRGIYk94clD/AUMCUgQ== +"@typescript-eslint/types@8.6.0": + version "8.6.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-8.6.0.tgz#cdc3a16f83f2f0663d6723e9fd032331cdd9f51c" + integrity sha512-rojqFZGd4MQxw33SrOy09qIDS8WEldM8JWtKQLAjf/X5mGSeEFh5ixQlxssMNyPslVIk9yzWqXCsV2eFhYrYUw== -"@typescript-eslint/typescript-estree@7.6.0": - version "7.6.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-7.6.0.tgz#112a3775563799fd3f011890ac8322f80830ac17" - integrity sha512-+7Y/GP9VuYibecrCQWSKgl3GvUM5cILRttpWtnAu8GNL9j11e4tbuGZmZjJ8ejnKYyBRb2ddGQ3rEFCq3QjMJw== +"@typescript-eslint/typescript-estree@8.6.0": + version "8.6.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-8.6.0.tgz#f945506de42871f04868371cb5bf21e8f7266e01" + integrity sha512-MOVAzsKJIPIlLK239l5s06YXjNqpKTVhBVDnqUumQJja5+Y94V3+4VUFRA0G60y2jNnTVwRCkhyGQpavfsbq/g== dependencies: - "@typescript-eslint/types" "7.6.0" - "@typescript-eslint/visitor-keys" "7.6.0" + "@typescript-eslint/types" "8.6.0" + "@typescript-eslint/visitor-keys" "8.6.0" debug "^4.3.4" - globby "^11.1.0" + fast-glob "^3.3.2" is-glob "^4.0.3" minimatch "^9.0.4" semver "^7.6.0" ts-api-utils "^1.3.0" -"@typescript-eslint/utils@7.6.0": - version "7.6.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/utils/-/utils-7.6.0.tgz#e400d782280b6f724c8a1204269d984c79202282" - integrity sha512-x54gaSsRRI+Nwz59TXpCsr6harB98qjXYzsRxGqvA5Ue3kQH+FxS7FYU81g/omn22ML2pZJkisy6Q+ElK8pBCA== +"@typescript-eslint/utils@8.6.0": + version "8.6.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/utils/-/utils-8.6.0.tgz#175fe893f32804bed1e72b3364ea6bbe1044181c" + integrity sha512-eNp9cWnYf36NaOVjkEUznf6fEgVy1TWpE0o52e4wtojjBx7D1UV2WAWGzR+8Y5lVFtpMLPwNbC67T83DWSph4A== dependencies: "@eslint-community/eslint-utils" "^4.4.0" - "@types/json-schema" "^7.0.15" - "@types/semver" "^7.5.8" - "@typescript-eslint/scope-manager" "7.6.0" - "@typescript-eslint/types" "7.6.0" - "@typescript-eslint/typescript-estree" "7.6.0" - semver "^7.6.0" + "@typescript-eslint/scope-manager" "8.6.0" + "@typescript-eslint/types" "8.6.0" + "@typescript-eslint/typescript-estree" "8.6.0" -"@typescript-eslint/visitor-keys@7.6.0": - version "7.6.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-7.6.0.tgz#d1ce13145844379021e1f9bd102c1d78946f4e76" - integrity sha512-4eLB7t+LlNUmXzfOu1VAIAdkjbu5xNSerURS9X/S5TUKWFRpXRQZbmtPqgKmYx8bj3J0irtQXSiWAOY82v+cgw== +"@typescript-eslint/visitor-keys@8.6.0": + version "8.6.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-8.6.0.tgz#5432af4a1753f376f35ab5b891fc9db237aaf76f" + integrity sha512-wapVFfZg9H0qOYh4grNVQiMklJGluQrOUiOhYRrQWhx7BY/+I1IYb8BczWNbbUpO+pqy0rDciv3lQH5E1bCLrg== dependencies: - "@typescript-eslint/types" "7.6.0" + "@typescript-eslint/types" "8.6.0" eslint-visitor-keys "^3.4.3" "@ungap/structured-clone@^1.2.0": @@ -1233,10 +1240,10 @@ abort-controller@^3.0.0: dependencies: event-target-shim "^5.0.0" -acorn-import-assertions@^1.9.0: - version "1.9.0" - resolved "https://registry.yarnpkg.com/acorn-import-assertions/-/acorn-import-assertions-1.9.0.tgz#507276249d684797c84e0734ef84860334cfb1ac" - integrity sha512-cmMwop9x+8KFhxvKrKfPYmN6/pKTYYHBqLa0DfvVZcKMJWNyWLnaqND7dx/qn66R7ewM1UX5XMaDVP5wlVTaVA== +acorn-import-attributes@^1.9.5: + version "1.9.5" + resolved "https://registry.yarnpkg.com/acorn-import-attributes/-/acorn-import-attributes-1.9.5.tgz#7eb1557b1ba05ef18b5ed0ec67591bfab04688ef" + integrity sha512-n02Vykv5uA3eHGM/Z2dQrcD56kL8TyDb2p1+0P83PClMnC/nc+anbQRhIOWnSq4Ke/KvDPrY3C9hDtC/A3eHnQ== acorn-jsx@^5.0.0, acorn-jsx@^5.3.2: version "5.3.2" @@ -1249,9 +1256,9 @@ acorn@^6.0.7: integrity sha512-XtGIhXwF8YM8bJhGxG5kXgjkEuNGLTkoYqVE+KMR+aspr4KGYmKYg7yUe3KghyQ9yheNwLnjmzh/7+gfDBmHCQ== acorn@^8.7.1, acorn@^8.8.2, acorn@^8.9.0: - version "8.11.3" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.11.3.tgz#71e0b14e13a4ec160724b38fb7b0f233b1b81d7a" - integrity sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg== + version "8.12.1" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.12.1.tgz#71616bdccbe25e27a54439e0046e89ca76df2248" + integrity sha512-tcpGyI9zbizT9JbV6oYE477V6mTlXvvi0T0G3SNIYE2apm/G5huBa1+K89VGeovbg+jycCrfhl3ADxErOuO6Jg== aes-js@3.0.0: version "3.0.0" @@ -1278,15 +1285,15 @@ ajv@^6.10.2, ajv@^6.12.4, ajv@^6.12.5, ajv@^6.9.1: json-schema-traverse "^0.4.1" uri-js "^4.2.2" -ajv@^8.12.0: - version "8.12.0" - resolved "https://registry.yarnpkg.com/ajv/-/ajv-8.12.0.tgz#d1a0527323e22f53562c567c00991577dfbe19d1" - integrity sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA== +ajv@^8.17.1: + version "8.17.1" + resolved "https://registry.yarnpkg.com/ajv/-/ajv-8.17.1.tgz#37d9a5c776af6bc92d7f4f9510eba4c0a60d11a6" + integrity sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g== dependencies: - fast-deep-equal "^3.1.1" + fast-deep-equal "^3.1.3" + fast-uri "^3.0.1" json-schema-traverse "^1.0.0" require-from-string "^2.0.2" - uri-js "^4.2.2" ansi-escapes@^3.2.0: version "3.2.0" @@ -1313,6 +1320,11 @@ ansi-regex@^5.0.1: resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304" integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ== +ansi-regex@^6.0.1: + version "6.1.0" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-6.1.0.tgz#95ec409c69619d6cb1b8b34f14b660ef28ebd654" + integrity sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA== + ansi-styles@^3.2.0, ansi-styles@^3.2.1: version "3.2.1" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" @@ -1320,13 +1332,18 @@ ansi-styles@^3.2.0, ansi-styles@^3.2.1: dependencies: color-convert "^1.9.0" -ansi-styles@^4.1.0: +ansi-styles@^4.0.0, ansi-styles@^4.1.0: version "4.3.0" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-4.3.0.tgz#edd803628ae71c04c85ae7a0906edad34b648937" integrity sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg== dependencies: color-convert "^2.0.1" +ansi-styles@^6.1.0: + version "6.2.1" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-6.2.1.tgz#0e62320cf99c21afff3b3012192546aacbfb05c5" + integrity sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug== + argparse@^1.0.7: version "1.0.10" resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911" @@ -1357,7 +1374,7 @@ array-buffer-byte-length@^1.0.1: call-bind "^1.0.5" is-array-buffer "^3.0.4" -array-includes@^3.1.7: +array-includes@^3.1.8: version "3.1.8" resolved "https://registry.yarnpkg.com/array-includes/-/array-includes-3.1.8.tgz#5e370cbe172fdd5dd6530c1d4aadda25281ba97d" integrity sha512-itaWrbYbqpGXkGhZPGUulwnhVf5Hpy1xiCFsGqyIGglbBxmG5vSjxQen3/WGOjPpNEv1RtBLKxbmVXm8HpJStQ== @@ -1369,12 +1386,7 @@ array-includes@^3.1.7: get-intrinsic "^1.2.4" is-string "^1.0.7" -array-union@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/array-union/-/array-union-2.1.0.tgz#b798420adbeb1de828d84acd8a2e23d3efe85e8d" - integrity sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw== - -array.prototype.findlastindex@^1.2.3: +array.prototype.findlastindex@^1.2.5: version "1.2.5" resolved "https://registry.yarnpkg.com/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.5.tgz#8c35a755c72908719453f87145ca011e39334d0d" integrity sha512-zfETvRFA8o7EiNn++N5f/kaCw221hrpGsDmcpndVupkPzEc1Wuf3VgC0qby1BbHs7f5DVYjgtEU2LLh5bqeGfQ== @@ -1559,12 +1571,12 @@ brace-expansion@^2.0.1: dependencies: balanced-match "^1.0.0" -braces@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.2.tgz#3454e1a462ee8d599e236df336cd9ea4f8afe107" - integrity sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A== +braces@^3.0.3: + version "3.0.3" + resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.3.tgz#490332f40919452272d55a8480adc0c441358789" + integrity sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA== dependencies: - fill-range "^7.0.1" + fill-range "^7.1.1" brorand@^1.0.1, brorand@^1.1.0: version "1.1.0" @@ -1634,14 +1646,14 @@ browserify-zlib@^0.2.0: pako "~1.0.5" browserslist@^4.21.10: - version "4.23.0" - resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.23.0.tgz#8f3acc2bbe73af7213399430890f86c63a5674ab" - integrity sha512-QW8HiM1shhT2GuzkvklfjcKDiWFXHOeFCIA/huJPwHsslwcydgk7X+z2zXpEijP98UCY7HbubZt5J2Zgvf0CaQ== + version "4.23.3" + resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.23.3.tgz#debb029d3c93ebc97ffbc8d9cbb03403e227c800" + integrity sha512-btwCFJVjI4YWDNfau8RhZ+B1Q/VLoUITrm3RlP6y1tYGWIOa+InuYiRGXUBXo8nA1qKmHMyLB/iVQg5TT4eFoA== dependencies: - caniuse-lite "^1.0.30001587" - electron-to-chromium "^1.4.668" - node-releases "^2.0.14" - update-browserslist-db "^1.0.13" + caniuse-lite "^1.0.30001646" + electron-to-chromium "^1.5.4" + node-releases "^2.0.18" + update-browserslist-db "^1.1.0" buffer-from@^1.0.0: version "1.1.2" @@ -1692,15 +1704,15 @@ camelcase@^5.0.0: resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-5.3.1.tgz#e3c9b31569e106811df242f715725a1f4c494320" integrity sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg== -caniuse-lite@^1.0.30001587: - version "1.0.30001612" - resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001612.tgz#d34248b4ec1f117b70b24ad9ee04c90e0b8a14ae" - integrity sha512-lFgnZ07UhaCcsSZgWW0K5j4e69dK1u/ltrL9lTUiFOwNHs12S3UMIEYgBV0Z6C6hRDev7iRnMzzYmKabYdXF9g== +caniuse-lite@^1.0.30001646: + version "1.0.30001662" + resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001662.tgz#3574b22dfec54a3f3b6787331da1040fe8e763ec" + integrity sha512-sgMUVwLmGseH8ZIrm1d51UbrhqMCH3jvS7gF/M6byuHOnKyLOBL7W8yz5V02OHwgLGA36o/AFhWzzh4uc5aqTA== chai@^4.2.0: - version "4.4.1" - resolved "https://registry.yarnpkg.com/chai/-/chai-4.4.1.tgz#3603fa6eba35425b0f2ac91a009fe924106e50d1" - integrity sha512-13sOfMv2+DWduEU+/xbun3LScLoqN17nBeTLUsmDfKdoiC1fr0n9PU4guu4AhRcOVFk/sW8LyZWHuhWtQZiF+g== + version "4.5.0" + resolved "https://registry.yarnpkg.com/chai/-/chai-4.5.0.tgz#707e49923afdd9b13a8b0b47d33d732d13812fd8" + integrity sha512-RITGBfijLkBddZvnn8jdqoTypxvqbOLYQkGGxXzeFjVHvudaPw0HNFD9x928/eUwYWd2dPCugVqspGALTZZQKw== dependencies: assertion-error "^1.1.0" check-error "^1.0.3" @@ -1708,7 +1720,7 @@ chai@^4.2.0: get-func-name "^2.0.2" loupe "^2.3.6" pathval "^1.1.1" - type-detect "^4.0.8" + type-detect "^4.1.0" chalk@^2.1.0, chalk@^2.4.2: version "2.4.2" @@ -1740,9 +1752,9 @@ check-error@^1.0.3: get-func-name "^2.0.2" chrome-trace-event@^1.0.2: - version "1.0.3" - resolved "https://registry.yarnpkg.com/chrome-trace-event/-/chrome-trace-event-1.0.3.tgz#1015eced4741e15d06664a957dbbf50d041e26ac" - integrity sha512-p3KULyQg4S7NIHixdwbGX+nFHkoBiA4YQmyWtjb8XngSKV124nJmRysgAeujbUVb15vh+RvFUfCPqU7rXk+hZg== + version "1.0.4" + resolved "https://registry.yarnpkg.com/chrome-trace-event/-/chrome-trace-event-1.0.4.tgz#05bffd7ff928465093314708c93bdfa9bd1f0f5b" + integrity sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ== cipher-base@^1.0.0, cipher-base@^1.0.1, cipher-base@^1.0.3: version "1.0.4" @@ -1942,7 +1954,7 @@ cross-spawn@^6.0.0, cross-spawn@^6.0.5: shebang-command "^1.2.0" which "^1.2.9" -cross-spawn@^7.0.2, cross-spawn@^7.0.3: +cross-spawn@^7.0.0, cross-spawn@^7.0.2, cross-spawn@^7.0.3: version "7.0.3" resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.3.tgz#f73a85b9d5d41d045551c177e2882d4ac85728a6" integrity sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w== @@ -2002,12 +2014,12 @@ debug@^3.2.7: dependencies: ms "^2.1.1" -debug@^4.0.1, debug@^4.3.1, debug@^4.3.2, debug@^4.3.4: - version "4.3.4" - resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.4.tgz#1319f6579357f2338d3337d2cdd4914bb5dcc865" - integrity sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ== +debug@^4.0.1, debug@^4.3.1, debug@^4.3.2, debug@^4.3.4, debug@^4.3.5: + version "4.3.7" + resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.7.tgz#87945b4151a011d76d95a198d7111c865c360a52" + integrity sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ== dependencies: - ms "2.1.2" + ms "^2.1.3" decamelize@^1.2.0: version "1.2.0" @@ -2015,9 +2027,9 @@ decamelize@^1.2.0: integrity sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA== deep-eql@^4.1.3: - version "4.1.3" - resolved "https://registry.yarnpkg.com/deep-eql/-/deep-eql-4.1.3.tgz#7c7775513092f7df98d8df9996dd085eb668cc6d" - integrity sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw== + version "4.1.4" + resolved "https://registry.yarnpkg.com/deep-eql/-/deep-eql-4.1.4.tgz#d0d3912865911bb8fac5afb4e3acfa6a28dc72b7" + integrity sha512-SUwdGfqdKOwxCPeVYjwSyRpJ7Z+fhpwIAtmCUdZIWZ/YP5R9WAsyuSgpLVDi9bjWoN2LXHNss/dk3urXtdQxGg== dependencies: type-detect "^4.0.0" @@ -2076,13 +2088,6 @@ diffie-hellman@^5.0.0: miller-rabin "^4.0.0" randombytes "^2.0.0" -dir-glob@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/dir-glob/-/dir-glob-3.0.1.tgz#56dbf73d992a4a93ba1584f4534063fd2e41717f" - integrity sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA== - dependencies: - path-type "^4.0.0" - doctrine@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-2.1.0.tgz#5cd01fc101621b42c4cd7f5d1a66243716d3f39d" @@ -2097,15 +2102,20 @@ doctrine@^3.0.0: dependencies: esutils "^2.0.2" -domain-browser@^4.22.0: - version "4.23.0" - resolved "https://registry.yarnpkg.com/domain-browser/-/domain-browser-4.23.0.tgz#427ebb91efcb070f05cffdfb8a4e9a6c25f8c94b" - integrity sha512-ArzcM/II1wCCujdCNyQjXrAFwS4mrLh4C7DZWlaI8mdh7h3BfKdNd3bKXITfl2PT9FtfQqaGvhi1vPRQPimjGA== +domain-browser@^5.7.0: + version "5.7.0" + resolved "https://registry.yarnpkg.com/domain-browser/-/domain-browser-5.7.0.tgz#81b942459672e3c7ed8f721fe31135a5628f31cf" + integrity sha512-edTFu0M/7wO1pXY6GDxVNVW086uqwWYIHP98txhcPyV995X21JIH2DtYp33sQJOupYoXKe9RwTw2Ya2vWaquTQ== -electron-to-chromium@^1.4.668: - version "1.4.748" - resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.748.tgz#aa7d4f2f3eac3a6a863cd1779bd4682b4bb68ed5" - integrity sha512-VWqjOlPZn70UZ8FTKUOkUvBLeTQ0xpty66qV0yJcAGY2/CthI4xyW9aEozRVtuwv3Kpf5xTesmJUcPwuJmgP4A== +eastasianwidth@^0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/eastasianwidth/-/eastasianwidth-0.2.0.tgz#696ce2ec0aa0e6ea93a397ffcf24aa7840c827cb" + integrity sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA== + +electron-to-chromium@^1.5.4: + version "1.5.25" + resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.5.25.tgz#492ade1cde401332b9b75aa0c55fd5e1550ca66c" + integrity sha512-kMb204zvK3PsSlgvvwzI3wBIcAw15tRkYk+NQdsjdDtcQWTp2RABbMQ9rUBy8KNEOM+/E6ep+XC3AykiWZld4g== elliptic@6.5.4: version "6.5.4" @@ -2121,9 +2131,9 @@ elliptic@6.5.4: minimalistic-crypto-utils "^1.0.1" elliptic@^6.5.3, elliptic@^6.5.5: - version "6.5.5" - resolved "https://registry.yarnpkg.com/elliptic/-/elliptic-6.5.5.tgz#c715e09f78b6923977610d4c2346d6ce22e6dded" - integrity sha512-7EjbcmUm17NQFu4Pmgmq2olYMj8nwMnpcddByChSUjArp8F5DQWcIcpriwO4ZToLNAJig0yiyjswfyGNje/ixw== + version "6.5.7" + resolved "https://registry.yarnpkg.com/elliptic/-/elliptic-6.5.7.tgz#8ec4da2cb2939926a1b9a73619d768207e647c8b" + integrity sha512-ESVCtTwiA+XhY3wyh24QqRGBoP3rEdDUl3EDUUo9tft074fi19IrdpH7hLCMMP3CIj7jb3W96rn8lt/BqIlt5Q== dependencies: bn.js "^4.11.9" brorand "^1.1.0" @@ -2138,6 +2148,16 @@ emoji-regex@^7.0.1: resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-7.0.3.tgz#933a04052860c85e83c122479c4748a8e4c72156" integrity sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA== +emoji-regex@^8.0.0: + version "8.0.0" + resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37" + integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A== + +emoji-regex@^9.2.2: + version "9.2.2" + resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-9.2.2.tgz#840c8803b0d8047f4ff0cf963176b32d4ef3ed72" + integrity sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg== + emojis-list@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/emojis-list/-/emojis-list-3.0.0.tgz#5570662046ad29e2e916e71aae260abdff4f6a78" @@ -2150,18 +2170,18 @@ end-of-stream@^1.1.0: dependencies: once "^1.4.0" -enhanced-resolve@^5.12.0, enhanced-resolve@^5.16.0: - version "5.16.0" - resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-5.16.0.tgz#65ec88778083056cb32487faa9aef82ed0864787" - integrity sha512-O+QWCviPNSSLAD9Ucn8Awv+poAkqn3T1XY5/N7kR7rQO9yfSGWkYZDwpJ+iKF7B8rxaQKWngSqACpgzeapSyoA== +enhanced-resolve@^5.15.0, enhanced-resolve@^5.17.1: + version "5.17.1" + resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-5.17.1.tgz#67bfbbcc2f81d511be77d686a90267ef7f898a15" + integrity sha512-LMHl3dXhTcfv8gM4kEzIUeTQ+7fpdA0l2tUf34BddXPkz2A5xJ5L/Pchd5BL6rdccM9QGvu0sWZzK1Z1t4wwyg== dependencies: graceful-fs "^4.2.4" tapable "^2.2.0" envinfo@^7.7.3: - version "7.12.0" - resolved "https://registry.yarnpkg.com/envinfo/-/envinfo-7.12.0.tgz#b56723b39c2053d67ea5714f026d05d4f5cc7acd" - integrity sha512-Iw9rQJBGpJRd3rwXm9ft/JiGoAZmLxxJZELYDQoPRZ4USVhkKtIcNBPw6U+/K2mBpaqM25JSV6Yl4Az9vO2wJg== + version "7.14.0" + resolved "https://registry.yarnpkg.com/envinfo/-/envinfo-7.14.0.tgz#26dac5db54418f2a4c1159153a0b2ae980838aae" + integrity sha512-CO40UI41xDQzhLB1hWyqUKgFhs250pNcGbyGKe1l/e4FSaI/+YE4IMG76GDt0In67WLPACIITC+sOi08x4wIvg== es-abstract@^1.22.1, es-abstract@^1.22.3, es-abstract@^1.23.0, es-abstract@^1.23.2: version "1.23.3" @@ -2228,9 +2248,9 @@ es-errors@^1.2.1, es-errors@^1.3.0: integrity sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw== es-module-lexer@^1.2.1, es-module-lexer@^1.3.1: - version "1.5.0" - resolved "https://registry.yarnpkg.com/es-module-lexer/-/es-module-lexer-1.5.0.tgz#4878fee3789ad99e065f975fdd3c645529ff0236" - integrity sha512-pqrTKmwEIgafsYZAGw9kszYzmagcE/n4dbgwGWLEXg7J4QFJVQRBld8j3Q3GNez79jzxZshq0bcT962QHOghjw== + version "1.5.4" + resolved "https://registry.yarnpkg.com/es-module-lexer/-/es-module-lexer-1.5.4.tgz#a8efec3a3da991e60efa6b633a7cad6ab8d26b78" + integrity sha512-MVNK56NiMrOwitFB7cqDwq0CQutbw+0BvLshJSse0MUNU+y1FC3bUS/AQg7oUng+/wKrrki7JfmwtVHkVfPLlw== es-object-atoms@^1.0.0: version "1.0.0" @@ -2264,49 +2284,49 @@ es-to-primitive@^1.2.1: is-date-object "^1.0.1" is-symbol "^1.0.2" -esbuild-loader@^4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/esbuild-loader/-/esbuild-loader-4.1.0.tgz#06bddf224320c279fafbe4981feb1a0175b593e4" - integrity sha512-543TtIvqbqouEMlOHg4xKoDQkmdImlwIpyAIgpUtDPvMuklU/c2k+Qt2O3VeDBgAwozxmlEbjOzV+F8CZ0g+Bw== +esbuild-loader@^4.2.2: + version "4.2.2" + resolved "https://registry.yarnpkg.com/esbuild-loader/-/esbuild-loader-4.2.2.tgz#cce9032097767d325d6aa231edbd7d66a5d7fa1b" + integrity sha512-Mdq/A1L8p37hkibp8jGFwuQTDSWhDmlueAefsrCPRwNWThEOlQmIglV7Gd6GE2mO5bt7ksfxKOMwkuY7jjVTXg== dependencies: - esbuild "^0.20.0" + esbuild "^0.21.0" get-tsconfig "^4.7.0" loader-utils "^2.0.4" webpack-sources "^1.4.3" -esbuild@^0.20.0, esbuild@^0.20.2: - version "0.20.2" - resolved "https://registry.yarnpkg.com/esbuild/-/esbuild-0.20.2.tgz#9d6b2386561766ee6b5a55196c6d766d28c87ea1" - integrity sha512-WdOOppmUNU+IbZ0PaDiTst80zjnrOkyJNHoKupIcVyU8Lvla3Ugx94VzkQ32Ijqd7UhHJy75gNWDMUekcrSJ6g== +esbuild@^0.21.0: + version "0.21.5" + resolved "https://registry.yarnpkg.com/esbuild/-/esbuild-0.21.5.tgz#9ca301b120922959b766360d8ac830da0d02997d" + integrity sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw== optionalDependencies: - "@esbuild/aix-ppc64" "0.20.2" - "@esbuild/android-arm" "0.20.2" - "@esbuild/android-arm64" "0.20.2" - "@esbuild/android-x64" "0.20.2" - "@esbuild/darwin-arm64" "0.20.2" - "@esbuild/darwin-x64" "0.20.2" - "@esbuild/freebsd-arm64" "0.20.2" - "@esbuild/freebsd-x64" "0.20.2" - "@esbuild/linux-arm" "0.20.2" - "@esbuild/linux-arm64" "0.20.2" - "@esbuild/linux-ia32" "0.20.2" - "@esbuild/linux-loong64" "0.20.2" - "@esbuild/linux-mips64el" "0.20.2" - "@esbuild/linux-ppc64" "0.20.2" - "@esbuild/linux-riscv64" "0.20.2" - "@esbuild/linux-s390x" "0.20.2" - "@esbuild/linux-x64" "0.20.2" - "@esbuild/netbsd-x64" "0.20.2" - "@esbuild/openbsd-x64" "0.20.2" - "@esbuild/sunos-x64" "0.20.2" - "@esbuild/win32-arm64" "0.20.2" - "@esbuild/win32-ia32" "0.20.2" - "@esbuild/win32-x64" "0.20.2" + "@esbuild/aix-ppc64" "0.21.5" + "@esbuild/android-arm" "0.21.5" + "@esbuild/android-arm64" "0.21.5" + "@esbuild/android-x64" "0.21.5" + "@esbuild/darwin-arm64" "0.21.5" + "@esbuild/darwin-x64" "0.21.5" + "@esbuild/freebsd-arm64" "0.21.5" + "@esbuild/freebsd-x64" "0.21.5" + "@esbuild/linux-arm" "0.21.5" + "@esbuild/linux-arm64" "0.21.5" + "@esbuild/linux-ia32" "0.21.5" + "@esbuild/linux-loong64" "0.21.5" + "@esbuild/linux-mips64el" "0.21.5" + "@esbuild/linux-ppc64" "0.21.5" + "@esbuild/linux-riscv64" "0.21.5" + "@esbuild/linux-s390x" "0.21.5" + "@esbuild/linux-x64" "0.21.5" + "@esbuild/netbsd-x64" "0.21.5" + "@esbuild/openbsd-x64" "0.21.5" + "@esbuild/sunos-x64" "0.21.5" + "@esbuild/win32-arm64" "0.21.5" + "@esbuild/win32-ia32" "0.21.5" + "@esbuild/win32-x64" "0.21.5" -escalade@^3.1.1: - version "3.1.2" - resolved "https://registry.yarnpkg.com/escalade/-/escalade-3.1.2.tgz#54076e9ab29ea5bf3d8f1ed62acffbb88272df27" - integrity sha512-ErCHMCae19vR8vQGe50xIsVomy19rg6gFu3+r3jkEO46suLMWBksvVyoGgQV+jOfl84ZSOSlmv6Gxa89PmTGmA== +escalade@^3.1.2: + version "3.2.0" + resolved "https://registry.yarnpkg.com/escalade/-/escalade-3.2.0.tgz#011a3f69856ba189dffa7dc8fcce99d2a87903e5" + integrity sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA== escape-string-regexp@^1.0.5: version "1.0.5" @@ -2332,56 +2352,58 @@ eslint-import-resolver-node@^0.3.9: is-core-module "^2.13.0" resolve "^1.22.4" -eslint-import-resolver-typescript@^3.6.1: - version "3.6.1" - resolved "https://registry.yarnpkg.com/eslint-import-resolver-typescript/-/eslint-import-resolver-typescript-3.6.1.tgz#7b983680edd3f1c5bce1a5829ae0bc2d57fe9efa" - integrity sha512-xgdptdoi5W3niYeuQxKmzVDTATvLYqhpwmykwsh7f6HIOStGWEIL9iqZgQDF9u9OEzrRwR8no5q2VT+bjAujTg== +eslint-import-resolver-typescript@^3.6.3: + version "3.6.3" + resolved "https://registry.yarnpkg.com/eslint-import-resolver-typescript/-/eslint-import-resolver-typescript-3.6.3.tgz#bb8e388f6afc0f940ce5d2c5fd4a3d147f038d9e" + integrity sha512-ud9aw4szY9cCT1EWWdGv1L1XR6hh2PaRWif0j2QjQ0pgTY/69iw+W0Z4qZv5wHahOl8isEr+k/JnyAqNQkLkIA== dependencies: - debug "^4.3.4" - enhanced-resolve "^5.12.0" - eslint-module-utils "^2.7.4" - fast-glob "^3.3.1" - get-tsconfig "^4.5.0" - is-core-module "^2.11.0" + "@nolyfill/is-core-module" "1.0.39" + debug "^4.3.5" + enhanced-resolve "^5.15.0" + eslint-module-utils "^2.8.1" + fast-glob "^3.3.2" + get-tsconfig "^4.7.5" + is-bun-module "^1.0.2" is-glob "^4.0.3" -eslint-module-utils@^2.7.4, eslint-module-utils@^2.8.0: - version "2.8.1" - resolved "https://registry.yarnpkg.com/eslint-module-utils/-/eslint-module-utils-2.8.1.tgz#52f2404300c3bd33deece9d7372fb337cc1d7c34" - integrity sha512-rXDXR3h7cs7dy9RNpUlQf80nX31XWJEyGq1tRMo+6GsO5VmTe4UTwtmonAD4ZkAsrfMVDA2wlGJ3790Ys+D49Q== +eslint-module-utils@^2.8.1, eslint-module-utils@^2.9.0: + version "2.11.0" + resolved "https://registry.yarnpkg.com/eslint-module-utils/-/eslint-module-utils-2.11.0.tgz#b99b211ca4318243f09661fae088f373ad5243c4" + integrity sha512-gbBE5Hitek/oG6MUVj6sFuzEjA/ClzNflVrLovHi/JgLdC7fiN5gLAY1WIPW1a0V5I999MnsrvVrCOGmmVqDBQ== dependencies: debug "^3.2.7" -eslint-plugin-import@^2.29.1: - version "2.29.1" - resolved "https://registry.yarnpkg.com/eslint-plugin-import/-/eslint-plugin-import-2.29.1.tgz#d45b37b5ef5901d639c15270d74d46d161150643" - integrity sha512-BbPC0cuExzhiMo4Ff1BTVwHpjjv28C5R+btTOGaCRC7UEz801up0JadwkeSk5Ued6TG34uaczuVuH6qyy5YUxw== +eslint-plugin-import@^2.30.0: + version "2.30.0" + resolved "https://registry.yarnpkg.com/eslint-plugin-import/-/eslint-plugin-import-2.30.0.tgz#21ceea0fc462657195989dd780e50c92fe95f449" + integrity sha512-/mHNE9jINJfiD2EKkg1BKyPyUk4zdnT54YgbOgfjSakWT5oyX/qQLVNTkehyfpcMxZXMy1zyonZ2v7hZTX43Yw== dependencies: - array-includes "^3.1.7" - array.prototype.findlastindex "^1.2.3" + "@rtsao/scc" "^1.1.0" + array-includes "^3.1.8" + array.prototype.findlastindex "^1.2.5" array.prototype.flat "^1.3.2" array.prototype.flatmap "^1.3.2" debug "^3.2.7" doctrine "^2.1.0" eslint-import-resolver-node "^0.3.9" - eslint-module-utils "^2.8.0" - hasown "^2.0.0" - is-core-module "^2.13.1" + eslint-module-utils "^2.9.0" + hasown "^2.0.2" + is-core-module "^2.15.1" is-glob "^4.0.3" minimatch "^3.1.2" - object.fromentries "^2.0.7" - object.groupby "^1.0.1" - object.values "^1.1.7" + object.fromentries "^2.0.8" + object.groupby "^1.0.3" + object.values "^1.2.0" semver "^6.3.1" tsconfig-paths "^3.15.0" -eslint-plugin-prettier@^5.1.3: - version "5.1.3" - resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-5.1.3.tgz#17cfade9e732cef32b5f5be53bd4e07afd8e67e1" - integrity sha512-C9GCVAs4Eq7ZC/XFQHITLiHJxQngdtraXaM+LoUFoFp/lHNl2Zn8f3WQbe9HvTBBQ9YnKFB0/2Ajdqwo5D1EAw== +eslint-plugin-prettier@^5.2.1: + version "5.2.1" + resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-5.2.1.tgz#d1c8f972d8f60e414c25465c163d16f209411f95" + integrity sha512-gH3iR3g4JfF+yYPaJYkN7jEl9QbweL/YfkoRlNnuIEHEz1vHVlCmWOS+eGGiRuzHQXdJFCOTxRgvju9b8VUmrw== dependencies: prettier-linter-helpers "^1.0.0" - synckit "^0.8.6" + synckit "^0.9.1" eslint-scope@5.1.1: version "5.1.1" @@ -2424,49 +2446,7 @@ eslint-visitor-keys@^3.3.0, eslint-visitor-keys@^3.4.1, eslint-visitor-keys@^3.4 resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz#0cd72fe8550e3c2eae156a96a4dddcd1c8ac5800" integrity sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag== -eslint@^5.16.0: - version "5.16.0" - resolved "https://registry.yarnpkg.com/eslint/-/eslint-5.16.0.tgz#a1e3ac1aae4a3fbd8296fcf8f7ab7314cbb6abea" - integrity sha512-S3Rz11i7c8AA5JPv7xAH+dOyq/Cu/VXHiHXBPOU1k/JAM5dXqQPt3qcrhpHSorXmrpu2g0gkIBVXAqCpzfoZIg== - dependencies: - "@babel/code-frame" "^7.0.0" - ajv "^6.9.1" - chalk "^2.1.0" - cross-spawn "^6.0.5" - debug "^4.0.1" - doctrine "^3.0.0" - eslint-scope "^4.0.3" - eslint-utils "^1.3.1" - eslint-visitor-keys "^1.0.0" - espree "^5.0.1" - esquery "^1.0.1" - esutils "^2.0.2" - file-entry-cache "^5.0.1" - functional-red-black-tree "^1.0.1" - glob "^7.1.2" - globals "^11.7.0" - ignore "^4.0.6" - import-fresh "^3.0.0" - imurmurhash "^0.1.4" - inquirer "^6.2.2" - js-yaml "^3.13.0" - json-stable-stringify-without-jsonify "^1.0.1" - levn "^0.3.0" - lodash "^4.17.11" - minimatch "^3.0.4" - mkdirp "^0.5.1" - natural-compare "^1.4.0" - optionator "^0.8.2" - path-is-inside "^1.0.2" - progress "^2.0.0" - regexpp "^2.0.1" - semver "^5.5.1" - strip-ansi "^4.0.0" - strip-json-comments "^2.0.1" - table "^5.2.3" - text-table "^0.2.0" - -eslint@^8.57.0: +eslint@8.57.0: version "8.57.0" resolved "https://registry.yarnpkg.com/eslint/-/eslint-8.57.0.tgz#c786a6fd0e0b68941aaf624596fb987089195668" integrity sha512-dZ6+mexnaTIbSBZWgou51U6OmzIhYM2VcNdtiTtI7qPNZm35Akpr0f6vtw3w1Kmn5PYo+tZVfh13WrhpS6oLqQ== @@ -2510,6 +2490,48 @@ eslint@^8.57.0: strip-ansi "^6.0.1" text-table "^0.2.0" +eslint@^5.16.0: + version "5.16.0" + resolved "https://registry.yarnpkg.com/eslint/-/eslint-5.16.0.tgz#a1e3ac1aae4a3fbd8296fcf8f7ab7314cbb6abea" + integrity sha512-S3Rz11i7c8AA5JPv7xAH+dOyq/Cu/VXHiHXBPOU1k/JAM5dXqQPt3qcrhpHSorXmrpu2g0gkIBVXAqCpzfoZIg== + dependencies: + "@babel/code-frame" "^7.0.0" + ajv "^6.9.1" + chalk "^2.1.0" + cross-spawn "^6.0.5" + debug "^4.0.1" + doctrine "^3.0.0" + eslint-scope "^4.0.3" + eslint-utils "^1.3.1" + eslint-visitor-keys "^1.0.0" + espree "^5.0.1" + esquery "^1.0.1" + esutils "^2.0.2" + file-entry-cache "^5.0.1" + functional-red-black-tree "^1.0.1" + glob "^7.1.2" + globals "^11.7.0" + ignore "^4.0.6" + import-fresh "^3.0.0" + imurmurhash "^0.1.4" + inquirer "^6.2.2" + js-yaml "^3.13.0" + json-stable-stringify-without-jsonify "^1.0.1" + levn "^0.3.0" + lodash "^4.17.11" + minimatch "^3.0.4" + mkdirp "^0.5.1" + natural-compare "^1.4.0" + optionator "^0.8.2" + path-is-inside "^1.0.2" + progress "^2.0.0" + regexpp "^2.0.1" + semver "^5.5.1" + strip-ansi "^4.0.0" + strip-json-comments "^2.0.1" + table "^5.2.3" + text-table "^0.2.0" + espree@^5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/espree/-/espree-5.0.1.tgz#5d6526fa4fc7f0788a5cf75b15f30323e2f81f7a" @@ -2534,9 +2556,9 @@ esprima@^4.0.0: integrity sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A== esquery@^1.0.1, esquery@^1.4.2: - version "1.5.0" - resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.5.0.tgz#6ce17738de8577694edd7361c57182ac8cb0db0b" - integrity sha512-YQLXUplAwJgCydQ78IMJywZCceoqk1oH01OERdSAJc/7U2AylwjhSCLDEtqwg811idIS/9fIU5GjG73IgjKMVg== + version "1.6.0" + resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.6.0.tgz#91419234f804d852a82dceec3e16cdc22cf9dae7" + integrity sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg== dependencies: estraverse "^5.1.0" @@ -2568,14 +2590,14 @@ esutils@^2.0.2: integrity sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g== ethereum-cryptography@^2.0.0, ethereum-cryptography@^2.1.2: - version "2.1.3" - resolved "https://registry.yarnpkg.com/ethereum-cryptography/-/ethereum-cryptography-2.1.3.tgz#1352270ed3b339fe25af5ceeadcf1b9c8e30768a" - integrity sha512-BlwbIL7/P45W8FGW2r7LGuvoEZ+7PWsniMvQ4p5s2xCyw9tmaDlpfsN9HjAucbF+t/qpVHwZUisgfK24TCW8aA== + version "2.2.1" + resolved "https://registry.yarnpkg.com/ethereum-cryptography/-/ethereum-cryptography-2.2.1.tgz#58f2810f8e020aecb97de8c8c76147600b0b8ccf" + integrity sha512-r/W8lkHSiTLxUxW8Rf3u4HGB0xQweG2RyETjywylKZSzLWoWAijRz8WCuOtJ6wah+avllXBqZuk29HCCvhEIRg== dependencies: - "@noble/curves" "1.3.0" - "@noble/hashes" "1.3.3" - "@scure/bip32" "1.3.3" - "@scure/bip39" "1.2.2" + "@noble/curves" "1.4.2" + "@noble/hashes" "1.4.0" + "@scure/bip32" "1.4.0" + "@scure/bip39" "1.3.0" ethers@^5.5.1: version "5.7.2" @@ -2613,10 +2635,10 @@ ethers@^5.5.1: "@ethersproject/web" "5.7.1" "@ethersproject/wordlists" "5.7.0" -ethers@^6.4.0: - version "6.12.0" - resolved "https://registry.yarnpkg.com/ethers/-/ethers-6.12.0.tgz#b0c2ce207ae5a3b5125be966e32ffea7c1f2481a" - integrity sha512-zL5NlOTjML239gIvtVJuaSk0N9GQLi1Hom3ZWUszE5lDTQE/IVB62mrPkQ2W1bGcZwVGSLaetQbWNQSvI4rGDQ== +ethers@^6.13.2, ethers@^6.4.0: + version "6.13.2" + resolved "https://registry.yarnpkg.com/ethers/-/ethers-6.13.2.tgz#4b67d4b49e69b59893931a032560999e5e4419fe" + integrity sha512-9VkriTTed+/27BGuY1s0hf441kqwHJ1wtN2edksEtiRvXx+soxRX3iSXTfFqq2+YwrOqbDoTHjIhQnjJRlzKmg== dependencies: "@adraffy/ens-normalize" "1.10.1" "@noble/curves" "1.2.0" @@ -2624,7 +2646,7 @@ ethers@^6.4.0: "@types/node" "18.15.13" aes-js "4.0.0-beta.5" tslib "2.4.0" - ws "8.5.0" + ws "8.17.1" event-target-shim@^5.0.0: version "5.0.1" @@ -2676,7 +2698,7 @@ fast-diff@^1.1.2: resolved "https://registry.yarnpkg.com/fast-diff/-/fast-diff-1.3.0.tgz#ece407fa550a64d638536cd727e129c61616e0f0" integrity sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw== -fast-glob@^3.2.9, fast-glob@^3.3.1: +fast-glob@^3.3.2: version "3.3.2" resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.3.2.tgz#a904501e57cfdd2ffcded45e99a54fef55e46129" integrity sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow== @@ -2697,6 +2719,11 @@ fast-levenshtein@^2.0.6, fast-levenshtein@~2.0.6: resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917" integrity sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw== +fast-uri@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/fast-uri/-/fast-uri-3.0.1.tgz#cddd2eecfc83a71c1be2cc2ef2061331be8a7134" + integrity sha512-MWipKbbYiYI0UC7cl8m/i/IWTqfC8YXsqjzybjddLsFjStroQzsHXkc73JutMvBiXmOvapk+axIl79ig5t55Bw== + fastest-levenshtein@^1.0.12: version "1.0.16" resolved "https://registry.yarnpkg.com/fastest-levenshtein/-/fastest-levenshtein-1.0.16.tgz#210e61b6ff181de91ea9b3d1b84fdedd47e034e5" @@ -2709,7 +2736,7 @@ fastq@^1.6.0: dependencies: reusify "^1.0.4" -ffjavascript@0.2.48, ffjavascript@^0.2.45: +ffjavascript@0.2.48: version "0.2.48" resolved "https://registry.yarnpkg.com/ffjavascript/-/ffjavascript-0.2.48.tgz#0ca408471d7b18bfc096a9631aa3ef3549c8c82b" integrity sha512-uNrWP+odLofNmmO+iCCPi/Xt/sJh1ku3pVKmKWVWCLFfdCP69hvRrogKUIGnsdiINcWn0lGxcEh5oEjStMFXQQ== @@ -2719,6 +2746,15 @@ ffjavascript@0.2.48, ffjavascript@^0.2.45: wasmcurves "0.1.0" web-worker "^1.2.0" +ffjavascript@^0.2.45: + version "0.2.63" + resolved "https://registry.yarnpkg.com/ffjavascript/-/ffjavascript-0.2.63.tgz#0c1216a1f123dc9181df69e144473704d2f115eb" + integrity sha512-dBgdsfGks58b66JnUZeZpGxdMIDQ4QsD3VYlRJyFVrKQHb2kJy4R2gufx5oetrTxXPT+aEjg0dOvOLg1N0on4A== + dependencies: + wasmbuilder "0.0.16" + wasmcurves "0.2.2" + web-worker "1.2.0" + fflate@^0.8.2: version "0.8.2" resolved "https://registry.yarnpkg.com/fflate/-/fflate-0.8.2.tgz#fc8631f5347812ad6028bbe4a2308b2792aa1dea" @@ -2750,10 +2786,10 @@ file-uri-to-path@1.0.0: resolved "https://registry.yarnpkg.com/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz#553a7b8446ff6f684359c445f1e37a05dacc33dd" integrity sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw== -fill-range@^7.0.1: - version "7.0.1" - resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.0.1.tgz#1919a6a7c75fe38b2c7c77e5198535da9acdda40" - integrity sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ== +fill-range@^7.1.1: + version "7.1.1" + resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.1.1.tgz#44265d3cac07e3ea7dc247516380643754a05292" + integrity sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg== dependencies: to-regex-range "^5.0.1" @@ -2827,6 +2863,14 @@ for-each@^0.3.3: dependencies: is-callable "^1.1.3" +foreground-child@^3.1.0: + version "3.3.0" + resolved "https://registry.yarnpkg.com/foreground-child/-/foreground-child-3.3.0.tgz#0ac8644c06e431439f8561db8ecf29a7b5519c77" + integrity sha512-Ld2g8rrAyMYFXBhEqMz8ZAHBi4J4uS1i/CxGMDnjyFWddMXLVcDp051DZfu+t7+ab7Wv6SMqpWmyFIj5UbfFvg== + dependencies: + cross-spawn "^7.0.0" + signal-exit "^4.0.1" + form-data@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/form-data/-/form-data-4.0.0.tgz#93919daeaf361ee529584b9b31664dc12c9fa452" @@ -2917,10 +2961,10 @@ get-symbol-description@^1.0.2: es-errors "^1.3.0" get-intrinsic "^1.2.4" -get-tsconfig@^4.5.0, get-tsconfig@^4.7.0, get-tsconfig@^4.7.2: - version "4.7.3" - resolved "https://registry.yarnpkg.com/get-tsconfig/-/get-tsconfig-4.7.3.tgz#0498163d98f7b58484dd4906999c0c9d5f103f83" - integrity sha512-ZvkrzoUA0PQZM6fy6+/Hce561s+faD1rsNwhnO5FelNjyy7EMGJ3Rz1AQ8GYDWjhRs/7dBLOEJvhK8MiEJOAFg== +get-tsconfig@^4.7.0, get-tsconfig@^4.7.2, get-tsconfig@^4.7.5: + version "4.8.1" + resolved "https://registry.yarnpkg.com/get-tsconfig/-/get-tsconfig-4.8.1.tgz#8995eb391ae6e1638d251118c7b56de7eb425471" + integrity sha512-k9PN+cFBmaLWtVz29SkUoqU5O0slLuHJXt/2P+tMVFT+phsSGXGkp9t3rQIqdz0e+06EHNGs3oM6ZX1s2zHxRg== dependencies: resolve-pkg-maps "^1.0.0" @@ -2955,6 +2999,18 @@ glob@7.1.7: once "^1.3.0" path-is-absolute "^1.0.0" +glob@^10.4.1: + version "10.4.5" + resolved "https://registry.yarnpkg.com/glob/-/glob-10.4.5.tgz#f4d9f0b90ffdbab09c9d77f5f29b4262517b0956" + integrity sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg== + dependencies: + foreground-child "^3.1.0" + jackspeak "^3.1.2" + minimatch "^9.0.4" + minipass "^7.1.2" + package-json-from-dist "^1.0.0" + path-scurry "^1.11.1" + glob@^7.1.2, glob@^7.1.3: version "7.2.3" resolved "https://registry.yarnpkg.com/glob/-/glob-7.2.3.tgz#b8df0fb802bbfa8e89bd1d938b4e16578ed44f2b" @@ -2967,17 +3023,6 @@ glob@^7.1.2, glob@^7.1.3: once "^1.3.0" path-is-absolute "^1.0.0" -glob@^8.0.3: - version "8.1.0" - resolved "https://registry.yarnpkg.com/glob/-/glob-8.1.0.tgz#d388f656593ef708ee3e34640fdfb99a9fd1c33e" - integrity sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ== - dependencies: - fs.realpath "^1.0.0" - inflight "^1.0.4" - inherits "2" - minimatch "^5.0.1" - once "^1.3.0" - globals@^11.7.0: version "11.12.0" resolved "https://registry.yarnpkg.com/globals/-/globals-11.12.0.tgz#ab8795338868a0babd8525758018c2a7eb95c42e" @@ -2991,23 +3036,12 @@ globals@^13.19.0: type-fest "^0.20.2" globalthis@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/globalthis/-/globalthis-1.0.3.tgz#5852882a52b80dc301b0660273e1ed082f0b6ccf" - integrity sha512-sFdI5LyBiNTHjRd7cGPWapiHWMOXKyuBNX/cWJ3NfzrZQVa8GI/8cofCl74AOVqq9W5kNmguTIzJ/1s2gyI9wA== + version "1.0.4" + resolved "https://registry.yarnpkg.com/globalthis/-/globalthis-1.0.4.tgz#7430ed3a975d97bfb59bcce41f5cabbafa651236" + integrity sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ== dependencies: - define-properties "^1.1.3" - -globby@^11.1.0: - version "11.1.0" - resolved "https://registry.yarnpkg.com/globby/-/globby-11.1.0.tgz#bd4be98bb042f83d796f7e3811991fbe82a0d34b" - integrity sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g== - dependencies: - array-union "^2.1.0" - dir-glob "^3.0.1" - fast-glob "^3.2.9" - ignore "^5.2.0" - merge2 "^1.4.1" - slash "^3.0.0" + define-properties "^1.2.1" + gopd "^1.0.1" gopd@^1.0.1: version "1.0.1" @@ -3129,9 +3163,9 @@ ignore@^4.0.6: integrity sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg== ignore@^5.2.0, ignore@^5.3.1: - version "5.3.1" - resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.3.1.tgz#5073e554cd42c5b33b394375f538b8593e34d4ef" - integrity sha512-5Fytz/IraMjqpwfd34ke28PTVMjZjJG2MPn5t7OE4eUCUNf8BAa7b5WUS9/Qvr6mwOQS7Mk6vdsMno5he+T8Xw== + version "5.3.2" + resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.3.2.tgz#3cd40e729f3643fd87cb04e50bf0eb722bc596f5" + integrity sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g== import-fresh@^3.0.0, import-fresh@^3.2.1: version "3.3.0" @@ -3142,9 +3176,9 @@ import-fresh@^3.0.0, import-fresh@^3.2.1: resolve-from "^4.0.0" import-local@^3.0.2: - version "3.1.0" - resolved "https://registry.yarnpkg.com/import-local/-/import-local-3.1.0.tgz#b4479df8a5fd44f6cdce24070675676063c95cb4" - integrity sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg== + version "3.2.0" + resolved "https://registry.yarnpkg.com/import-local/-/import-local-3.2.0.tgz#c3d5c745798c02a6f8b897726aba5100186ee260" + integrity sha512-2SPlun1JUPWoM6t3F0dw0FkCF/jWY8kttcY4f599GLTSjh2OCuuhdTkJQsEcZzBqbXZGKMK2OqW1oZsjtf/gQA== dependencies: pkg-dir "^4.2.0" resolve-cwd "^3.0.0" @@ -3243,17 +3277,24 @@ is-builtin-module@^3.2.1: dependencies: builtin-modules "^3.3.0" +is-bun-module@^1.0.2: + version "1.2.1" + resolved "https://registry.yarnpkg.com/is-bun-module/-/is-bun-module-1.2.1.tgz#495e706f42e29f086fd5fe1ac3c51f106062b9fc" + integrity sha512-AmidtEM6D6NmUiLOvvU7+IePxjEjOzra2h0pSrsfSAcXwl/83zLLXDByafUJy9k/rKK0pvXMLdwKwGHlX2Ke6Q== + dependencies: + semver "^7.6.3" + is-callable@^1.1.3, is-callable@^1.1.4, is-callable@^1.2.7: version "1.2.7" resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.2.7.tgz#3bc2a85ea742d9e36205dcacdd72ca1fdc51b055" integrity sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA== -is-core-module@^2.11.0, is-core-module@^2.13.0, is-core-module@^2.13.1: - version "2.13.1" - resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.13.1.tgz#ad0d7532c6fea9da1ebdc82742d74525c6273384" - integrity sha512-hHrIjvZsftOsvKSn2TRYl63zvxsgE0K+0mYMoH6gD4omR5IWB2KynivBQczo3+wF1cCkjzvptnI9Q0sPU66ilw== +is-core-module@^2.13.0, is-core-module@^2.15.1: + version "2.15.1" + resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.15.1.tgz#a7363a25bee942fefab0de13bf6aa372c82dcc37" + integrity sha512-z0vtXSwucUJtANQWldhbtbt7BnL0vxiFjIdDLAatwhDYty2bad6s+rijD6Ri4YuYJubLzIJLUidCh09e1djEVQ== dependencies: - hasown "^2.0.0" + hasown "^2.0.2" is-data-view@^1.0.1: version "1.0.1" @@ -3286,6 +3327,11 @@ is-fullwidth-code-point@^2.0.0: resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz#a3b30a5c4f199183167aaab93beefae3ddfb654f" integrity sha512-VHskAKYM8RfSFXwee5t5cbN5PZeq1Wrh6qd5bkyiXIf6UQcN6w/A0eXM9r6t8d+GYOh+o6ZhiEnb88LN/Y8m2w== +is-fullwidth-code-point@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d" + integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== + is-generator-function@^1.0.7: version "1.0.10" resolved "https://registry.yarnpkg.com/is-generator-function/-/is-generator-function-1.0.10.tgz#f1558baf1ac17e0deea7c0415c438351ff2b3c72" @@ -3417,6 +3463,15 @@ isobject@^3.0.1: resolved "https://registry.yarnpkg.com/isobject/-/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df" integrity sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg== +jackspeak@^3.1.2: + version "3.4.3" + resolved "https://registry.yarnpkg.com/jackspeak/-/jackspeak-3.4.3.tgz#8833a9d89ab4acde6188942bd1c53b6390ed5a8a" + integrity sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw== + dependencies: + "@isaacs/cliui" "^8.0.2" + optionalDependencies: + "@pkgjs/parseargs" "^0.11.0" + jest-worker@^27.4.5: version "27.5.1" resolved "https://registry.yarnpkg.com/jest-worker/-/jest-worker-27.5.1.tgz#8d146f0900e8973b106b6f73cc1e9a8cb86f8db0" @@ -3598,19 +3653,17 @@ loupe@^2.3.6: dependencies: get-func-name "^2.0.1" -lru-cache@^6.0.0: - version "6.0.0" - resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-6.0.0.tgz#6d6fe6570ebd96aaf90fcad1dafa3b2566db3a94" - integrity sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA== - dependencies: - yallist "^4.0.0" +lru-cache@^10.2.0: + version "10.4.3" + resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-10.4.3.tgz#410fc8a17b70e598013df257c2446b7f3383f119" + integrity sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ== magic-string@^0.30.3: - version "0.30.9" - resolved "https://registry.yarnpkg.com/magic-string/-/magic-string-0.30.9.tgz#8927ae21bfdd856310e07a1bc8dd5e73cb6c251d" - integrity sha512-S1+hd+dIrC8EZqKyT9DstTH/0Z+f76kmmvZnkfQVmOpDEF9iVgdYif3Q/pIWHmCoo59bQVGW0kVL3e2nl+9+Sw== + version "0.30.11" + resolved "https://registry.yarnpkg.com/magic-string/-/magic-string-0.30.11.tgz#301a6f93b3e8c2cb13ac1a7a673492c0dfd12954" + integrity sha512-+Wri9p0QHMy+545hKww7YAu5NyzF8iomPL/RQazugQ9+Ez4Ic3mERMd8ZTX5rfK944j+560ZJi8iAwgak1Ac7A== dependencies: - "@jridgewell/sourcemap-codec" "^1.4.15" + "@jridgewell/sourcemap-codec" "^1.5.0" map-age-cleaner@^0.1.1: version "0.1.3" @@ -3642,7 +3695,7 @@ merge-stream@^2.0.0: resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-2.0.0.tgz#52823629a14dd00c9770fb6ad47dc6310f2c1f60" integrity sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w== -merge2@^1.3.0, merge2@^1.4.1: +merge2@^1.3.0: version "1.4.1" resolved "https://registry.yarnpkg.com/merge2/-/merge2-1.4.1.tgz#4368892f885e907455a6fd7dc55c0c9d404990ae" integrity sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg== @@ -3653,11 +3706,11 @@ micro-ftch@^0.3.1: integrity sha512-/0LLxhzP0tfiR5hcQebtudP56gUurs2CLkGarnCiB/OqEyUFQ6U3paQi/tgLv0hBJYt2rnr9MNpxz4fiiugstg== micromatch@^4.0.4: - version "4.0.5" - resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.5.tgz#bc8999a7cbbf77cdc89f132f6e467051b49090c6" - integrity sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA== + version "4.0.8" + resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.8.tgz#d66fa18f3a47076789320b9b1af32bd86d9fa202" + integrity sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA== dependencies: - braces "^3.0.2" + braces "^3.0.3" picomatch "^2.3.1" miller-rabin@^4.0.0: @@ -3707,17 +3760,10 @@ minimatch@^3.0.4, minimatch@^3.0.5, minimatch@^3.1.1, minimatch@^3.1.2: dependencies: brace-expansion "^1.1.7" -minimatch@^5.0.1: - version "5.1.6" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-5.1.6.tgz#1cfcb8cf5522ea69952cd2af95ae09477f122a96" - integrity sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g== - dependencies: - brace-expansion "^2.0.1" - minimatch@^9.0.4: - version "9.0.4" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-9.0.4.tgz#8e49c731d1749cbec05050ee5145147b32496a51" - integrity sha512-KqWh+VchfxcMNRAJjj2tnsSJdNbHsVgnkBhTNrW7AjVo6OvLtxw8zfT9oLw1JSohlFzJ8jCoTgaoXvJ+kHt6fw== + version "9.0.5" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-9.0.5.tgz#d74f9dd6b57d83d8e98cfb82133b03978bc929e5" + integrity sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow== dependencies: brace-expansion "^2.0.1" @@ -3726,6 +3772,11 @@ minimist@^1.2.0, minimist@^1.2.6: resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.8.tgz#c1a464e7693302e082a075cee0c057741ac4772c" integrity sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA== +"minipass@^5.0.0 || ^6.0.2 || ^7.0.0", minipass@^7.1.2: + version "7.1.2" + resolved "https://registry.yarnpkg.com/minipass/-/minipass-7.1.2.tgz#93a9626ce5e5e66bd4db86849e7515e92340a707" + integrity sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw== + mkdirp@^0.5.1: version "0.5.6" resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.6.tgz#7def03d2432dcae4ba1d611445c48396062255f6" @@ -3738,12 +3789,7 @@ mkdirp@^1.0.4: resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e" integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw== -ms@2.1.2: - version "2.1.2" - resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" - integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== - -ms@^2.1.1: +ms@^2.1.1, ms@^2.1.3: version "2.1.3" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== @@ -3754,9 +3800,9 @@ mute-stream@0.0.7: integrity sha512-r65nCZhrbXXb6dXOACihYApHw2Q6pV0M3V0PSxd74N0+D8nzAdEAITq2oAjA1jVnKI+tGvEBUpqiMh0+rW6zDQ== nan@^2.14.0: - version "2.19.0" - resolved "https://registry.yarnpkg.com/nan/-/nan-2.19.0.tgz#bb58122ad55a6c5bc973303908d5b16cfdd5a8c0" - integrity sha512-nO1xXxfh/RWNxfd/XPfbIfFk5vgLsAxUR9y5O0cHMJu/AW9U95JLXqthYHjEp+8gQ5p96K9jUp8nbVOxCdRbtw== + version "2.20.0" + resolved "https://registry.yarnpkg.com/nan/-/nan-2.20.0.tgz#08c5ea813dd54ed16e5bd6505bf42af4f7838ca3" + integrity sha512-bk3gXBZDGILuuo/6sKtr0DQmSThYHLtNCdSdXk9YkxD/jK6X2vmCyyXBBxyqZ4XcnzTyYEAThfX3DCEnLf6igw== nanoassert@^2.0.0: version "2.0.0" @@ -3791,14 +3837,14 @@ node-fetch@^2.6.12: whatwg-url "^5.0.0" node-gyp-build@^4.2.2: - version "4.8.0" - resolved "https://registry.yarnpkg.com/node-gyp-build/-/node-gyp-build-4.8.0.tgz#3fee9c1731df4581a3f9ead74664369ff00d26dd" - integrity sha512-u6fs2AEUljNho3EYTJNBfImO5QTo/J/1Etd+NVdCj7qWKUSN/bSLkZwhDv7I+w/MSC6qJ4cknepkAYykDdK8og== + version "4.8.2" + resolved "https://registry.yarnpkg.com/node-gyp-build/-/node-gyp-build-4.8.2.tgz#4f802b71c1ab2ca16af830e6c1ea7dd1ad9496fa" + integrity sha512-IRUxE4BVsHWXkV/SFOut4qTlagw2aM8T5/vnTsmrHJvVoKueJHRc/JaFND7QDDc61kLYUJ6qlZM3sqTSyx2dTw== -node-polyfill-webpack-plugin@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/node-polyfill-webpack-plugin/-/node-polyfill-webpack-plugin-3.0.0.tgz#296b8235d081af368cd413f4c77e68c98919d99c" - integrity sha512-QpG496dDBiaelQZu9wDcVvpLbtk7h9Ctz693RaUMZBgl8DUoFToO90ZTLKq57gP7rwKqYtGbMBXkcEgLSag2jQ== +node-polyfill-webpack-plugin@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/node-polyfill-webpack-plugin/-/node-polyfill-webpack-plugin-4.0.0.tgz#99c4e4a0b41073b65aa8c584b0d195798aed2c76" + integrity sha512-WLk77vLpbcpmTekRj6s6vYxk30XoyaY5MDZ4+9g8OaKoG3Ij+TjOqhpQjVUlfDZBPBgpNATDltaQkzuXSnnkwg== dependencies: assert "^2.1.0" browserify-zlib "^0.2.0" @@ -3806,29 +3852,29 @@ node-polyfill-webpack-plugin@^3.0.0: console-browserify "^1.2.0" constants-browserify "^1.0.0" crypto-browserify "^3.12.0" - domain-browser "^4.22.0" + domain-browser "^5.7.0" events "^3.3.0" https-browserify "^1.0.0" os-browserify "^0.3.0" path-browserify "^1.0.1" process "^0.11.10" - punycode "^2.3.0" + punycode "^2.3.1" querystring-es3 "^0.2.1" - readable-stream "^4.4.2" + readable-stream "^4.5.2" stream-browserify "^3.0.0" stream-http "^3.2.0" string_decoder "^1.3.0" timers-browserify "^2.0.12" tty-browserify "^0.0.1" - type-fest "^4.4.0" + type-fest "^4.18.2" url "^0.11.3" util "^0.12.5" vm-browserify "^1.1.2" -node-releases@^2.0.14: - version "2.0.14" - resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-2.0.14.tgz#2ffb053bceb8b2be8495ece1ab6ce600c4461b0b" - integrity sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw== +node-releases@^2.0.18: + version "2.0.18" + resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-2.0.18.tgz#f010e8d35e2fe8d6b2944f03f70213ecedc4ca3f" + integrity sha512-d9VeXT4SJ7ZeOqGX6R5EM022wpL+eWPooLI+5UpWn2jCT1aosUQEhQP214x33Wkwx3JQMvIm+tIoVOdodFS40g== npm-run-path@^2.0.0: version "2.0.2" @@ -3843,9 +3889,9 @@ number-is-nan@^1.0.0: integrity sha512-4jbtZXNAsfZbAHiiqjLPBiCl16dES1zI4Hpzzxw61Tk+loF+sBDBKx1ICKKKwIqQ7M0mFn1TmkN7euSncWgHiQ== object-inspect@^1.13.1: - version "1.13.1" - resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.13.1.tgz#b96c6109324ccfef6b12216a956ca4dc2ff94bc2" - integrity sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ== + version "1.13.2" + resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.13.2.tgz#dea0088467fb991e67af4058147a24824a3043ff" + integrity sha512-IRZSRuzJiynemAXPYtPe5BoI/RESNYR7TYm50MC5Mqbd3Jmw5y790sErYw3V6SryFJD64b74qQQs9wn5Bg/k3g== object-is@^1.1.5: version "1.1.6" @@ -3870,7 +3916,7 @@ object.assign@^4.1.4, object.assign@^4.1.5: has-symbols "^1.0.3" object-keys "^1.1.1" -object.fromentries@^2.0.7: +object.fromentries@^2.0.8: version "2.0.8" resolved "https://registry.yarnpkg.com/object.fromentries/-/object.fromentries-2.0.8.tgz#f7195d8a9b97bd95cbc1999ea939ecd1a2b00c65" integrity sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ== @@ -3880,7 +3926,7 @@ object.fromentries@^2.0.7: es-abstract "^1.23.2" es-object-atoms "^1.0.0" -object.groupby@^1.0.1: +object.groupby@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/object.groupby/-/object.groupby-1.0.3.tgz#9b125c36238129f6f7b61954a1e7176148d5002e" integrity sha512-+Lhy3TQTuzXI5hevh8sBGqbmurHbbIjAi0Z4S63nthVLmLxfbj4T54a4CfZrXIrt9iP4mVAPYMo/v99taj3wjQ== @@ -3889,7 +3935,7 @@ object.groupby@^1.0.1: define-properties "^1.2.1" es-abstract "^1.23.2" -object.values@^1.1.7: +object.values@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/object.values/-/object.values-1.2.0.tgz#65405a9d92cee68ac2d303002e0b8470a4d9ab1b" integrity sha512-yBYjY9QX2hnRmZHAjG/f13MzmBzxzYgQhFrke06TTyKY5zSTEqkOeukBzIdVA3j3ulu8Qa3MbVFShV7T2RmGtQ== @@ -3925,16 +3971,16 @@ optionator@^0.8.2: word-wrap "~1.2.3" optionator@^0.9.3: - version "0.9.3" - resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.9.3.tgz#007397d44ed1872fdc6ed31360190f81814e2c64" - integrity sha512-JjCoypp+jKn1ttEFExxhetCKeJt9zhAgAve5FXHixTvFDW/5aEktX9bufBKLRRMdU7bNtpLfcGu94B3cdEJgjg== + version "0.9.4" + resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.9.4.tgz#7ea1c1a5d91d764fb282139c88fe11e182a3a734" + integrity sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g== dependencies: - "@aashutoshrathi/word-wrap" "^1.2.3" deep-is "^0.1.3" fast-levenshtein "^2.0.6" levn "^0.4.1" prelude-ls "^1.2.1" type-check "^0.4.0" + word-wrap "^1.2.5" os-browserify@^0.3.0: version "0.3.0" @@ -4010,6 +4056,11 @@ p-try@^2.0.0: resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.2.0.tgz#cb2868540e313d61de58fafbe35ce9004d5540e6" integrity sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ== +package-json-from-dist@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/package-json-from-dist/-/package-json-from-dist-1.0.0.tgz#e501cd3094b278495eb4258d4c9f6d5ac3019f00" + integrity sha512-dATvCeZN/8wQsGywez1mzHtTlP22H8OEfPrVMLNr4/eGa+ijtLn/6M5f0dY8UKNrC2O9UCU6SSoG3qRKnt7STw== + pako@~1.0.5: version "1.0.11" resolved "https://registry.yarnpkg.com/pako/-/pako-1.0.11.tgz#6c9599d340d54dfd3946380252a35705a6b992bf" @@ -4074,10 +4125,13 @@ path-parse@^1.0.7: resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.7.tgz#fbc114b60ca42b30d9daf5858e4bd68bbedb6735" integrity sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw== -path-type@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/path-type/-/path-type-4.0.0.tgz#84ed01c0a7ba380afe09d90a8c180dcd9d03043b" - integrity sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw== +path-scurry@^1.11.1: + version "1.11.1" + resolved "https://registry.yarnpkg.com/path-scurry/-/path-scurry-1.11.1.tgz#7960a668888594a0720b12a911d1a742ab9f11d2" + integrity sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA== + dependencies: + lru-cache "^10.2.0" + minipass "^5.0.0 || ^6.0.2 || ^7.0.0" pathval@^1.1.1: version "1.1.1" @@ -4095,10 +4149,10 @@ pbkdf2@^3.0.3, pbkdf2@^3.1.2: safe-buffer "^5.0.1" sha.js "^2.4.8" -picocolors@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.0.0.tgz#cb5bdc74ff3f51892236eaf79d68bc44564ab81c" - integrity sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ== +picocolors@^1.0.0, picocolors@^1.0.1: + version "1.1.0" + resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.1.0.tgz#5358b76a78cde483ba5cef6a9dc9671440b27d59" + integrity sha512-TQ92mBOW0l3LeMeyLV6mzy/kWr8lkd/hp3mTg7wYK7zJhuBStmGMBG0BdeDZS/dZx1IukaX6Bk11zcln25o1Aw== picomatch@^2.3.1: version "2.3.1" @@ -4144,10 +4198,10 @@ prettier@^2.3.1: resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.8.8.tgz#e8c5d7e98a4305ffe3de2e1fc4aca1a71c28b1da" integrity sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q== -prettier@^3.2.5: - version "3.2.5" - resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.2.5.tgz#e52bc3090586e824964a8813b09aba6233b28368" - integrity sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A== +prettier@^3.3.3: + version "3.3.3" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.3.3.tgz#30c54fe0be0d8d12e6ae61dbb10109ea00d53105" + integrity sha512-i2tDNA0O5IrMO757lfrdQZCc2jPNDVntV0m/+4whiDfWaTKfMNgR7Qz0NAeGz/nRqF4m5/6CLzbP4/liHt12Ew== process-nextick-args@~2.0.0: version "2.0.1" @@ -4177,9 +4231,9 @@ public-encrypt@^4.0.0: safe-buffer "^5.1.2" pump@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/pump/-/pump-3.0.0.tgz#b4a2116815bde2f4e1ea602354e8c75565107a64" - integrity sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww== + version "3.0.2" + resolved "https://registry.yarnpkg.com/pump/-/pump-3.0.2.tgz#836f3edd6bc2ee599256c924ffe0d88573ddcbf8" + integrity sha512-tUPXtzlGM8FE3P0ZL6DVs/3P58k9nk8/jZeQCurTJylQA8qFYzHFfhBJkuqyE0FifOsQ0uKWekiZ5g8wtr28cw== dependencies: end-of-stream "^1.1.0" once "^1.3.1" @@ -4189,15 +4243,15 @@ punycode@^1.4.1: resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.4.1.tgz#c0d5a63b2718800ad8e1eb0fa5269c84dd41845e" integrity sha512-jmYNElW7yvO7TV33CjSmvSiE2yco3bV2czu/OzDKdMNVZQWfxCblURLhf+47syQRBntjfLdd/H0egrzIG+oaFQ== -punycode@^2.1.0, punycode@^2.3.0: +punycode@^2.1.0, punycode@^2.3.1: version "2.3.1" resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.3.1.tgz#027422e2faec0b25e1549c3e1bd8309b9133b6e5" integrity sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg== -qs@^6.11.2: - version "6.12.1" - resolved "https://registry.yarnpkg.com/qs/-/qs-6.12.1.tgz#39422111ca7cbdb70425541cba20c7d7b216599a" - integrity sha512-zWmv4RSuB9r2mYQw3zxQuHWeU+42aKi1wWig/j4ele4ygELZ7PEO6MM7rim9oAQH2A5MWfsAVf/jPvTPgCbvUQ== +qs@^6.12.3: + version "6.13.0" + resolved "https://registry.yarnpkg.com/qs/-/qs-6.13.0.tgz#6ca3bd58439f7e245655798997787b0d88a51906" + integrity sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg== dependencies: side-channel "^1.0.6" @@ -4248,7 +4302,7 @@ readable-stream@^3.5.0, readable-stream@^3.6.0: string_decoder "^1.1.1" util-deprecate "^1.0.1" -readable-stream@^4.4.2: +readable-stream@^4.5.2: version "4.5.2" resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-4.5.2.tgz#9e7fc4c45099baeed934bff6eb97ba6cf2729e09" integrity sha512-yjavECdqeZ3GLXNgRXgeQEdz9fvDDkNKyHnbHRFtOr7/LcfgBcmct7t/ET+HaCTqfh06OzoAxrkN/IfjJBVe+g== @@ -4377,28 +4431,29 @@ rollup-plugin-esbuild@^6.1.1: es-module-lexer "^1.3.1" get-tsconfig "^4.7.2" -rollup@^4.14.1: - version "4.14.1" - resolved "https://registry.yarnpkg.com/rollup/-/rollup-4.14.1.tgz#228d5159c3f4d8745bd24819d734bc6c6ca87c09" - integrity sha512-4LnHSdd3QK2pa1J6dFbfm1HN0D7vSK/ZuZTsdyUAlA6Rr1yTouUTL13HaDOGJVgby461AhrNGBS7sCGXXtT+SA== +rollup@^4.22.0: + version "4.22.0" + resolved "https://registry.yarnpkg.com/rollup/-/rollup-4.22.0.tgz#23cd9e4565a458587683accc34a054660c01f351" + integrity sha512-W21MUIFPZ4+O2Je/EU+GP3iz7PH4pVPUXSbEZdatQnxo29+3rsUjgrJmzuAZU24z7yRAnFN6ukxeAhZh/c7hzg== dependencies: "@types/estree" "1.0.5" optionalDependencies: - "@rollup/rollup-android-arm-eabi" "4.14.1" - "@rollup/rollup-android-arm64" "4.14.1" - "@rollup/rollup-darwin-arm64" "4.14.1" - "@rollup/rollup-darwin-x64" "4.14.1" - "@rollup/rollup-linux-arm-gnueabihf" "4.14.1" - "@rollup/rollup-linux-arm64-gnu" "4.14.1" - "@rollup/rollup-linux-arm64-musl" "4.14.1" - "@rollup/rollup-linux-powerpc64le-gnu" "4.14.1" - "@rollup/rollup-linux-riscv64-gnu" "4.14.1" - "@rollup/rollup-linux-s390x-gnu" "4.14.1" - "@rollup/rollup-linux-x64-gnu" "4.14.1" - "@rollup/rollup-linux-x64-musl" "4.14.1" - "@rollup/rollup-win32-arm64-msvc" "4.14.1" - "@rollup/rollup-win32-ia32-msvc" "4.14.1" - "@rollup/rollup-win32-x64-msvc" "4.14.1" + "@rollup/rollup-android-arm-eabi" "4.22.0" + "@rollup/rollup-android-arm64" "4.22.0" + "@rollup/rollup-darwin-arm64" "4.22.0" + "@rollup/rollup-darwin-x64" "4.22.0" + "@rollup/rollup-linux-arm-gnueabihf" "4.22.0" + "@rollup/rollup-linux-arm-musleabihf" "4.22.0" + "@rollup/rollup-linux-arm64-gnu" "4.22.0" + "@rollup/rollup-linux-arm64-musl" "4.22.0" + "@rollup/rollup-linux-powerpc64le-gnu" "4.22.0" + "@rollup/rollup-linux-riscv64-gnu" "4.22.0" + "@rollup/rollup-linux-s390x-gnu" "4.22.0" + "@rollup/rollup-linux-x64-gnu" "4.22.0" + "@rollup/rollup-linux-x64-musl" "4.22.0" + "@rollup/rollup-win32-arm64-msvc" "4.22.0" + "@rollup/rollup-win32-ia32-msvc" "4.22.0" + "@rollup/rollup-win32-x64-msvc" "4.22.0" fsevents "~2.3.2" run-async@^2.2.0: @@ -4478,12 +4533,10 @@ semver@^6.3.1: resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.1.tgz#556d2ef8689146e46dcea4bfdd095f3434dffcb4" integrity sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA== -semver@^7.5.4, semver@^7.6.0: - version "7.6.0" - resolved "https://registry.yarnpkg.com/semver/-/semver-7.6.0.tgz#1a46a4db4bffcccd97b743b5005c8325f23d4e2d" - integrity sha512-EnwXhrlwXMk9gKu5/flx5sv/an57AkRplG3hTK68W7FRDN+k+OWBj65M7719OkA82XLBxrcX0KSHj+X5COhOVg== - dependencies: - lru-cache "^6.0.0" +semver@^7.5.4, semver@^7.6.0, semver@^7.6.3: + version "7.6.3" + resolved "https://registry.yarnpkg.com/semver/-/semver-7.6.3.tgz#980f7b5550bc175fb4dc09403085627f9eb33143" + integrity sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A== serialize-javascript@^6.0.1: version "6.0.2" @@ -4578,10 +4631,10 @@ signal-exit@^3.0.0, signal-exit@^3.0.2: resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.7.tgz#a9a1767f8af84155114eaabd73f99273c8f59ad9" integrity sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ== -slash@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/slash/-/slash-3.0.0.tgz#6539be870c165adbd5240220dbe361f1bc4d4634" - integrity sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q== +signal-exit@^4.0.1: + version "4.1.0" + resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-4.1.0.tgz#952188c1cbd546070e2dd20d0f41c0ae0530cb04" + integrity sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw== slice-ansi@^2.1.0: version "2.1.0" @@ -4638,6 +4691,15 @@ string-format@^2.0.0: resolved "https://registry.yarnpkg.com/string-format/-/string-format-2.0.0.tgz#f2df2e7097440d3b65de31b6d40d54c96eaffb9b" integrity sha512-bbEs3scLeYNXLecRRuk6uJxdXUSj6le/8rNPHChIJTn2V79aXVTR1EH2OH5zLKKoz0V02fOUKZZcw01pLUShZA== +"string-width-cjs@npm:string-width@^4.2.0": + version "4.2.3" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" + integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== + dependencies: + emoji-regex "^8.0.0" + is-fullwidth-code-point "^3.0.0" + strip-ansi "^6.0.1" + string-width@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/string-width/-/string-width-1.0.2.tgz#118bdf5b8cdc51a2a7e70d211e07e2b0b9b107d3" @@ -4664,6 +4726,24 @@ string-width@^3.0.0: is-fullwidth-code-point "^2.0.0" strip-ansi "^5.1.0" +string-width@^4.1.0: + version "4.2.3" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" + integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== + dependencies: + emoji-regex "^8.0.0" + is-fullwidth-code-point "^3.0.0" + strip-ansi "^6.0.1" + +string-width@^5.0.1, string-width@^5.1.2: + version "5.1.2" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-5.1.2.tgz#14f8daec6d81e7221d2a357e668cab73bdbca794" + integrity sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA== + dependencies: + eastasianwidth "^0.2.0" + emoji-regex "^9.2.2" + strip-ansi "^7.0.1" + string.prototype.trim@^1.2.9: version "1.2.9" resolved "https://registry.yarnpkg.com/string.prototype.trim/-/string.prototype.trim-1.2.9.tgz#b6fa326d72d2c78b6df02f7759c73f8f6274faa4" @@ -4706,6 +4786,13 @@ string_decoder@~1.1.1: dependencies: safe-buffer "~5.1.0" +"strip-ansi-cjs@npm:strip-ansi@^6.0.1": + version "6.0.1" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" + integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== + dependencies: + ansi-regex "^5.0.1" + strip-ansi@^3.0.0, strip-ansi@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf" @@ -4727,13 +4814,20 @@ strip-ansi@^5.1.0: dependencies: ansi-regex "^4.1.0" -strip-ansi@^6.0.1: +strip-ansi@^6.0.0, strip-ansi@^6.0.1: version "6.0.1" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== dependencies: ansi-regex "^5.0.1" +strip-ansi@^7.0.1: + version "7.1.0" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-7.1.0.tgz#d5b6568ca689d8561370b0707685d22434faff45" + integrity sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ== + dependencies: + ansi-regex "^6.0.1" + strip-bom@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-3.0.0.tgz#2334c18e9c759f7bdd56fdef7e9ae3d588e68ed3" @@ -4754,11 +4848,6 @@ strip-json-comments@^3.1.1: resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz#31f1281b3832630434831c310c01cccda8cbe006" integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig== -superstruct@^1.0.3: - version "1.0.4" - resolved "https://registry.yarnpkg.com/superstruct/-/superstruct-1.0.4.tgz#0adb99a7578bd2f1c526220da6571b2d485d91ca" - integrity sha512-7JpaAoX2NGyoFlI9NBh66BQXGONc+uE+MRS5i2iOBKuS4e+ccgMDjATgZldkah+33DakBxDHiss9kvUcGAO8UQ== - supports-color@^5.3.0: version "5.5.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f" @@ -4785,10 +4874,10 @@ supports-preserve-symlinks-flag@^1.0.0: resolved "https://registry.yarnpkg.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz#6eda4bd344a3c94aea376d4cc31bc77311039e09" integrity sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w== -synckit@^0.8.6: - version "0.8.8" - resolved "https://registry.yarnpkg.com/synckit/-/synckit-0.8.8.tgz#fe7fe446518e3d3d49f5e429f443cf08b6edfcd7" - integrity sha512-HwOKAP7Wc5aRGYdKH+dw0PRRpbO841v2DENBtjnR5HFWoiNByAl7vrx3p0G/rCyYXQsrxqtX48TImFtPcIHSpQ== +synckit@^0.9.1: + version "0.9.1" + resolved "https://registry.yarnpkg.com/synckit/-/synckit-0.9.1.tgz#febbfbb6649979450131f64735aa3f6c14575c88" + integrity sha512-7gr8p9TQP6RAHusBOSLs46F4564ZrjV8xFmw5zCmgmhGUcw2hxsShhJ6CEiHQMgPDwAQ1fWHPM0ypc4RMAig4A== dependencies: "@pkgr/core" "^0.1.0" tslib "^2.6.2" @@ -4830,9 +4919,9 @@ terser-webpack-plugin@^5.3.10: terser "^5.26.0" terser@^5.26.0: - version "5.30.4" - resolved "https://registry.yarnpkg.com/terser/-/terser-5.30.4.tgz#62b4d16a819424e6317fd5ceffb4ee8dc769803a" - integrity sha512-xRdd0v64a8mFK9bnsKVdoNP9GQIKUAaJPTaqEQDL4w/J8WaW4sWXXoMZ+6SimPkfT5bElreXf8m9HnmPc3E1BQ== + version "5.33.0" + resolved "https://registry.yarnpkg.com/terser/-/terser-5.33.0.tgz#8f9149538c7468ffcb1246cfec603c16720d2db1" + integrity sha512-JuPVaB7s1gdFKPKTelwUyRq5Sid2A3Gko2S0PncwdBq7kN9Ti9HPWDQ06MPsEDGsZeVESjKEnyGy68quBk1w6g== dependencies: "@jridgewell/source-map" "^0.3.3" acorn "^8.8.2" @@ -4921,20 +5010,15 @@ tslib@^1.9.0: integrity sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg== tslib@^2.6.2: - version "2.6.2" - resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.6.2.tgz#703ac29425e7b37cd6fd456e92404d46d1f3e4ae" - integrity sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q== + version "2.7.0" + resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.7.0.tgz#d9b40c5c40ab59e8738f297df3087bf1a2690c01" + integrity sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA== tty-browserify@^0.0.1: version "0.0.1" resolved "https://registry.yarnpkg.com/tty-browserify/-/tty-browserify-0.0.1.tgz#3f05251ee17904dfd0677546670db9651682b811" integrity sha512-C3TaO7K81YvjCgQH9Q1S3R3P3BtN3RIM8n+OvX4il1K1zgE8ZhI0op7kClgkxtutIE8hQrcrHBXvIheqKUUCxw== -tweetnacl-util@^0.15.1: - version "0.15.1" - resolved "https://registry.yarnpkg.com/tweetnacl-util/-/tweetnacl-util-0.15.1.tgz#b80fcdb5c97bcc508be18c44a4be50f022eea00b" - integrity sha512-RKJBIj8lySrShN4w6i/BonWp2Z/uxwC3h4y7xsRrpP59ZboCd0GpEVsOnMDYLMmKBpYhb5TgHzZXy7wTfYFBRw== - tweetnacl@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/tweetnacl/-/tweetnacl-1.0.3.tgz#ac0af71680458d8a6378d0d0d050ab1407d35596" @@ -4954,20 +5038,20 @@ type-check@~0.3.2: dependencies: prelude-ls "~1.1.2" -type-detect@^4.0.0, type-detect@^4.0.8: - version "4.0.8" - resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c" - integrity sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g== +type-detect@^4.0.0, type-detect@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.1.0.tgz#deb2453e8f08dcae7ae98c626b13dddb0155906c" + integrity sha512-Acylog8/luQ8L7il+geoSxhEkazvkslg7PSNKOX59mbB9cOveP5aq9h74Y7YU8yDpJwetzQQrfIwtf4Wp4LKcw== type-fest@^0.20.2: version "0.20.2" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.20.2.tgz#1bf207f4b28f91583666cb5fbd327887301cd5f4" integrity sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ== -type-fest@^4.4.0: - version "4.17.0" - resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-4.17.0.tgz#4c1b2c2852d2a40ba8c0236d3afc6fc68229e5bf" - integrity sha512-9flrz1zkfLRH3jO3bLflmTxryzKMxVa7841VeMgBaNQGY6vH4RCcpN/sQLB7mQQYh1GZ5utT2deypMuCy4yicw== +type-fest@^4.18.2: + version "4.26.1" + resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-4.26.1.tgz#a4a17fa314f976dd3e6d6675ef6c775c16d7955e" + integrity sha512-yOGpmOAL7CkKe/91I5O3gPICmJNLJ1G4zFYVAsRHg7M64biSnPtRj0WNQt++bRkjYOqjWXrhnUw1utzmVErAdg== typechain@^8.3.2: version "8.3.2" @@ -5029,10 +5113,10 @@ typed-array-length@^1.0.6: is-typed-array "^1.1.13" possible-typed-array-names "^1.0.0" -typescript@^5.4.4: - version "5.4.4" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-5.4.4.tgz#eb2471e7b0a5f1377523700a21669dce30c2d952" - integrity sha512-dGE2Vv8cpVvw28v8HCPqyb08EzbBURxDpuhJvTrusShUfGnhHBafDsLdS1EhhxyL6BJQE+2cT3dDPAv+MQ6oLw== +typescript@^5.6.2: + version "5.6.2" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-5.6.2.tgz#d1de67b6bef77c41823f822df8f0b3bcff60a5a0" + integrity sha512-NW8ByodCSNCwZeghjN3o+JX5OFH0Ojg6sadjEKY4huZ52TqbJTJnDo5+Tw98lSy63NZvi4n+ez5m2u5d4PkZyw== typical@^4.0.0: version "4.0.0" @@ -5054,23 +5138,23 @@ unbox-primitive@^1.0.2: has-symbols "^1.0.3" which-boxed-primitive "^1.0.2" -undici-types@~5.26.4: - version "5.26.5" - resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-5.26.5.tgz#bcd539893d00b56e964fd2657a4866b221a65617" - integrity sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA== +undici-types@~6.19.2: + version "6.19.8" + resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-6.19.8.tgz#35111c9d1437ab83a7cdc0abae2f26d88eda0a02" + integrity sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw== universalify@^0.1.0: version "0.1.2" resolved "https://registry.yarnpkg.com/universalify/-/universalify-0.1.2.tgz#b646f69be3942dabcecc9d6639c80dc105efaa66" integrity sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg== -update-browserslist-db@^1.0.13: - version "1.0.13" - resolved "https://registry.yarnpkg.com/update-browserslist-db/-/update-browserslist-db-1.0.13.tgz#3c5e4f5c083661bd38ef64b6328c26ed6c8248c4" - integrity sha512-xebP81SNcPuNpPP3uzeW1NYXxI3rxyJzF3pD6sH4jE7o/IX+WtSpwnVU+qIsDPyk0d3hmFQ7mjqc6AtV604hbg== +update-browserslist-db@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/update-browserslist-db/-/update-browserslist-db-1.1.0.tgz#7ca61c0d8650766090728046e416a8cde682859e" + integrity sha512-EdRAaAyk2cUE1wOf2DkEhzxqOQvFOoRJFNS6NeyJ01Gp2beMRpBAINjM2iDXE3KCuKhwnvHIQCJm6ThL2Z+HzQ== dependencies: - escalade "^3.1.1" - picocolors "^1.0.0" + escalade "^3.1.2" + picocolors "^1.0.1" uri-js@^4.2.2: version "4.4.1" @@ -5080,12 +5164,12 @@ uri-js@^4.2.2: punycode "^2.1.0" url@^0.11.3: - version "0.11.3" - resolved "https://registry.yarnpkg.com/url/-/url-0.11.3.tgz#6f495f4b935de40ce4a0a52faee8954244f3d3ad" - integrity sha512-6hxOLGfZASQK/cijlZnZJTq8OXAkt/3YGfQX45vvMYXpZoo8NdWZcY73K108Jf759lS1Bv/8wXnHDTSz17dSRw== + version "0.11.4" + resolved "https://registry.yarnpkg.com/url/-/url-0.11.4.tgz#adca77b3562d56b72746e76b330b7f27b6721f3c" + integrity sha512-oCwdVC7mTuWiPyjLUz/COz5TLk6wgp0RCsN+wHZ2Ekneac9w8uuV0njcbbie2ME+Vs+d6duwmYuR3HgQXs1fOg== dependencies: punycode "^1.4.1" - qs "^6.11.2" + qs "^6.12.3" util-deprecate@^1.0.1, util-deprecate@~1.0.1: version "1.0.2" @@ -5113,6 +5197,11 @@ vm-browserify@^1.1.2: resolved "https://registry.yarnpkg.com/vm-browserify/-/vm-browserify-1.1.2.tgz#78641c488b8e6ca91a75f511e7a3b32a86e5dda0" integrity sha512-2ham8XPWTONajOR0ohOKOHXkm3+gaBmGut3SRuu75xLd/RRaY6vqgh8NBYYk7+RW3u5AtzPQZG8F10LHkl0lAQ== +wasmbuilder@0.0.16: + version "0.0.16" + resolved "https://registry.yarnpkg.com/wasmbuilder/-/wasmbuilder-0.0.16.tgz#f34c1f2c047d2f6e1065cbfec5603988f16d8549" + integrity sha512-Qx3lEFqaVvp1cEYW7Bfi+ebRJrOiwz2Ieu7ZG2l7YyeSJIok/reEQCQCuicj/Y32ITIJuGIM9xZQppGx5LrQdA== + wasmbuilder@^0.0.12: version "0.0.12" resolved "https://registry.yarnpkg.com/wasmbuilder/-/wasmbuilder-0.0.12.tgz#a60cb25d6d11f314fe5ab3f4ee041ccb493cb78a" @@ -5128,14 +5217,26 @@ wasmcurves@0.1.0: big-integer "^1.6.42" blakejs "^1.1.0" +wasmcurves@0.2.2: + version "0.2.2" + resolved "https://registry.yarnpkg.com/wasmcurves/-/wasmcurves-0.2.2.tgz#ca444f6a6f6e2a5cbe6629d98ff478a62b4ccb2b" + integrity sha512-JRY908NkmKjFl4ytnTu5ED6AwPD+8VJ9oc94kdq7h5bIwbj0L4TDJ69mG+2aLs2SoCmGfqIesMWTEJjtYsoQXQ== + dependencies: + wasmbuilder "0.0.16" + watchpack@^2.4.1: - version "2.4.1" - resolved "https://registry.yarnpkg.com/watchpack/-/watchpack-2.4.1.tgz#29308f2cac150fa8e4c92f90e0ec954a9fed7fff" - integrity sha512-8wrBCMtVhqcXP2Sup1ctSkga6uc2Bx0IIvKyT7yTFier5AXHooSI+QyQQAtTb7+E0IUCCKyTFmXqdqgum2XWGg== + version "2.4.2" + resolved "https://registry.yarnpkg.com/watchpack/-/watchpack-2.4.2.tgz#2feeaed67412e7c33184e5a79ca738fbd38564da" + integrity sha512-TnbFSbcOCcDgjZ4piURLCbJ3nJhznVh9kw6F6iokjiFPl8ONxe9A6nMDVXDiNbrSfLILs6vB07F7wLBrwPYzJw== dependencies: glob-to-regexp "^0.4.1" graceful-fs "^4.1.2" +web-worker@1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/web-worker/-/web-worker-1.2.0.tgz#5d85a04a7fbc1e7db58f66595d7a3ac7c9c180da" + integrity sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA== + web-worker@^1.2.0: version "1.3.0" resolved "https://registry.yarnpkg.com/web-worker/-/web-worker-1.3.0.tgz#e5f2df5c7fe356755a5fb8f8410d4312627e6776" @@ -5187,21 +5288,20 @@ webpack-sources@^3.2.3: resolved "https://registry.yarnpkg.com/webpack-sources/-/webpack-sources-3.2.3.tgz#2d4daab8451fd4b240cc27055ff6a0c2ccea0cde" integrity sha512-/DyMEOrDgLKKIG0fmvtz+4dUX/3Ghozwgm6iPp8KRhvn+eQf9+Q7GWxVNMk3+uCPWfdXYC4ExGBckIXdFEfH1w== -webpack@^5.91.0: - version "5.91.0" - resolved "https://registry.yarnpkg.com/webpack/-/webpack-5.91.0.tgz#ffa92c1c618d18c878f06892bbdc3373c71a01d9" - integrity sha512-rzVwlLeBWHJbmgTC/8TvAcu5vpJNII+MelQpylD4jNERPwpBJOE2lEcko1zJX3QJeLjTTAnQxn/OJ8bjDzVQaw== +webpack@^5.94.0: + version "5.94.0" + resolved "https://registry.yarnpkg.com/webpack/-/webpack-5.94.0.tgz#77a6089c716e7ab90c1c67574a28da518a20970f" + integrity sha512-KcsGn50VT+06JH/iunZJedYGUJS5FGjow8wb9c0v5n1Om8O1g4L6LjtfxwlXIATopoQu+vOXXa7gYisWxCoPyg== dependencies: - "@types/eslint-scope" "^3.7.3" "@types/estree" "^1.0.5" "@webassemblyjs/ast" "^1.12.1" "@webassemblyjs/wasm-edit" "^1.12.1" "@webassemblyjs/wasm-parser" "^1.12.1" acorn "^8.7.1" - acorn-import-assertions "^1.9.0" + acorn-import-attributes "^1.9.5" browserslist "^4.21.10" chrome-trace-event "^1.0.2" - enhanced-resolve "^5.16.0" + enhanced-resolve "^5.17.1" es-module-lexer "^1.2.1" eslint-scope "5.1.1" events "^3.2.0" @@ -5271,7 +5371,7 @@ wildcard@^2.0.0: resolved "https://registry.yarnpkg.com/wildcard/-/wildcard-2.0.1.tgz#5ab10d02487198954836b6349f74fff961e10f67" integrity sha512-CC1bOL87PIWSBhDcTrdeLo6eGT7mCFtrg0uIJtqJUFyK+eJnzl8A1niH56uu7KMa5XFrtiV+AQuHO3n7DsHnLQ== -word-wrap@~1.2.3: +word-wrap@^1.2.5, word-wrap@~1.2.3: version "1.2.5" resolved "https://registry.yarnpkg.com/word-wrap/-/word-wrap-1.2.5.tgz#d2c45c6dd4fbce621a66f136cbe328afd0410b34" integrity sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA== @@ -5284,6 +5384,15 @@ wordwrapjs@^4.0.0: reduce-flatten "^2.0.0" typical "^5.2.0" +"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0": + version "7.0.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" + integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== + dependencies: + ansi-styles "^4.0.0" + string-width "^4.1.0" + strip-ansi "^6.0.0" + wrap-ansi@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-2.1.0.tgz#d8fc3d284dd05794fe84973caecdd1cf824fdd85" @@ -5292,6 +5401,15 @@ wrap-ansi@^2.0.0: string-width "^1.0.1" strip-ansi "^3.0.1" +wrap-ansi@^8.1.0: + version "8.1.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-8.1.0.tgz#56dc22368ee570face1b49819975d9b9a5ead214" + integrity sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ== + dependencies: + ansi-styles "^6.1.0" + string-width "^5.0.1" + strip-ansi "^7.0.1" + wrappy@1: version "1.0.2" resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" @@ -5309,10 +5427,10 @@ ws@7.4.6: resolved "https://registry.yarnpkg.com/ws/-/ws-7.4.6.tgz#5654ca8ecdeee47c33a9a4bf6d28e2be2980377c" integrity sha512-YmhHDO4MzaDLB+M9ym/mDA5z0naX8j7SIlT8f8z+I0VtzsRbekxEutHSme7NPS2qE8StCYQNUnfWdXta/Yu85A== -ws@8.5.0: - version "8.5.0" - resolved "https://registry.yarnpkg.com/ws/-/ws-8.5.0.tgz#bfb4be96600757fe5382de12c670dab984a1ed4f" - integrity sha512-BWX0SWVgLPzYwF8lTzEy1egjhS4S4OEAHfsO8o65WOVsrnSRGaSiUaa9e0ggGlkMTtBlmOpEXiie9RUcBO86qg== +ws@8.17.1: + version "8.17.1" + resolved "https://registry.yarnpkg.com/ws/-/ws-8.17.1.tgz#9293da530bb548febc95371d90f9c878727d919b" + integrity sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ== xtend@^4.0.2: version "4.0.2" @@ -5324,11 +5442,6 @@ xtend@^4.0.2: resolved "https://registry.yarnpkg.com/y18n/-/y18n-4.0.3.tgz#b5f259c82cd6e336921efd7bfd8bf560de9eeedf" integrity sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ== -yallist@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72" - integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A== - yargs-parser@^11.1.1: version "11.1.1" resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-11.1.1.tgz#879a0865973bca9f6bab5cbdf3b1c67ec7d3bcf4"