Skip to content

Commit

Permalink
port loaderror to zksync_error
Browse files Browse the repository at this point in the history
  • Loading branch information
sayon committed Jan 28, 2025
1 parent 2bb8a99 commit cc0d79c
Show file tree
Hide file tree
Showing 20 changed files with 1,901 additions and 791 deletions.
4 changes: 3 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/api_server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ anvil_zksync_types.workspace = true

zksync_types.workspace = true
zksync_web3_decl.workspace = true
zksync_error.workspace = true

anyhow.workspace = true
hex.workspace = true
Expand Down
22 changes: 8 additions & 14 deletions crates/api_server/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use anvil_zksync_core::node::error::LoadStateError;
use jsonrpsee::types::{ErrorCode, ErrorObjectOwned};
use zksync_error::{anvil::state::StateLoaderError, error::IError as _, ZksyncError};
use zksync_web3_decl::error::Web3Error;

#[derive(thiserror::Error, Debug)]
pub enum RpcError {
#[error("failed to load state: {0}")]
LoadState(#[from] LoadStateError),
LoadState(#[from] StateLoaderError),
#[error("method is unsupported")]
Unsupported,
#[error("{0}")]
Expand All @@ -15,17 +15,15 @@ pub enum RpcError {
Other(#[from] anyhow::Error),
}

pub fn to_error_object(error: impl Into<ZksyncError>) -> ErrorObjectOwned {
let error: ZksyncError = error.into();
ErrorObjectOwned::owned(error.get_code() as i32, error.get_message(), Some(error))
}

impl From<RpcError> for ErrorObjectOwned {
fn from(error: RpcError) -> Self {
match error {
RpcError::LoadState(error) => match error {
err @ LoadStateError::HasExistingState
| err @ LoadStateError::EmptyState
| err @ LoadStateError::FailedDecompress(_)
| err @ LoadStateError::FailedDeserialize(_)
| err @ LoadStateError::UnknownStateVersion(_) => invalid_params(err.to_string()),
LoadStateError::Other(error) => internal(error.to_string()),
},
RpcError::LoadState(error) => to_error_object(error),
RpcError::Unsupported => unsupported(),
RpcError::Web3Error(error) => into_jsrpc_error(error),
RpcError::Other(error) => internal(error.to_string()),
Expand All @@ -37,10 +35,6 @@ fn internal(msg: String) -> ErrorObjectOwned {
ErrorObjectOwned::owned(ErrorCode::InternalError.code(), msg, None::<()>)
}

fn invalid_params(msg: String) -> ErrorObjectOwned {
ErrorObjectOwned::owned(ErrorCode::InvalidParams.code(), msg, None::<()>)
}

fn unsupported() -> ErrorObjectOwned {
ErrorObjectOwned::owned(
ErrorCode::MethodNotFound.code(),
Expand Down
4 changes: 2 additions & 2 deletions crates/api_server/src/impls/anvil.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::error::RpcError;
use crate::error::{to_error_object, RpcError};
use anvil_zksync_api_decl::AnvilNamespaceServer;
use anvil_zksync_core::node::InMemoryNode;
use anvil_zksync_types::api::{DetailedTransaction, ResetRequest};
Expand Down Expand Up @@ -29,7 +29,7 @@ impl AnvilNamespaceServer for AnvilNamespace {
}

async fn load_state(&self, bytes: Bytes) -> RpcResult<bool> {
Ok(self.node.load_state(bytes).await.map_err(RpcError::from)?)
Ok(self.node.load_state(bytes).await.map_err(to_error_object)?)
}

async fn mine_detailed(&self) -> RpcResult<Block<DetailedTransaction>> {
Expand Down
4 changes: 3 additions & 1 deletion crates/cli/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -637,6 +637,7 @@ mod tests {
net::{IpAddr, Ipv4Addr},
};
use tempdir::TempDir;
use zksync_error::error::ICustomError as _;
use zksync_types::{H160, U256};

#[test]
Expand Down Expand Up @@ -768,7 +769,8 @@ mod tests {

new_node
.load_state(zksync_types::web3::Bytes(std::fs::read(&state_path)?))
.await?;
.await
.map_err(|e| e.to_unified())?;

// assert the balance from the loaded state is correctly applied
let balance = new_node.get_balance_impl(test_address, None).await?;
Expand Down
32 changes: 18 additions & 14 deletions crates/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,21 @@ use anvil_zksync_core::observability::Observability;
use anvil_zksync_core::system_contracts::SystemContracts;
use anyhow::Context;
use clap::Parser;
use zksync_error::error::IError as _;
use std::fs::File;
use std::sync::Arc;
use std::time::Duration;
use std::{env, net::SocketAddr, str::FromStr};
use tokio::sync::RwLock;
use tower_http::cors::AllowOrigin;
use tracing_subscriber::filter::LevelFilter;
use zksync_error::documentation::Documented as _;
use zksync_types::fee_model::{FeeModelConfigV2, FeeParams};
use zksync_types::H160;
use zksync_web3_decl::namespaces::ZksNamespaceClient;

use zksync_error::anvil::env::generic_error;
use zksync_error::anvil::state::StateLoaderError;
use zksync_error::documentation::Documented as _;
use zksync_error::error::IError as _;

mod bytecode_override;
mod cli;
Expand All @@ -43,7 +44,6 @@ async fn main() -> Result<(), zksync_error::ZksyncError> {
match main_inner().await {
Ok(_) => Ok(()),
Err(e) => {

eprintln!("Error: {}", e.get_message());
if let Ok(Some(documentation)) = e.get_documentation() {
eprintln!("{documentation:#?}")
Expand Down Expand Up @@ -402,17 +402,21 @@ async fn main_inner() -> Result<(), zksync_error::ZksyncError> {
futures::future::select_all(server_handles.into_iter().map(|h| Box::pin(h.stopped())));

// Load state from `--load-state` if provided
if let Some(ref load_state_path) = config.load_state {
let bytes = std::fs::read(load_state_path).expect("Failed to read load state file");
node.load_state(zksync_types::web3::Bytes(bytes))
.await
.map_err(|e| generic_error!("{e}"))?;
}
if let Some(ref state_path) = config.state {
let bytes = std::fs::read(state_path).expect("Failed to read load state file");
node.load_state(zksync_types::web3::Bytes(bytes))
.await
.map_err(|e| generic_error!("{e}"))?;
for state_path in [config.load_state.as_deref(), config.state.as_deref()]
.iter()
.flatten()
{
let path_as_str = state_path.to_str().ok_or(StateLoaderError::GenericError {
message: format!("Invalid path to the state {state_path:?}"),
})?;

let bytes = std::fs::read(state_path).map_err(|error| {
zksync_error::anvil::state::LoadStateError {
path: path_as_str.to_string(),
reason: error.to_string(),
}
})?;
node.load_state(zksync_types::web3::Bytes(bytes)).await?;
}

let state_path = config.dump_state.clone().or_else(|| config.state.clone());
Expand Down
15 changes: 0 additions & 15 deletions crates/core/src/node/error.rs

This file was deleted.

10 changes: 5 additions & 5 deletions crates/core/src/node/in_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use crate::deps::storage_view::StorageView;
use crate::deps::InMemoryStorage;
use crate::filters::EthFilters;
use crate::node::call_error_tracer::CallErrorTracer;
use crate::node::error::LoadStateError;
use crate::node::fee_model::TestNodeFeeInputProvider;
use crate::node::impersonate::{ImpersonationManager, ImpersonationState};
use crate::node::inner::blockchain::ReadBlockchain;
Expand All @@ -32,6 +31,7 @@ use flate2::Compression;
use indexmap::IndexMap;
use once_cell::sync::OnceCell;
use serde::{Deserialize, Serialize};
use zksync_error::anvil::state::StateLoaderError;
use std::collections::{HashMap, HashSet};
use std::io::{Read, Write};
use std::str::FromStr;
Expand Down Expand Up @@ -497,7 +497,7 @@ impl InMemoryNode {
Ok(encoder.finish()?.into())
}

pub async fn load_state(&self, buf: Bytes) -> Result<bool, LoadStateError> {
pub async fn load_state(&self, buf: Bytes) -> Result<bool, StateLoaderError> {
let orig_buf = &buf.0[..];
let mut decoder = GzDecoder::new(orig_buf);
let mut decoded_data = Vec::new();
Expand All @@ -507,16 +507,16 @@ impl InMemoryNode {
tracing::trace!(bytes = buf.0.len(), "decompressing state");
decoder
.read_to_end(decoded_data.as_mut())
.map_err(LoadStateError::FailedDecompress)?;
.map_err(|e| StateLoaderError::StateDecompressionError { details: e.to_string() } )?;
&decoded_data
} else {
&buf.0
};
tracing::trace!(bytes = decoded.len(), "deserializing state");
let state: VersionedState =
serde_json::from_slice(decoded).map_err(LoadStateError::FailedDeserialize)?;
serde_json::from_slice(decoded).map_err(|e| StateLoaderError::StateDeserializationError { details: e.to_string() })?;

self.inner.write().await.load_state(state).await
Ok(self.inner.write().await.load_state(state).await?)
}

pub async fn get_chain_id(&self) -> anyhow::Result<u32> {
Expand Down
10 changes: 5 additions & 5 deletions crates/core/src/node/inner/in_memory_inner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use crate::console_log::ConsoleLogHandler;
use crate::deps::storage_view::StorageView;
use crate::filters::EthFilters;
use crate::node::call_error_tracer::CallErrorTracer;
use crate::node::error::LoadStateError;
use crate::node::keys::StorageKeyLayout;
use crate::node::state::StateV1;
use crate::node::storage_logs::print_storage_logs_details;
Expand All @@ -28,6 +27,7 @@ use anyhow::Context;
use colored::Colorize;
use indexmap::IndexMap;
use once_cell::sync::OnceCell;
use zksync_error::anvil::state::StateLoaderError;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use tokio::sync::RwLock;
Expand Down Expand Up @@ -1162,24 +1162,24 @@ impl InMemoryNodeInner {
}))
}

pub async fn load_state(&mut self, state: VersionedState) -> Result<bool, LoadStateError> {
pub async fn load_state(&mut self, state: VersionedState) -> Result<bool, StateLoaderError> {
let mut storage = self.blockchain.write().await;
if storage.blocks.len() > 1 {
tracing::debug!(
blocks = storage.blocks.len(),
"node has existing state; refusing to load new state"
);
return Err(LoadStateError::HasExistingState);
return Err(StateLoaderError::LoadingStateOverExistingStateError);
}
let state = match state {
VersionedState::V1 { state, .. } => state,
VersionedState::Unknown { version } => {
return Err(LoadStateError::UnknownStateVersion(version))
return Err(StateLoaderError::UnknownStateVersionError { version: version.into() } )
}
};
if state.blocks.is_empty() {
tracing::debug!("new state has no blocks; refusing to load");
return Err(LoadStateError::EmptyState);
return Err(StateLoaderError::LoadEmptyStateError);
}

storage.load_blocks(&mut self.time, state.blocks);
Expand Down
1 change: 0 additions & 1 deletion crates/core/src/node/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
mod call_error_tracer;
mod debug;
pub mod error;
mod eth;
mod fee_model;
mod impersonate;
Expand Down
1 change: 1 addition & 0 deletions crates/zksync_error/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ serde_json = { version = "1.0.128" }
strum = "0.26.3"
strum_macros = "0.26.4"
zksync-error-description = { git = "https://github.com/sayon/error-codegen-poc", branch = "main"}
anyhow = "1.0"
Loading

0 comments on commit cc0d79c

Please sign in to comment.