UNPKG

@silvana-one/prover

Version:
487 lines (479 loc) 14.6 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // dist/node/index.js var index_exports = {}; __export(index_exports, { Cloud: () => Cloud, Memory: () => Memory, bigintFromBase56: () => bigintFromBase56, bigintFromBase64: () => bigintFromBase64, bigintToBase56: () => bigintToBase56, bigintToBase64: () => bigintToBase64, config: () => config, defaultToken: () => defaultToken, formatTime: () => formatTime, fromBase: () => fromBase, getAccountFromGraphQL: () => getAccountFromGraphQL, getBalanceFromGraphQL: () => getBalanceFromGraphQL, makeString: () => makeString, sleep: () => sleep, toBase: () => toBase, zkCloudWorker: () => zkCloudWorker }); module.exports = __toCommonJS(index_exports); // dist/node/utils/graphql.js var defaultToken = "wSHV2S4qX9jFsLjQo8r1BsMLH2ZRKsZx6EJd1sbozGPieEC4Jf"; async function getBalanceFromGraphQL(params) { const { publicKey, mina } = params; const tokenId = params.tokenId ?? defaultToken; if (mina.length === 0) throw new Error("no mina endpoints provided"); const account = await fetchAccountInternal({ publicKey, tokenId, mina, queryType: "balance" }); const balance = account?.account?.balance?.total; return balance ? BigInt(balance) : 0n; } async function getAccountFromGraphQL(params) { const { publicKey, mina } = params; const tokenId = params.tokenId ?? defaultToken; if (mina.length === 0) throw new Error("no mina endpoints provided"); const account = await fetchAccountInternal({ publicKey, tokenId, mina, queryType: "account" }); return account?.account; } async function fetchAccountInternal(params) { const { publicKey, tokenId, mina, timeout, queryType } = params; const query = queryType === "balance" ? balanceQuery(publicKey, tokenId) : accountQuery(publicKey, tokenId); let [response, error] = await makeGraphqlRequest({ query, mina, timeout }); if (error !== void 0) return { account: void 0, error }; const account = response?.data?.account; if (!account) { return { account: void 0, error: { statusCode: 404, statusText: `fetchAccount: Account with public key ${publicKey} does not exist.` } }; } return { account, error: void 0 }; } async function makeGraphqlRequest(params) { const defaultTimeout = 5 * 60 * 1e3; const timeout = params.timeout ?? defaultTimeout; const { query, mina } = params; const graphqlEndpoint = mina[0]; const fallbackEndpoints = mina.slice(1); if (graphqlEndpoint === "none") throw Error("Should have made a graphql request, but don't know to which endpoint."); let timeouts = []; const clearTimeouts = () => { timeouts.forEach((t) => clearTimeout(t)); timeouts = []; }; const makeRequest = async (url) => { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeout); timeouts.push(timer); let body = JSON.stringify({ operationName: null, query, variables: {} }); try { let response = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body, signal: controller.signal }); return checkResponseStatus(response); } finally { clearTimeouts(); } }; let timeoutErrors = []; let urls = [graphqlEndpoint, ...fallbackEndpoints]; for (let i = 0; i < urls.length; i += 2) { let url1 = urls[i]; let url2 = urls[i + 1]; if (url2 === void 0) { try { return await makeRequest(url1); } catch (error) { return [void 0, inferError(error)]; } } try { return await Promise.race([makeRequest(url1), makeRequest(url2)]); } catch (unknownError) { let error = inferError(unknownError); if (error.statusCode === 408) { timeoutErrors.push({ url1, url2, error }); } else { return [void 0, error]; } } } const statusText = timeoutErrors.map(({ url1, url2, error }) => `Request to ${url1} and ${url2} timed out. Error: ${error}`).join("\n"); return [void 0, { statusCode: 408, statusText }]; } function inferError(error) { let errorMessage = JSON.stringify(error); if (error instanceof AbortSignal) { return { statusCode: 408, statusText: `Request Timeout: ${errorMessage}` }; } else { return { statusCode: 500, statusText: `Unknown Error: ${errorMessage}` }; } } async function checkResponseStatus(response) { if (response.ok) { const jsonResponse = await response.json(); if (jsonResponse.errors && jsonResponse.errors.length > 0) { return [ void 0, { statusCode: response.status, statusText: jsonResponse.errors.map((error) => error.message).join("\n") } ]; } else if (jsonResponse.data === void 0) { return [ void 0, { statusCode: response.status, statusText: `GraphQL response data is undefined` } ]; } return [jsonResponse, void 0]; } else { return [ void 0, { statusCode: response.status, statusText: response.statusText } ]; } } var balanceQuery = (publicKey, tokenId) => `{ account(publicKey: "${publicKey}", token: "${tokenId}") { balance { total } } } `; var accountQuery = (publicKey, tokenId) => `{ account(publicKey: "${publicKey}", token: "${tokenId}") { publicKey token nonce balance { total } tokenSymbol receiptChainHash timing { initialMinimumBalance cliffTime cliffAmount vestingPeriod vestingIncrement } permissions { editState access send receive setDelegate setPermissions setVerificationKey { auth txnVersion } setZkappUri editActionState setTokenSymbol incrementNonce setVotingFor setTiming } delegateAccount { publicKey } votingFor zkappState verificationKey { verificationKey hash } actionState provedState zkappUri } } `; // dist/node/utils/utils.js function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } function makeString(length) { let outString = ``; const inOptions = `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`; for (let i = 0; i < length; i++) { outString += inOptions.charAt(Math.floor(Math.random() * inOptions.length)); } return outString; } function formatTime(ms) { if (ms === void 0) return ""; if (ms < 1e3) return ms.toString() + " ms"; if (ms < 60 * 1e3) return parseInt((ms / 1e3).toString()).toString() + " sec"; if (ms < 60 * 60 * 1e3) { const minutes = parseInt((ms / 1e3 / 60).toString()); const seconds = parseInt(((ms - minutes * 60 * 1e3) / 1e3).toString()); return minutes.toString() + " min " + seconds.toString() + " sec"; } else { const hours = parseInt((ms / 1e3 / 60 / 60).toString()); const minutes = parseInt(((ms - hours * 60 * 60 * 1e3) / 1e3 / 60).toString()); return hours.toString() + " h " + minutes.toString() + " min"; } } var _Memory = class _Memory { constructor() { _Memory.rss = 0; } // eslint-disable-next-line @typescript-eslint/no-inferrable-types static info(description = ``, fullInfo = false) { const memoryData = process.memoryUsage(); const formatMemoryUsage = (data) => `${Math.round(data / 1024 / 1024)} MB`; const oldRSS = _Memory.rss; _Memory.rss = Math.round(memoryData.rss / 1024 / 1024); const memoryUsage = fullInfo ? { step: `${description}:`, rssDelta: `${(oldRSS === 0 ? 0 : _Memory.rss - oldRSS).toString()} MB -> Resident Set Size memory change`, rss: `${formatMemoryUsage(memoryData.rss)} -> Resident Set Size - total memory allocated`, heapTotal: `${formatMemoryUsage(memoryData.heapTotal)} -> total size of the allocated heap`, heapUsed: `${formatMemoryUsage(memoryData.heapUsed)} -> actual memory used during the execution`, external: `${formatMemoryUsage(memoryData.external)} -> V8 external memory` } : `RSS memory ${description}: ${formatMemoryUsage(memoryData.rss)}${oldRSS === 0 ? `` : `, changed by ` + (_Memory.rss - oldRSS).toString() + ` MB`}`; console.log(memoryUsage); } }; _Memory.rss = 0; var Memory = _Memory; // dist/node/utils/base64.js var TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; function bigintToBase56(value) { const digits = toBase(value, 56n); const str = digits.map((x) => TABLE[Number(x)]).join(""); return str; } function bigintFromBase56(str) { const base56Digits = str.split("").map((x2) => BigInt(TABLE.indexOf(x2))); const x = fromBase(base56Digits, 56n); return x; } function bigintToBase64(value) { const digits = toBase(value, 64n); const str = digits.map((x) => TABLE[Number(x)]).join(""); return str; } function bigintFromBase64(str) { const base64Digits = str.split("").map((x2) => BigInt(TABLE.indexOf(x2))); const x = fromBase(base64Digits, 64n); return x; } function fromBase(digits, base) { if (base <= 0n) throw Error("fromBase: base must be positive"); let basePowers = []; for (let power = base, n = 1; n < digits.length; power **= 2n, n *= 2) { basePowers.push(power); } let k = basePowers.length; digits = digits.concat(Array(2 ** k - digits.length).fill(0n)); for (let i = 0; i < k; i++) { let newDigits = Array(digits.length >> 1); let basePower = basePowers[i]; for (let j = 0; j < newDigits.length; j++) { newDigits[j] = digits[2 * j] + basePower * digits[2 * j + 1]; } digits = newDigits; } console.assert(digits.length === 1); let [digit] = digits; return digit; } function toBase(x, base) { if (base <= 0n) throw Error("toBase: base must be positive"); let basePowers = []; for (let power = base; power <= x; power **= 2n) { basePowers.push(power); } let digits = [x]; let k = basePowers.length; for (let i = 0; i < k; i++) { let newDigits = Array(2 * digits.length); let basePower = basePowers[k - 1 - i]; for (let j = 0; j < digits.length; j++) { let x2 = digits[j]; let high = x2 / basePower; newDigits[2 * j + 1] = high; newDigits[2 * j] = x2 - high * basePower; } digits = newDigits; } while (digits[digits.length - 1] === 0n) { digits.pop(); } return digits; } // dist/node/worker/cloud.js var Cloud = class { /** * Constructor for the Cloud class * @param params the parameters for the Cloud class * @param params.id the id of the user * @param params.jobId the job id * @param params.stepId the step id * @param params.taskId the task id * @param params.cache the cache folder. Use it to get the Cache object: cache = Cache.FileSystem(this.cloud.cache); * @param params.developer the developer id * @param params.repo the repo id * @param params.task the task id * @param params.userId the user id * @param params.args the arguments, should be a string or serialized JSON * @param params.metadata the metadata, should be a string or serialized JSON * @param params.chain the blockchain network * @param params.isLocalCloud a boolean to check if the cloud is local or not */ constructor(params) { const { id, jobId, stepId, taskId, cache, developer, repo, task, userId, args, metadata, isLocalCloud, chain } = params; this.id = id; this.jobId = jobId; this.stepId = stepId; this.taskId = taskId; this.cache = cache; this.developer = developer; this.repo = repo; this.task = task; this.userId = userId; this.args = args; this.metadata = metadata; this.isLocalCloud = isLocalCloud ?? false; this.chain = chain; } }; // dist/node/worker/worker.js var zkCloudWorker = class { /** * Constructor for the zkCloudWorker class * @param cloud the cloud instance provided by the zkCloudWorker in the local environment or in the cloud */ constructor(cloud) { this.cloud = cloud; } // Those methods should be implemented for recursive proofs calculations /** * Creates a new proof from a transaction * @param transaction the transaction * @returns the serialized proof */ async create(transaction) { return void 0; } /** * Merges two proofs * @param proof1 the first proof * @param proof2 the second proof * @returns the merged proof */ async merge(proof1, proof2) { return void 0; } // Those methods should be implemented for anything except for recursive proofs /** * Executes the transactions * @param transactions the transactions, can be empty list * @returns the result */ async execute(transactions) { return void 0; } /* Process the transactions received by the cloud * @param transactions: the transactions */ async processTransactions(transactions) { } /** * process the task defined by the developer * @returns the result */ async task() { return void 0; } }; // dist/node/config.js var config = { MINAFEE: "200000000", ZKCLOUDWORKER_AUTH: "M6t4jtbBAFFXhLERHQWyEB9JA9xi4cWqmYduaCXtbrFjb7yaY7TyaXDunKDJNiUTBEcyUomNXJgC", ZKCLOUDWORKER_API: "https://api.zkcloudworker.com/v1/", ZKCLOUDWORKER_NATS: "https://cloud.zkcloudworker.com:4222", ZKCLOUDWORKER_NATS_WS: "wss://cloud.zkcloudworker.com:4223" }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { Cloud, Memory, bigintFromBase56, bigintFromBase64, bigintToBase56, bigintToBase64, config, defaultToken, formatTime, fromBase, getAccountFromGraphQL, getBalanceFromGraphQL, makeString, sleep, toBase, zkCloudWorker });