From 3fbbee10be99e8c5a696bfd50d81230141bccbf4 Mon Sep 17 00:00:00 2001 From: Manuel Mauro Date: Tue, 23 Jul 2024 14:05:15 +0300 Subject: [PATCH] feat: add revert tests (external node) to zk_toolbox (#2408) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What ❔ - Adds revert tests (external node) to zk_toolbox ## Why ❔ ## Checklist - [x] PR title corresponds to the body of PR (we generate changelog entries from PRs). - [x] Tests for the changes have been added / updated. - [x] Documentation comments have been added / updated. - [x] Code has been formatted via `zk fmt` and `zk lint`. --------- Co-authored-by: aon <21188659+aon@users.noreply.github.com> Co-authored-by: Manuel --- .github/workflows/ci-zk-toolbox-reusable.yml | 4 + .../tests/revert-and-restart-en.test.ts | 242 +++++++++++++----- core/tests/revert-test/tests/utils.ts | 81 ++++++ etc/utils/src/file-configs.ts | 18 +- .../src/commands/test/args/revert.rs | 4 +- .../zk_supervisor/src/commands/test/revert.rs | 22 +- .../crates/zk_supervisor/src/messages.rs | 11 + 7 files changed, 304 insertions(+), 78 deletions(-) create mode 100644 core/tests/revert-test/tests/utils.ts diff --git a/.github/workflows/ci-zk-toolbox-reusable.yml b/.github/workflows/ci-zk-toolbox-reusable.yml index 7ff5eb3f1cf..87bd1729db9 100644 --- a/.github/workflows/ci-zk-toolbox-reusable.yml +++ b/.github/workflows/ci-zk-toolbox-reusable.yml @@ -118,6 +118,10 @@ jobs: run: | ci_run zk_supervisor test revert --ignore-prerequisites --verbose + - name: Run revert tests (external node) + run: | + ci_run zk_supervisor test revert --external-node --ignore-prerequisites --verbose + - name: Show server.log logs if: always() run: ci_run cat server.log || true diff --git a/core/tests/revert-test/tests/revert-and-restart-en.test.ts b/core/tests/revert-test/tests/revert-and-restart-en.test.ts index ce306134f51..2fee9c7be88 100644 --- a/core/tests/revert-test/tests/revert-and-restart-en.test.ts +++ b/core/tests/revert-test/tests/revert-and-restart-en.test.ts @@ -5,23 +5,49 @@ // main_contract.getTotalBatchesExecuted actually checks the number of batches executed. import * as utils from 'utils'; import { Tester } from './tester'; +import { exec, runServerInBackground, runExternalNodeInBackground } from './utils'; import * as zksync from 'zksync-ethers'; import * as ethers from 'ethers'; import { expect, assert } from 'chai'; import fs from 'fs'; import * as child_process from 'child_process'; import * as dotenv from 'dotenv'; +import { + getAllConfigsPath, + loadConfig, + shouldLoadConfigFromFile, + replaceAggregatedBlockExecuteDeadline +} from 'utils/build/file-configs'; +import path from 'path'; + +const pathToHome = path.join(__dirname, '../../../..'); +const fileConfig = shouldLoadConfigFromFile(); let mainEnv: string; let extEnv: string; -if (process.env.DEPLOYMENT_MODE == 'Validium') { + +let deploymentMode: string; + +if (fileConfig.loadFromFile) { + const genesisConfig = loadConfig({ pathToHome, chain: fileConfig.chain, config: 'genesis.yaml' }); + deploymentMode = genesisConfig.deploymentMode; +} else { + if (!process.env.DEPLOYMENT_MODE) { + throw new Error('DEPLOYMENT_MODE is not set'); + } + if (!['Validium', 'Rollup'].includes(process.env.DEPLOYMENT_MODE)) { + throw new Error(`Unknown deployment mode: ${process.env.DEPLOYMENT_MODE}`); + } + deploymentMode = process.env.DEPLOYMENT_MODE; +} + +if (deploymentMode == 'Validium') { mainEnv = process.env.IN_DOCKER ? 'dev_validium_docker' : 'dev_validium'; extEnv = process.env.IN_DOCKER ? 'ext-node-validium-docker' : 'ext-node-validium'; -} else if (process.env.DEPLOYMENT_MODE == 'Rollup') { +} else { + // Rollup deployment mode mainEnv = process.env.IN_DOCKER ? 'docker' : 'dev'; extEnv = process.env.IN_DOCKER ? 'ext-node-docker' : 'ext-node'; -} else { - throw new Error(`Unknown deployment mode: ${process.env.DEPLOYMENT_MODE}`); } const mainLogsPath: string = 'revert_main.log'; const extLogsPath: string = 'revert_ext.log'; @@ -46,10 +72,6 @@ function parseSuggestedValues(jsonString: string): SuggestedValues { }; } -function spawn(cmd: string, args: string[], options: child_process.SpawnOptions): child_process.ChildProcess { - return child_process.spawn(cmd, args, options); -} - function run(cmd: string, args: string[], options: child_process.SpawnOptions): child_process.SpawnSyncReturns { let res = child_process.spawnSync(cmd, args, options); expect(res.error).to.be.undefined; @@ -79,18 +101,33 @@ function fetchEnv(zksyncEnv: string): any { return { ...process.env, ...dotenv.parse(res.stdout) }; } -function runBlockReverter(args: string[]): string { +async function runBlockReverter(args: string[]): Promise { let env = fetchEnv(mainEnv); - env.RUST_LOG = 'off'; - let res = run('./target/release/block_reverter', args, { + + let fileConfigFlags = ''; + if (fileConfig.loadFromFile) { + const configPaths = getAllConfigsPath({ pathToHome, chain: fileConfig.chain }); + fileConfigFlags = ` + --config-path=${configPaths['general.yaml']} + --contracts-config-path=${configPaths['contracts.yaml']} + --secrets-path=${configPaths['secrets.yaml']} + --wallets-path=${configPaths['wallets.yaml']} + --genesis-path=${configPaths['genesis.yaml']} + `; + } + + const cmd = `cd ${pathToHome} && RUST_LOG=off cargo run --bin block_reverter --release -- ${args.join( + ' ' + )} ${fileConfigFlags}`; + const executedProcess = await exec(cmd, { cwd: env.ZKSYNC_HOME, env: { ...env, PATH: process.env.PATH } }); - console.log(res.stderr.toString()); - return res.stdout.toString(); + + return executedProcess.stdout; } async function killServerAndWaitForShutdown(tester: Tester, server: string) { @@ -112,7 +149,7 @@ async function killServerAndWaitForShutdown(tester: Tester, server: string) { } class MainNode { - constructor(public tester: Tester, private proc: child_process.ChildProcess) {} + constructor(public tester: Tester) {} // Terminates all main node processes running. public static async terminateAll() { @@ -129,33 +166,35 @@ class MainNode { public static async spawn( logs: fs.WriteStream, enableConsensus: boolean, - enableExecute: boolean + enableExecute: boolean, + ethClientWeb3Url: string, + apiWeb3JsonRpcHttpUrl: string, + baseTokenAddress: string ): Promise { let env = fetchEnv(mainEnv); env.ETH_SENDER_SENDER_AGGREGATED_BLOCK_EXECUTE_DEADLINE = enableExecute ? '1' : '10000'; // Set full mode for the Merkle tree as it is required to get blocks committed. env.DATABASE_MERKLE_TREE_MODE = 'full'; - console.log(`DATABASE_URL = ${env.DATABASE_URL}`); + + if (fileConfig.loadFromFile) { + replaceAggregatedBlockExecuteDeadline(pathToHome, fileConfig, enableExecute ? 1 : 10000); + } let components = 'api,tree,eth,state_keeper,commitment_generator,da_dispatcher'; if (enableConsensus) { components += ',consensus'; } - let proc = spawn('./target/release/zksync_server', ['--components', components], { - cwd: env.ZKSYNC_HOME, + let proc = runServerInBackground({ + components: [components], stdio: [null, logs, logs], - env: { - ...env, - PATH: process.env.PATH - } + cwd: pathToHome, + env: env, + useZkInception: fileConfig.loadFromFile }); + // Wait until the main node starts responding. - let tester: Tester = await Tester.init( - env.ETH_CLIENT_WEB3_URL, - env.API_WEB3_JSON_RPC_HTTP_URL, - env.CONTRACTS_BASE_TOKEN_ADDR - ); + let tester: Tester = await Tester.init(ethClientWeb3Url, apiWeb3JsonRpcHttpUrl, baseTokenAddress); while (true) { try { await tester.syncWallet.provider.getBlockNumber(); @@ -168,7 +207,7 @@ class MainNode { await utils.sleep(1); } } - return new MainNode(tester, proc); + return new MainNode(tester); } } @@ -186,27 +225,29 @@ class ExtNode { // Spawns an external node. // If enableConsensus is set, the node will use consensus P2P network to fetch blocks. - public static async spawn(logs: fs.WriteStream, enableConsensus: boolean): Promise { + public static async spawn( + logs: fs.WriteStream, + enableConsensus: boolean, + ethClientWeb3Url: string, + enEthClientUrl: string, + baseTokenAddress: string + ): Promise { let env = fetchEnv(extEnv); - console.log(`DATABASE_URL = ${env.DATABASE_URL}`); let args = []; if (enableConsensus) { args.push('--enable-consensus'); } - let proc = spawn('./target/release/zksync_external_node', args, { - cwd: env.ZKSYNC_HOME, + + // Run server in background. + let proc = runExternalNodeInBackground({ stdio: [null, logs, logs], - env: { - ...env, - PATH: process.env.PATH - } + cwd: pathToHome, + env: env, + useZkInception: fileConfig.loadFromFile }); + // Wait until the node starts responding. - let tester: Tester = await Tester.init( - env.EN_ETH_CLIENT_URL, - `http://127.0.0.1:${env.EN_HTTP_PORT}`, - env.CONTRACTS_BASE_TOKEN_ADDR - ); + let tester: Tester = await Tester.init(ethClientWeb3Url, enEthClientUrl, baseTokenAddress); while (true) { try { await tester.syncWallet.provider.getBlockNumber(); @@ -232,15 +273,53 @@ class ExtNode { } describe('Block reverting test', function () { - if (process.env.SKIP_COMPILATION !== 'true') { - compileBinaries(); - } - console.log(`PWD = ${process.env.PWD}`); - const mainLogs: fs.WriteStream = fs.createWriteStream(mainLogsPath, { flags: 'a' }); - const extLogs: fs.WriteStream = fs.createWriteStream(extLogsPath, { flags: 'a' }); - const enableConsensus = process.env.ENABLE_CONSENSUS === 'true'; - console.log(`enableConsensus = ${enableConsensus}`); - const depositAmount = ethers.parseEther('0.001'); + let ethClientWeb3Url: string; + let apiWeb3JsonRpcHttpUrl: string; + let baseTokenAddress: string; + let enEthClientUrl: string; + let operatorAddress: string; + let mainLogs: fs.WriteStream; + let extLogs: fs.WriteStream; + let depositAmount: bigint; + let enableConsensus: boolean; + + before('initialize test', async () => { + if (fileConfig.loadFromFile) { + const secretsConfig = loadConfig({ pathToHome, chain: fileConfig.chain, config: 'secrets.yaml' }); + const generalConfig = loadConfig({ pathToHome, chain: fileConfig.chain, config: 'general.yaml' }); + const contractsConfig = loadConfig({ pathToHome, chain: fileConfig.chain, config: 'contracts.yaml' }); + const externalNodeConfig = loadConfig({ + pathToHome, + chain: fileConfig.chain, + config: 'external_node.yaml' + }); + const walletsConfig = loadConfig({ pathToHome, chain: fileConfig.chain, config: 'wallets.yaml' }); + + ethClientWeb3Url = secretsConfig.l1.l1_rpc_url; + apiWeb3JsonRpcHttpUrl = generalConfig.api.web3_json_rpc.http_url; + baseTokenAddress = contractsConfig.l1.base_token_addr; + enEthClientUrl = externalNodeConfig.main_node_url; + operatorAddress = walletsConfig.operator.address; + } else { + let env = fetchEnv(mainEnv); + ethClientWeb3Url = env.ETH_CLIENT_WEB3_URL; + apiWeb3JsonRpcHttpUrl = env.API_WEB3_JSON_RPC_HTTP_URL; + baseTokenAddress = env.CONTRACTS_BASE_TOKEN_ADDR; + enEthClientUrl = `http://127.0.0.1:${env.EN_HTTP_PORT}`; + // TODO use env variable for this? + operatorAddress = '0xde03a0B5963f75f1C8485B355fF6D30f3093BDE7'; + } + + if (process.env.SKIP_COMPILATION !== 'true' && !fileConfig.loadFromFile) { + compileBinaries(); + } + console.log(`PWD = ${process.env.PWD}`); + mainLogs = fs.createWriteStream(mainLogsPath, { flags: 'a' }); + extLogs = fs.createWriteStream(extLogsPath, { flags: 'a' }); + enableConsensus = process.env.ENABLE_CONSENSUS === 'true'; + console.log(`enableConsensus = ${enableConsensus}`); + depositAmount = ethers.parseEther('0.001'); + }); step('run', async () => { console.log('Make sure that nodes are not running'); @@ -248,23 +327,30 @@ describe('Block reverting test', function () { await MainNode.terminateAll(); console.log('Start main node'); - let mainNode = await MainNode.spawn(mainLogs, enableConsensus, true); + let mainNode = await MainNode.spawn( + mainLogs, + enableConsensus, + true, + ethClientWeb3Url, + apiWeb3JsonRpcHttpUrl, + baseTokenAddress + ); console.log('Start ext node'); - let extNode = await ExtNode.spawn(extLogs, enableConsensus); + let extNode = await ExtNode.spawn(extLogs, enableConsensus, ethClientWeb3Url, enEthClientUrl, baseTokenAddress); await mainNode.tester.fundSyncWallet(); await extNode.tester.fundSyncWallet(); const main_contract = await mainNode.tester.syncWallet.getMainContract(); - const baseTokenAddress = await mainNode.tester.syncWallet.getBaseToken(); - const isETHBasedChain = baseTokenAddress === zksync.utils.ETH_ADDRESS_IN_CONTRACTS; + const baseToken = await mainNode.tester.syncWallet.getBaseToken(); + const isETHBasedChain = baseToken === zksync.utils.ETH_ADDRESS_IN_CONTRACTS; const alice: zksync.Wallet = extNode.tester.emptyWallet(); console.log( 'Finalize an L1 transaction to ensure at least 1 executed L1 batch and that all transactions are processed' ); const h: zksync.types.PriorityOpResponse = await extNode.tester.syncWallet.deposit({ - token: isETHBasedChain ? zksync.utils.LEGACY_ETH_ADDRESS : baseTokenAddress, + token: isETHBasedChain ? zksync.utils.LEGACY_ETH_ADDRESS : baseToken, amount: depositAmount, to: alice.address, approveBaseERC20: true, @@ -274,7 +360,14 @@ describe('Block reverting test', function () { console.log('Restart the main node with L1 batch execution disabled.'); await killServerAndWaitForShutdown(mainNode.tester, 'zksync_server'); - mainNode = await MainNode.spawn(mainLogs, enableConsensus, false); + mainNode = await MainNode.spawn( + mainLogs, + enableConsensus, + false, + ethClientWeb3Url, + apiWeb3JsonRpcHttpUrl, + baseTokenAddress + ); console.log('Commit at least 2 L1 batches which are not executed'); const lastExecuted = await main_contract.getTotalBatchesExecuted(); @@ -282,7 +375,7 @@ describe('Block reverting test', function () { // it gets updated with some batch logs only at the start of the next batch. const initialL1BatchNumber = await main_contract.getTotalBatchesCommitted(); const firstDepositHandle = await extNode.tester.syncWallet.deposit({ - token: isETHBasedChain ? zksync.utils.LEGACY_ETH_ADDRESS : baseTokenAddress, + token: isETHBasedChain ? zksync.utils.LEGACY_ETH_ADDRESS : baseToken, amount: depositAmount, to: alice.address, approveBaseERC20: true, @@ -295,7 +388,7 @@ describe('Block reverting test', function () { } const secondDepositHandle = await extNode.tester.syncWallet.deposit({ - token: isETHBasedChain ? zksync.utils.LEGACY_ETH_ADDRESS : baseTokenAddress, + token: isETHBasedChain ? zksync.utils.LEGACY_ETH_ADDRESS : baseToken, amount: depositAmount, to: alice.address, approveBaseERC20: true, @@ -306,31 +399,31 @@ describe('Block reverting test', function () { await utils.sleep(0.3); } + const alice2 = await alice.getBalance(); while (true) { const lastCommitted = await main_contract.getTotalBatchesCommitted(); console.log(`lastExecuted = ${lastExecuted}, lastCommitted = ${lastCommitted}`); if (lastCommitted - lastExecuted >= 2n) { + console.log('Terminate the main node'); + await killServerAndWaitForShutdown(mainNode.tester, 'zksync_server'); break; } await utils.sleep(0.3); } - const alice2 = await alice.getBalance(); - console.log('Terminate the main node'); - await killServerAndWaitForShutdown(mainNode.tester, 'zksync_server'); console.log('Ask block_reverter to suggest to which L1 batch we should revert'); - const values_json = runBlockReverter([ + const values_json = await runBlockReverter([ 'print-suggested-values', '--json', '--operator-address', - '0xde03a0B5963f75f1C8485B355fF6D30f3093BDE7' + operatorAddress ]); console.log(`values = ${values_json}`); const values = parseSuggestedValues(values_json); assert(lastExecuted === values.lastExecutedL1BatchNumber); console.log('Send reverting transaction to L1'); - runBlockReverter([ + await runBlockReverter([ 'send-eth-transaction', '--l1-batch-number', values.lastExecutedL1BatchNumber.toString(), @@ -346,7 +439,7 @@ describe('Block reverting test', function () { assert(lastCommitted2 === lastExecuted); console.log('Rollback db'); - runBlockReverter([ + await runBlockReverter([ 'rollback-db', '--l1-batch-number', values.lastExecutedL1BatchNumber.toString(), @@ -356,17 +449,24 @@ describe('Block reverting test', function () { ]); console.log('Start main node.'); - mainNode = await MainNode.spawn(mainLogs, enableConsensus, true); + mainNode = await MainNode.spawn( + mainLogs, + enableConsensus, + true, + ethClientWeb3Url, + apiWeb3JsonRpcHttpUrl, + baseTokenAddress + ); console.log('Wait for the external node to detect reorg and terminate'); await extNode.waitForExit(); console.log('Restart external node and wait for it to revert.'); - extNode = await ExtNode.spawn(extLogs, enableConsensus); + extNode = await ExtNode.spawn(extLogs, enableConsensus, ethClientWeb3Url, enEthClientUrl, baseTokenAddress); console.log('Execute an L1 transaction'); const depositHandle = await extNode.tester.syncWallet.deposit({ - token: isETHBasedChain ? zksync.utils.LEGACY_ETH_ADDRESS : baseTokenAddress, + token: isETHBasedChain ? zksync.utils.LEGACY_ETH_ADDRESS : baseToken, amount: depositAmount, to: alice.address, approveBaseERC20: true, @@ -407,9 +507,13 @@ describe('Block reverting test', function () { await checkedRandomTransfer(alice, 1n); }); - after('Terminate nodes', async () => { + after('terminate nodes', async () => { await MainNode.terminateAll(); await ExtNode.terminateAll(); + + if (fileConfig.loadFromFile) { + replaceAggregatedBlockExecuteDeadline(pathToHome, fileConfig, 10); + } }); }); diff --git a/core/tests/revert-test/tests/utils.ts b/core/tests/revert-test/tests/utils.ts new file mode 100644 index 00000000000..4bf38387ccc --- /dev/null +++ b/core/tests/revert-test/tests/utils.ts @@ -0,0 +1,81 @@ +import { exec as _exec, spawn as _spawn, ChildProcessWithoutNullStreams, type ProcessEnvOptions } from 'child_process'; +import { promisify } from 'util'; + +// executes a command in background and returns a child process handle +// by default pipes data to parent's stdio but this can be overridden +export function background({ + command, + stdio = 'inherit', + cwd, + env +}: { + command: string; + stdio: any; + cwd?: ProcessEnvOptions['cwd']; + env?: ProcessEnvOptions['env']; +}): ChildProcessWithoutNullStreams { + command = command.replace(/\n/g, ' '); + return _spawn(command, { stdio: stdio, shell: true, detached: true, cwd, env }); +} + +export function runInBackground({ + command, + components, + stdio, + cwd, + env +}: { + command: string; + components?: string[]; + stdio: any; + cwd?: Parameters[0]['cwd']; + env?: Parameters[0]['env']; +}): ChildProcessWithoutNullStreams { + if (components && components.length > 0) { + command += ` --components=${components.join(',')}`; + } + return background({ command, stdio, cwd, env }); +} + +export function runServerInBackground({ + components, + stdio, + cwd, + env, + useZkInception +}: { + components?: string[]; + stdio: any; + cwd?: Parameters[0]['cwd']; + env?: Parameters[0]['env']; + useZkInception?: boolean; +}): ChildProcessWithoutNullStreams { + let command = useZkInception ? 'zk_inception server' : 'zk server'; + return runInBackground({ command, components, stdio, cwd, env }); +} + +export function runExternalNodeInBackground({ + components, + stdio, + cwd, + env, + useZkInception +}: { + components?: string[]; + stdio: any; + cwd?: Parameters[0]['cwd']; + env?: Parameters[0]['env']; + useZkInception?: boolean; +}): ChildProcessWithoutNullStreams { + let command = useZkInception ? 'zk_inception external-node run' : 'zk external-node'; + return runInBackground({ command, components, stdio, cwd, env }); +} + +// async executor of shell commands +// spawns a new shell and can execute arbitrary commands, like "ls -la | grep .env" +// returns { stdout, stderr } +const promisified = promisify(_exec); +export function exec(command: string, options: ProcessEnvOptions) { + command = command.replace(/\n/g, ' '); + return promisified(command, options); +} diff --git a/etc/utils/src/file-configs.ts b/etc/utils/src/file-configs.ts index 16b89f8f3c9..1675745bca5 100644 --- a/etc/utils/src/file-configs.ts +++ b/etc/utils/src/file-configs.ts @@ -16,7 +16,14 @@ export function shouldLoadConfigFromFile() { } } -export const configNames = ['contracts.yaml', 'general.yaml', 'genesis.yaml', 'secrets.yaml', 'wallets.yaml'] as const; +export const configNames = [ + 'contracts.yaml', + 'general.yaml', + 'genesis.yaml', + 'secrets.yaml', + 'wallets.yaml', + 'external_node.yaml' +] as const; export type ConfigName = (typeof configNames)[number]; @@ -114,3 +121,12 @@ export function getConfigsFolderPath({ }) { return path.join(pathToHome, 'chains', chain, configsFolder ?? 'configs', configsFolderSuffix ?? ''); } + +export function replaceAggregatedBlockExecuteDeadline(pathToHome: string, fileConfig: any, value: number) { + const generalConfigPath = getConfigPath({ pathToHome, chain: fileConfig.chain, config: 'general.yaml' }); + const generalConfig = fs.readFileSync(generalConfigPath, 'utf8'); + const regex = /aggregated_block_execute_deadline:\s*\d+/g; + const newGeneralConfig = generalConfig.replace(regex, `aggregated_block_execute_deadline: ${value}`); + + fs.writeFileSync(generalConfigPath, newGeneralConfig, 'utf8'); +} diff --git a/zk_toolbox/crates/zk_supervisor/src/commands/test/args/revert.rs b/zk_toolbox/crates/zk_supervisor/src/commands/test/args/revert.rs index dc78282fd0d..e4305b6796c 100644 --- a/zk_toolbox/crates/zk_supervisor/src/commands/test/args/revert.rs +++ b/zk_toolbox/crates/zk_supervisor/src/commands/test/args/revert.rs @@ -1,9 +1,11 @@ use clap::Parser; -use crate::messages::MSG_REVERT_TEST_ENABLE_CONSENSUS_HELP; +use crate::messages::{MSG_REVERT_TEST_ENABLE_CONSENSUS_HELP, MSG_TESTS_EXTERNAL_NODE_HELP}; #[derive(Debug, Parser)] pub struct RevertArgs { #[clap(long, help = MSG_REVERT_TEST_ENABLE_CONSENSUS_HELP)] pub enable_consensus: bool, + #[clap(short, long, help = MSG_TESTS_EXTERNAL_NODE_HELP)] + pub external_node: bool, } diff --git a/zk_toolbox/crates/zk_supervisor/src/commands/test/revert.rs b/zk_toolbox/crates/zk_supervisor/src/commands/test/revert.rs index 71de1a2027a..eead83303ee 100644 --- a/zk_toolbox/crates/zk_supervisor/src/commands/test/revert.rs +++ b/zk_toolbox/crates/zk_supervisor/src/commands/test/revert.rs @@ -1,9 +1,12 @@ -use common::{cmd::Cmd, logger, server::Server, spinner::Spinner}; +use common::{cmd::Cmd, logger, spinner::Spinner}; use config::EcosystemConfig; use xshell::{cmd, Shell}; use super::args::revert::RevertArgs; -use crate::messages::{MSG_REVERT_TEST_RUN_INFO, MSG_REVERT_TEST_RUN_SUCCESS}; +use crate::messages::{ + msg_revert_tests_run, MSG_REVERT_TEST_INSTALLING_DEPENDENCIES, MSG_REVERT_TEST_RUN_INFO, + MSG_REVERT_TEST_RUN_SUCCESS, +}; const REVERT_TESTS_PATH: &str = "core/tests/revert-test"; @@ -12,7 +15,6 @@ pub fn run(shell: &Shell, args: RevertArgs) -> anyhow::Result<()> { shell.change_dir(ecosystem_config.link_to_code.join(REVERT_TESTS_PATH)); logger::info(MSG_REVERT_TEST_RUN_INFO); - Server::new(None, ecosystem_config.link_to_code.clone()).build(shell)?; install_and_build_dependencies(shell, &ecosystem_config)?; run_test(shell, &args, &ecosystem_config)?; logger::outro(MSG_REVERT_TEST_RUN_SUCCESS); @@ -25,9 +27,10 @@ fn install_and_build_dependencies( ecosystem_config: &EcosystemConfig, ) -> anyhow::Result<()> { let _dir_guard = shell.push_dir(&ecosystem_config.link_to_code); - let spinner = Spinner::new("Installing and building dependencies..."); + let spinner = Spinner::new(MSG_REVERT_TEST_INSTALLING_DEPENDENCIES); Cmd::new(cmd!(shell, "yarn install")).run()?; Cmd::new(cmd!(shell, "yarn utils build")).run()?; + spinner.finish(); Ok(()) } @@ -37,10 +40,15 @@ fn run_test( args: &RevertArgs, ecosystem_config: &EcosystemConfig, ) -> anyhow::Result<()> { - Spinner::new("Running test...").freeze(); + Spinner::new(&msg_revert_tests_run(args.external_node)).freeze(); + + let cmd = if args.external_node { + cmd!(shell, "yarn mocha tests/revert-and-restart-en.test.ts") + } else { + cmd!(shell, "yarn mocha tests/revert-and-restart.test.ts") + }; - let mut cmd = Cmd::new(cmd!(shell, "yarn mocha tests/revert-and-restart.test.ts")) - .env("CHAIN_NAME", &ecosystem_config.default_chain); + let mut cmd = Cmd::new(cmd).env("CHAIN_NAME", &ecosystem_config.default_chain); if args.enable_consensus { cmd = cmd.env("ENABLE_CONSENSUS", "true"); } diff --git a/zk_toolbox/crates/zk_supervisor/src/messages.rs b/zk_toolbox/crates/zk_supervisor/src/messages.rs index 3275523ed96..863f1c4b1ae 100644 --- a/zk_toolbox/crates/zk_supervisor/src/messages.rs +++ b/zk_toolbox/crates/zk_supervisor/src/messages.rs @@ -93,7 +93,18 @@ pub(super) const MSG_INTEGRATION_TESTS_BUILDING_CONTRACTS: &str = "Building test // Revert tests related messages pub(super) const MSG_REVERT_TEST_ENABLE_CONSENSUS_HELP: &str = "Enable consensus"; +pub(super) const MSG_REVERT_TEST_INSTALLING_DEPENDENCIES: &str = + "Building and installing dependencies. This process may take a lot of time..."; pub(super) const MSG_REVERT_TEST_RUN_INFO: &str = "Running revert and restart test"; +pub(super) fn msg_revert_tests_run(external_node: bool) -> String { + let base = "Running integration tests"; + if external_node { + format!("{} for external node", base) + } else { + format!("{} for main server", base) + } +} + pub(super) const MSG_REVERT_TEST_RUN_SUCCESS: &str = "Revert and restart test ran successfully"; // Cleaning related messages