Skip to content

Commit

Permalink
chore: update era-test-node dep to anvil-zksync
Browse files Browse the repository at this point in the history
  • Loading branch information
dutterbutter committed Jan 6, 2025
1 parent 8159789 commit 6a9b866
Show file tree
Hide file tree
Showing 8 changed files with 654 additions and 668 deletions.
1,124 changes: 539 additions & 585 deletions Cargo.lock

Large diffs are not rendered by default.

6 changes: 5 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,11 @@ anstyle = "1.0"
terminal_size = "0.4"

## zksync
era_test_node = { git = "https://github.com/matter-labs/era-test-node.git", rev = "94503847b402f0161c3372d5f357a4cb16a2d66d" }
anvil-zksync = { git = "https://github.com/matter-labs/anvil-zksync.git", rev = "070c569a332436a17836fb5a548e323ea1ef878c", package = "anvil-zksync" }
anvil_zksync_core = { git = "https://github.com/matter-labs/anvil-zksync.git", rev = "070c569a332436a17836fb5a548e323ea1ef878c", package = "anvil_zksync_core" }
anvil_zksync_types = { git = "https://github.com/matter-labs/anvil-zksync.git", rev = "070c569a332436a17836fb5a548e323ea1ef878c", package = "anvil_zksync_types" }
anvil_zksync_config = { git = "https://github.com/matter-labs/anvil-zksync.git", rev = "070c569a332436a17836fb5a548e323ea1ef878c", package = "anvil_zksync_config" }
anvil_zksync_api_server = { git = "https://github.com/matter-labs/anvil-zksync.git", rev = "070c569a332436a17836fb5a548e323ea1ef878c", package = "anvil_zksync_api_server" }
zksync_basic_types = { git = "https://github.com/matter-labs/zksync-era.git", rev = "6c034f6e180cc92e99766f14c8840c90efa56cec" }
zksync_types = { git = "https://github.com/matter-labs/zksync-era.git", rev = "6c034f6e180cc92e99766f14c8840c90efa56cec" }
zksync_state = { git = "https://github.com/matter-labs/zksync-era.git", rev = "6c034f6e180cc92e99766f14c8840c90efa56cec" }
Expand Down
7 changes: 4 additions & 3 deletions crates/test-utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,13 @@ rand.workspace = true
snapbox = { version = "0.6", features = ["json", "regex"] }
tokio.workspace = true
tempfile.workspace = true
tower-http = { version = "0.6.2", features = ["cors"] }

# zk
zksync_types.workspace = true
era_test_node.workspace = true
jsonrpc-core = { git = "https://github.com/matter-labs/jsonrpc.git", branch = "master" }
jsonrpc-http-server = { git = "https://github.com/matter-labs/jsonrpc.git", branch = "master" }
anvil_zksync_core.workspace = true
anvil_zksync_api_server.workspace = true
anvil_zksync_config.workspace = true

[dev-dependencies]
tokio.workspace = true
Expand Down
129 changes: 69 additions & 60 deletions crates/test-utils/src/zksync.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
//! Contains in-memory implementation of era-test-node.
use std::{
net::{IpAddr, Ipv4Addr, SocketAddr},
str::FromStr,
};
use std::{net::SocketAddr, str::FromStr};

use era_test_node::{
http_fork_source::HttpForkSource,
namespaces::{
ConfigurationApiNamespaceT, DebugNamespaceT, EthNamespaceT, EthTestNodeNamespaceT,
EvmNamespaceT, HardhatNamespaceT, NetNamespaceT, Web3NamespaceT, ZksNamespaceT,
},
node::InMemoryNode,
use anvil_zksync_api_server::NodeServerBuilder;
use anvil_zksync_config::TestNodeConfig;
use anvil_zksync_core::node::{
BlockSealer, BlockSealerMode, ImpersonationManager, InMemoryNode, TimestampManager, TxPool,
};
use jsonrpc_core::IoHandler;
use zksync_types::H160;
use std::time::Duration;
use tower_http::cors::AllowOrigin;
use zksync_types::{H160, U256};

/// List of legacy wallets (address, private key) that we seed with tokens at start.
const LEGACY_RICH_WALLETS: [(&str, &str); 10] = [
Expand Down Expand Up @@ -113,7 +108,7 @@ const RICH_WALLETS: [(&str, &str, &str); 10] = [
),
];

/// In-memory era-test-node that is stopped when dropped.
/// In-memory anvil-zksync that is stopped when dropped.
pub struct ZkSyncNode {
port: u16,
_guard: tokio::sync::oneshot::Sender<()>,
Expand All @@ -126,69 +121,83 @@ impl ZkSyncNode {
format!("http://127.0.0.1:{}", self.port)
}

/// Start era-test-node in memory, binding a random available port
/// Start anvil-zksync in memory, binding a random available port
///
/// The server is automatically stopped when the instance is dropped.
pub fn start() -> Self {
let (_guard, _guard_rx) = tokio::sync::oneshot::channel::<()>();

let io_handler = {
let node: InMemoryNode<HttpForkSource> =
InMemoryNode::new(None, None, Default::default(), None);

for wallet in LEGACY_RICH_WALLETS.iter() {
let address = wallet.0;
node.set_rich_account(H160::from_str(address).unwrap());
}
for wallet in RICH_WALLETS.iter() {
let address = wallet.0;
node.set_rich_account(H160::from_str(address).unwrap());
}

let mut io = IoHandler::default();

io.extend_with(NetNamespaceT::to_delegate(node.clone()));
io.extend_with(Web3NamespaceT::to_delegate(node.clone()));
io.extend_with(ConfigurationApiNamespaceT::to_delegate(node.clone()));
io.extend_with(DebugNamespaceT::to_delegate(node.clone()));
io.extend_with(EthNamespaceT::to_delegate(node.clone()));
io.extend_with(EthTestNodeNamespaceT::to_delegate(node.clone()));
io.extend_with(EvmNamespaceT::to_delegate(node.clone()));
io.extend_with(HardhatNamespaceT::to_delegate(node.clone()));
io.extend_with(ZksNamespaceT::to_delegate(node));
io
let (stop_tx, _stop_rx) = tokio::sync::oneshot::channel::<()>();
let (port_tx, mut port_rx) = tokio::sync::oneshot::channel();

let config = TestNodeConfig::default();

let time = TimestampManager::default();
let impersonation = ImpersonationManager::default();
let pool = TxPool::new(impersonation.clone(), config.transaction_order);
let sealing_mode = if config.no_mining {
BlockSealerMode::noop()
} else if let Some(block_time) = config.block_time {
BlockSealerMode::fixed_time(config.max_transactions, block_time)
} else {
BlockSealerMode::immediate(config.max_transactions, pool.add_tx_listener())
};
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0);
let (port_tx, port) = tokio::sync::oneshot::channel();
let block_sealer = BlockSealer::new(sealing_mode);

let node: InMemoryNode = InMemoryNode::new(
None,
None,
&config,
time,
impersonation,
pool,
block_sealer,
);

for wallet in LEGACY_RICH_WALLETS.iter() {
let address = wallet.0;
node.set_rich_account(
H160::from_str(address).unwrap(),
U256::from(100u128 * 10u128.pow(18)),
);
}
for wallet in RICH_WALLETS.iter() {
let address = wallet.0;
node.set_rich_account(
H160::from_str(address).unwrap(),
U256::from(100u128 * 10u128.pow(18)),
);
}

std::thread::spawn(move || {
let runtime = tokio::runtime::Builder::new_multi_thread()
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.worker_threads(2)
.build()
.unwrap();

let server = jsonrpc_http_server::ServerBuilder::new(io_handler)
.threads(1)
.event_loop_executor(runtime.handle().clone())
.start_http(&addr)
.unwrap();
rt.block_on(async move {
let allow_origin = AllowOrigin::any();
let server_builder = NodeServerBuilder::new(node.clone(), allow_origin);

let server = server_builder.build(SocketAddr::from(([0, 0, 0, 0], 0))).await;

// if no receiver was ready to receive the spawning thread died
_ = port_tx.send(server.address().port());
// we only care that the channel is alive
_ = tokio::task::block_in_place(move || runtime.block_on(_guard_rx));
// if no receiver was ready to receive the spawning thread died
_ = port_tx.send(0);

server.close();
let handle = server.run();

tokio::select! {
_ = handle.stopped() => {
},
};
});
});

// wait for server to start
std::thread::sleep(std::time::Duration::from_millis(600));
let port =
tokio::task::block_in_place(move || tokio::runtime::Handle::current().block_on(port))
.expect("failed to start server");
std::thread::sleep(Duration::from_millis(500));

let port = port_rx.try_recv().expect("Failed to receive server port on channel");

Self { _guard, port }
Self { port, _guard: stop_tx }
}

pub fn rich_wallets() -> impl Iterator<Item = (&'static str, &'static str, &'static str)> {
Expand Down
4 changes: 3 additions & 1 deletion crates/zksync/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ serde.workspace = true
zksync_multivm.workspace = true
zksync_basic_types.workspace = true
zksync_types.workspace = true
era_test_node.workspace = true
anvil_zksync_core.workspace = true
anvil_zksync_types.workspace = true
anvil_zksync_config.workspace = true
zksync_utils.workspace = true
zksync_contracts.workspace = true
zksync_state.workspace = true
Expand Down
4 changes: 2 additions & 2 deletions crates/zksync/core/src/vm/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ where

/// Create a new instance of [ZKEVMData] with system contracts.
pub fn new_with_system_contracts(ecx: &'a mut EvmContext<DB>, chain_id: L2ChainId) -> Self {
let contracts = era_test_node::system_contracts::get_deployed_contracts(
&era_test_node::system_contracts::Options::BuiltInWithoutSecurity,
let contracts = anvil_zksync_core::deps::system_contracts::get_deployed_contracts(
&anvil_zksync_config::types::SystemContractsOptions::BuiltInWithoutSecurity,
false,
);
let system_context_init_log = get_system_context_init_logs(chain_id);
Expand Down
46 changes: 31 additions & 15 deletions crates/zksync/core/src/vm/inspect.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use alloy_primitives::{hex, FixedBytes, Log};
use era_test_node::{
config::node::ShowCalls,
formatter,
system_contracts::{Options, SystemContracts},
utils::bytecode_to_factory_dep,
use anvil_zksync_config::types::SystemContractsOptions;
use anvil_zksync_core::{
formatter, system_contracts::SystemContracts, utils::bytecode_to_factory_dep,
};
use anvil_zksync_types::ShowCalls;
use itertools::Itertools;
use revm::{
db::states::StorageSlot,
Expand All @@ -19,7 +18,7 @@ use tracing::{debug, error, info, trace, warn};
use zksync_basic_types::{ethabi, L2ChainId, Nonce, H160, H256, U256};
use zksync_multivm::{
interface::{
Call, CallType, ExecutionResult, Halt, InspectExecutionMode, VmEvent,
Call, CallType, ExecutionResult, Halt, InspectExecutionMode, TxExecutionMode, VmEvent,
VmExecutionResultAndLogs, VmFactory, VmInterface, VmRevertReason,
},
tracers::CallTracer,
Expand Down Expand Up @@ -470,8 +469,12 @@ fn inspect_inner<S: ReadStorage>(
) -> InnerZkVmResult {
let batch_env = create_l1_batch_env(storage.clone(), &ccx.zk_env);

let system_contracts = SystemContracts::from_options(&Options::BuiltInWithoutSecurity, false);
let system_env = create_system_env(system_contracts.baseline_contracts, chain_id);
let system_contracts =
SystemContracts::from_options(&SystemContractsOptions::BuiltInWithoutSecurity, false);
let system_env = create_system_env(
system_contracts.contracts(TxExecutionMode::VerifyExecute, false).clone(),
chain_id,
);

let mut vm: Vm<_, HistoryDisabled> = Vm::new(batch_env.clone(), system_env, storage.clone());

Expand Down Expand Up @@ -501,7 +504,7 @@ fn inspect_inner<S: ReadStorage>(
)
.into_tracer_pointer(),
];
let compressed_bytecodes = vm.push_transaction(tx).compressed_bytecodes.into_owned();
let compressed_bytecodes = vm.push_transaction(tx.clone()).compressed_bytecodes.into_owned();
let mut tx_result = vm.inspect(&mut tracers.into(), InspectExecutionMode::OneTx);

let mut call_traces = Arc::try_unwrap(call_tracer_result).unwrap().take().unwrap_or_default();
Expand Down Expand Up @@ -554,8 +557,8 @@ fn inspect_inner<S: ReadStorage>(
refunded: bootloader_debug.refund_by_operator,
bootloader_debug,
};

formatter::print_vm_details(&tx_result);
let mut formatter = formatter::Formatter::new();
formatter.print_vm_details(&tx_result);

info!("=== Console Logs: ");
let log_parser = ConsoleLogParser::new();
Expand All @@ -572,21 +575,34 @@ fn inspect_inner<S: ReadStorage>(
let resolve_hashes = get_env_var::<bool>("ZK_DEBUG_RESOLVE_HASHES");
let show_outputs = get_env_var::<bool>("ZK_DEBUG_SHOW_OUTPUTS");
info!("=== Calls: ");
for call in call_traces.iter() {
formatter::print_call(call, 0, &ShowCalls::All, show_outputs, resolve_hashes);
let num_calls = call_traces.len();
for (i, call) in call_traces.iter().enumerate() {
let is_last_sibling = i == num_calls - 1;
formatter.print_call(
tx.initiator_account(),
tx.execute.contract_address,
call,
is_last_sibling,
&ShowCalls::All,
show_outputs,
resolve_hashes,
);
}

let mut deployed_bytecode_hashes = HashMap::<H160, H256>::default();
info!("==== {}", format!("{} events", tx_result.logs.events.len()));
for event in &tx_result.logs.events {
let num_events = tx_result.logs.events.len();
for (i, event) in tx_result.logs.events.iter().enumerate() {
let is_last = i == num_events - 1;

if event.address == CONTRACT_DEPLOYER_ADDRESS {
deployed_bytecode_hashes.insert(
event.indexed_topics.get(3).cloned().unwrap_or_default().to_h160(),
event.indexed_topics.get(2).cloned().unwrap_or_default(),
);
}

formatter::print_event(event, resolve_hashes);
formatter.print_event(event, resolve_hashes, is_last);
}

let bytecodes = compressed_bytecodes
Expand Down
2 changes: 1 addition & 1 deletion crates/zksync/core/src/vm/tracers/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/// Contains tracer implementations for the zkEVM
pub mod bootloader {
pub use era_test_node::bootloader_debug::{BootloaderDebug, BootloaderDebugTracer};
pub use anvil_zksync_core::bootloader_debug::{BootloaderDebug, BootloaderDebugTracer};
}
pub mod cheatcode;
pub mod error;

0 comments on commit 6a9b866

Please sign in to comment.