From 1200ee12438f69ba8d4b2c08541e4e172b504591 Mon Sep 17 00:00:00 2001 From: Danil Date: Fri, 8 Dec 2023 15:10:17 +0100 Subject: [PATCH] apply formatting Signed-off-by: Danil --- crates/era-revm/src/cheatcodes.rs | 148 +++++++++------------------- crates/era-revm/src/db.rs | 41 ++++---- crates/era-revm/src/factory_deps.rs | 15 +-- crates/era-revm/src/transactions.rs | 62 +++++------- 4 files changed, 92 insertions(+), 174 deletions(-) diff --git a/crates/era-revm/src/cheatcodes.rs b/crates/era-revm/src/cheatcodes.rs index e6ace5991..bb665c2ad 100644 --- a/crates/era-revm/src/cheatcodes.rs +++ b/crates/era-revm/src/cheatcodes.rs @@ -1,18 +1,19 @@ -use era_test_node::fork::{ForkSource, ForkStorage}; -use era_test_node::utils::bytecode_to_factory_dep; -use ethers::utils::to_checksum; -use ethers::{abi::AbiDecode, prelude::abigen}; +use era_test_node::{ + fork::{ForkSource, ForkStorage}, + utils::bytecode_to_factory_dep, +}; +use ethers::{abi::AbiDecode, prelude::abigen, utils::to_checksum}; use itertools::Itertools; -use multivm::interface::dyn_tracers::vm_1_3_3::DynTracer; -use multivm::interface::tracer::TracerExecutionStatus; -use multivm::vm_refunds_enhancement::{ - BootloaderState, HistoryMode, SimpleMemory, VmTracer, ZkSyncVmState, +use multivm::{ + interface::{dyn_tracers::vm_1_3_3::DynTracer, tracer::TracerExecutionStatus}, + vm_refunds_enhancement::{BootloaderState, HistoryMode, SimpleMemory, VmTracer, ZkSyncVmState}, + zk_evm_1_3_1::zkevm_opcode_defs::RET_IMPLICIT_RETURNDATA_PARAMS_REGISTER, + zk_evm_1_3_3::{ + tracing::{BeforeExecutionData, VmLocalStateData}, + vm_state::PrimitiveValue, + }, }; -use multivm::zk_evm_1_3_1::zkevm_opcode_defs::RET_IMPLICIT_RETURNDATA_PARAMS_REGISTER; -use multivm::zk_evm_1_3_3::tracing::{BeforeExecutionData, VmLocalStateData}; -use multivm::zk_evm_1_3_3::vm_state::PrimitiveValue; -use std::collections::HashMap; -use std::fmt::Debug; +use std::{collections::HashMap, fmt::Debug}; use zk_evm::zkevm_opcode_defs::{FatPointer, Opcode, CALL_IMPLICIT_CALLDATA_FAT_PTR_REGISTER}; use zksync_basic_types::{AccountTreeId, Address, H160, H256, U256}; use zksync_state::{ReadStorage, StoragePtr, StorageView}; @@ -20,9 +21,8 @@ use zksync_types::{ block::{pack_block_info, unpack_block_info}, get_code_key, get_nonce_key, utils::{decompose_full_nonce, nonces_to_full_nonce, storage_key_for_eth_balance}, - StorageKey, + LogQuery, StorageKey, Timestamp, }; -use zksync_types::{LogQuery, Timestamp}; use zksync_utils::{h256_to_u256, u256_to_h256}; // address(uint160(uint256(keccak256('hevm cheat code')))) @@ -94,15 +94,8 @@ pub struct CheatcodeTracer { #[derive(Debug, Clone)] enum FinishCycleOneTimeActions { - StorageWrite { - key: StorageKey, - read_value: H256, - write_value: H256, - }, - StoreFactoryDep { - hash: U256, - bytecode: Vec, - }, + StorageWrite { key: StorageKey, read_value: H256, write_value: H256 }, + StoreFactoryDep { hash: U256, bytecode: Vec }, } #[derive(Debug, Default, Clone)] @@ -129,11 +122,11 @@ impl DynTracer VmTracer TracerExecutionStatus { while let Some(action) = self.one_time_actions.pop() { match action { - FinishCycleOneTimeActions::StorageWrite { - key, - read_value, - write_value, - } => { + FinishCycleOneTimeActions::StorageWrite { key, read_value, write_value } => { state.storage.write_value(LogQuery { timestamp: Timestamp(state.local_state.timestamp), tx_number_in_block: state.local_state.tx_number_in_block, @@ -217,12 +206,9 @@ impl VmTracer { - state.decommittment_processor.populate( - vec![(hash, bytecode)], - Timestamp(state.local_state.timestamp), - ) - } + FinishCycleOneTimeActions::StoreFactoryDep { hash, bytecode } => state + .decommittment_processor + .populate(vec![(hash, bytecode)], Timestamp(state.local_state.timestamp)), } } @@ -233,10 +219,7 @@ impl VmTracer { - tracing::info!( - "👷 Getting storage slot {:?} for account {:?}", - slot, - account - ); + tracing::info!("👷 Getting storage slot {:?} for account {:?}", slot, account); let key = StorageKey::new(AccountTreeId::new(account), H256(slot)); let mut storage = storage.borrow_mut(); let value = storage.read_value(&key); @@ -345,11 +324,7 @@ impl CheatcodeTracer { &mut storage, ); } - SerializeAddress(SerializeAddressCall { - object_key, - value_key, - value, - }) => { + SerializeAddress(SerializeAddressCall { object_key, value_key, value }) => { tracing::info!( "👷 Serializing address {:?} with key {:?} to object {:?}", value, @@ -361,18 +336,13 @@ impl CheatcodeTracer { }); //write to serialized_objects - self.serialized_objects - .insert(object_key.clone(), json_value.to_string()); + self.serialized_objects.insert(object_key.clone(), json_value.to_string()); let address = Address::from(value); let address_with_checksum = to_checksum(&address, None); self.add_trimmed_return_data(address_with_checksum.as_bytes()); } - SerializeBool(SerializeBoolCall { - object_key, - value_key, - value, - }) => { + SerializeBool(SerializeBoolCall { object_key, value_key, value }) => { tracing::info!( "👷 Serializing bool {:?} with key {:?} to object {:?}", value, @@ -383,17 +353,12 @@ impl CheatcodeTracer { value_key: value }); - self.serialized_objects - .insert(object_key.clone(), json_value.to_string()); + self.serialized_objects.insert(object_key.clone(), json_value.to_string()); let bool_value = value.to_string(); self.add_trimmed_return_data(bool_value.as_bytes()); } - SerializeUint(SerializeUintCall { - object_key, - value_key, - value, - }) => { + SerializeUint(SerializeUintCall { object_key, value_key, value }) => { tracing::info!( "👷 Serializing uint256 {:?} with key {:?} to object {:?}", value, @@ -404,8 +369,7 @@ impl CheatcodeTracer { value_key: value }); - self.serialized_objects - .insert(object_key.clone(), json_value.to_string()); + self.serialized_objects.insert(object_key.clone(), json_value.to_string()); let uint_value = value.to_string(); self.add_trimmed_return_data(uint_value.as_bytes()); @@ -423,7 +387,7 @@ impl CheatcodeTracer { account_nonce, nonce ); - return; + return } account_nonce = nonce.into(); if deployment_nonce.as_u64() >= nonce { @@ -432,23 +396,16 @@ impl CheatcodeTracer { deployment_nonce, nonce ); - return; + return } deployment_nonce = nonce.into(); let enforced_full_nonce = nonces_to_full_nonce(account_nonce, deployment_nonce); - tracing::info!( - "👷 Nonces for account {:?} have been set to {}", - account, - nonce - ); + tracing::info!("👷 Nonces for account {:?} have been set to {}", account, nonce); self.write_storage(nonce_key, u256_to_h256(enforced_full_nonce), &mut storage); } StartPrank(StartPrankCall { sender }) => { tracing::info!("👷 Starting prank to {sender:?}"); - self.permanent_actions.start_prank = Some(StartPrankOpts { - sender, - origin: None, - }); + self.permanent_actions.start_prank = Some(StartPrankOpts { sender, origin: None }); } StartPrankWithOrigin(StartPrankWithOriginCall { sender, origin }) => { tracing::info!("👷 Starting prank to {sender:?} with origin {origin:?}"); @@ -459,19 +416,14 @@ impl CheatcodeTracer { let original_tx_origin = storage.borrow_mut().read_value(&key); self.write_storage(key, origin.into(), &mut storage.borrow_mut()); - self.permanent_actions.start_prank = Some(StartPrankOpts { - sender, - origin: Some(original_tx_origin), - }); + self.permanent_actions.start_prank = + Some(StartPrankOpts { sender, origin: Some(original_tx_origin) }); } StopPrank(StopPrankCall) => { tracing::info!("👷 Stopping prank"); - if let Some(origin) = self - .permanent_actions - .start_prank - .as_ref() - .and_then(|v| v.origin) + if let Some(origin) = + self.permanent_actions.start_prank.as_ref().and_then(|v| v.origin) { let key = StorageKey::new( AccountTreeId::new(zksync_types::SYSTEM_CONTEXT_ADDRESS), @@ -482,11 +434,7 @@ impl CheatcodeTracer { self.permanent_actions.start_prank = None; } - Store(StoreCall { - account, - slot, - value, - }) => { + Store(StoreCall { account, slot, value }) => { tracing::info!( "👷 Setting storage slot {:?} for account {:?} to {:?}", slot, @@ -547,8 +495,7 @@ impl CheatcodeTracer { } fn store_factory_dep(&mut self, hash: U256, bytecode: Vec) { - self.one_time_actions - .push(FinishCycleOneTimeActions::StoreFactoryDep { hash, bytecode }); + self.one_time_actions.push(FinishCycleOneTimeActions::StoreFactoryDep { hash, bytecode }); } fn write_storage( @@ -557,12 +504,11 @@ impl CheatcodeTracer { write_value: H256, storage: &mut StorageView>, ) { - self.one_time_actions - .push(FinishCycleOneTimeActions::StorageWrite { - key, - read_value: storage.read_value(&key), - write_value, - }); + self.one_time_actions.push(FinishCycleOneTimeActions::StorageWrite { + key, + read_value: storage.read_value(&key), + write_value, + }); } fn add_trimmed_return_data(&mut self, data: &[u8]) { diff --git a/crates/era-revm/src/db.rs b/crates/era-revm/src/db.rs index fdf0a25c3..38459cc67 100644 --- a/crates/era-revm/src/db.rs +++ b/crates/era-revm/src/db.rs @@ -4,6 +4,7 @@ /// in the Database object. /// This code doesn't do any mutatios to Database: after each transaction run, the Revm /// is usually collecing all the diffs - and applies them to database itself. + use std::{ collections::HashMap, fmt::Debug, @@ -74,16 +75,15 @@ where fn read_storage_internal(&self, address: H160, idx: U256) -> H256 { let mut db = self.db.lock().unwrap(); - let result = db - .storage(h160_to_address(address), u256_to_revm_u256(idx)) - .unwrap(); + let result = db.storage(h160_to_address(address), u256_to_revm_u256(idx)).unwrap(); revm_u256_to_h256(result) } /// Tries to fetch the bytecode that belongs to a given account. - /// Start, by looking into account code storage - to see if there is any information about the bytecode for this account. - /// If there is none - check if any of the bytecode hashes are matching the account. - /// And as the final step - read the bytecode from the database itself. + /// Start, by looking into account code storage - to see if there is any information about the + /// bytecode for this account. If there is none - check if any of the bytecode hashes are + /// matching the account. And as the final step - read the bytecode from the database + /// itself. pub fn fetch_account_code( &self, account: H160, @@ -97,10 +97,8 @@ where )) { let new_bytecode_hash = *v; if let Some(new_bytecode) = bytecodes.get(&h256_to_u256(new_bytecode_hash)) { - let u8_bytecode: Vec = new_bytecode - .iter() - .flat_map(|x| u256_to_h256(*x).to_fixed_bytes()) - .collect(); + let u8_bytecode: Vec = + new_bytecode.iter().flat_map(|x| u256_to_h256(*x).to_fixed_bytes()).collect(); return Some(( new_bytecode_hash, @@ -108,7 +106,7 @@ where bytecode: Bytes::copy_from_slice(u8_bytecode.as_slice()), state: revm::primitives::BytecodeState::Raw, }, - )); + )) } } @@ -117,10 +115,8 @@ where // so we have to iterate over all the bytecodes, truncate their hash and then compare. for (k, v) in bytecodes { if h256_to_h160(&u256_to_h256(*k)) == account { - let u8_bytecode: Vec = v - .iter() - .flat_map(|x| u256_to_h256(*x).to_fixed_bytes()) - .collect(); + let u8_bytecode: Vec = + v.iter().flat_map(|x| u256_to_h256(*x).to_fixed_bytes()).collect(); return Some(( u256_to_h256(*k), @@ -128,7 +124,7 @@ where bytecode: Bytes::copy_from_slice(u8_bytecode.as_slice()), state: revm::primitives::BytecodeState::Raw, }, - )); + )) } } @@ -268,6 +264,7 @@ where } #[cfg(test)] +#[allow(clippy::box_default)] mod tests { use maplit::hashmap; use revm::primitives::AccountInfo; @@ -442,9 +439,9 @@ mod tests { .get_storage_at( H160::zero(), U256::zero(), - Some(BlockIdVariant::BlockNumber( - zksync_types::api::BlockNumber::Number(zksync_basic_types::U64::from(2)), - )), + Some(BlockIdVariant::BlockNumber(zksync_types::api::BlockNumber::Number( + zksync_basic_types::U64::from(2), + ))), ) .expect("failed getting storage"); @@ -467,9 +464,9 @@ mod tests { db.get_storage_at( H160::zero(), U256::zero(), - Some(BlockIdVariant::BlockNumber( - zksync_types::api::BlockNumber::Number(zksync_basic_types::U64::from(1)), - )), + Some(BlockIdVariant::BlockNumber(zksync_types::api::BlockNumber::Number( + zksync_basic_types::U64::from(1), + ))), ) .unwrap(); } diff --git a/crates/era-revm/src/factory_deps.rs b/crates/era-revm/src/factory_deps.rs index d7dd4d244..f5b6d732d 100644 --- a/crates/era-revm/src/factory_deps.rs +++ b/crates/era-revm/src/factory_deps.rs @@ -4,8 +4,8 @@ use zksync_basic_types::H256; /// Factory deps packer. /// -/// EVM assumes that all the necessary bytecodes (factory deps) are present within the original bytecode. -/// In case of Era - they are actually returned separate from the compiler. +/// EVM assumes that all the necessary bytecodes (factory deps) are present within the original +/// bytecode. In case of Era - they are actually returned separate from the compiler. /// /// So in order to fit to the REVM / Forge - we "serialize" all the factory deps into /// one huge "fake" bytecode string - and then pass them around. @@ -20,11 +20,7 @@ pub struct PackedEraBytecode { impl PackedEraBytecode { pub fn new(hash: String, bytecode: String, factory_deps: Vec) -> Self { - Self { - hash, - bytecode, - factory_deps, - } + Self { hash, bytecode, factory_deps } } pub fn to_vec(&self) -> Vec { serde_json::to_vec(self).unwrap() @@ -50,10 +46,7 @@ impl PackedEraBytecode { } fn ensure_chunkable(bytes: &[u8]) { - assert!( - bytes.len() % 32 == 0, - "Bytes must be divisible by 32 to split into chunks" - ); + assert!(bytes.len() % 32 == 0, "Bytes must be divisible by 32 to split into chunks"); } pub fn bytes_to_chunks(bytes: &[u8]) -> Vec<[u8; 32]> { diff --git a/crates/era-revm/src/transactions.rs b/crates/era-revm/src/transactions.rs index 9aecb74f1..e82341712 100644 --- a/crates/era-revm/src/transactions.rs +++ b/crates/era-revm/src/transactions.rs @@ -20,10 +20,9 @@ use std::{ sync::{Arc, Mutex}, }; use zksync_basic_types::{web3::signing::keccak256, L1BatchNumber, L2ChainId, H160, H256, U256}; -use zksync_types::api::Block; use zksync_types::{ - fee::Fee, l2::L2Tx, transaction_request::PaymasterParams, PackedEthSignature, StorageKey, - StorageLogQueryType, ACCOUNT_CODE_STORAGE_ADDRESS, + api::Block, fee::Fee, l2::L2Tx, transaction_request::PaymasterParams, PackedEthSignature, + StorageKey, StorageLogQueryType, ACCOUNT_CODE_STORAGE_ADDRESS, }; use revm::primitives::U256 as revmU256; @@ -40,10 +39,10 @@ use crate::{ fn contract_address_from_tx_result(execution_result: &VmExecutionResultAndLogs) -> Option { for query in execution_result.logs.storage_logs.iter().rev() { - if query.log_type == StorageLogQueryType::InitialWrite - && query.log_query.address == ACCOUNT_CODE_STORAGE_ADDRESS + if query.log_type == StorageLogQueryType::InitialWrite && + query.log_query.address == ACCOUNT_CODE_STORAGE_ADDRESS { - return Some(h256_to_account_address(&u256_to_h256(query.log_query.key))); + return Some(h256_to_account_address(&u256_to_h256(query.log_query.key))) } } None @@ -56,8 +55,8 @@ pub fn encode_deploy_params_create( contract_hash: H256, constructor_input: Vec, ) -> Vec { - // TODO (SMA-1608): We should not re-implement the ABI parts in different places, instead have the ABI available - // from the `zksync_contracts` crate. + // TODO (SMA-1608): We should not re-implement the ABI parts in different places, instead have + // the ABI available from the `zksync_contracts` crate. let signature = ethabi::short_signature( "create", &[ @@ -80,7 +79,8 @@ pub fn tx_env_to_fee(tx_env: &TxEnv) -> Fee { Fee { // Currently zkSync doesn't allow gas limits larger than u32. gas_limit: U256::min(tx_env.gas_limit.into(), U256::from(2147483640)), - // Block base fee on L2 is 0.25 GWei - make sure that the max_fee_per_gas is set to higher value. + // Block base fee on L2 is 0.25 GWei - make sure that the max_fee_per_gas is set to higher + // value. max_fee_per_gas: U256::max(revm_u256_to_u256(tx_env.gas_price), U256::from(260_000_000)), max_priority_fee_per_gas: revm_u256_to_u256(tx_env.gas_priority_fee.unwrap_or_default()), gas_per_pubdata_limit: U256::from(800), @@ -119,10 +119,7 @@ pub fn tx_env_to_era_tx(tx_env: TxEnv, nonce: u64) -> L2Tx { ) } }; - l2tx.set_input( - tx_env.data.to_vec(), - H256(keccak256(tx_env.data.to_vec().as_slice())), - ); + l2tx.set_input(tx_env.data.to_vec(), H256(keccak256(tx_env.data.to_vec().as_slice()))); l2tx } @@ -136,14 +133,8 @@ where DB: Database + Send, ::Error: Debug, { - let (num, ts) = ( - env.block.number.to::(), - env.block.timestamp.to::(), - ); - let era_db = RevmDatabaseForEra { - db: Arc::new(Mutex::new(Box::new(db))), - current_block: num, - }; + let (num, ts) = (env.block.number.to::(), env.block.timestamp.to::()); + let era_db = RevmDatabaseForEra { db: Arc::new(Mutex::new(Box::new(db))), current_block: num }; let nonces = era_db.get_nonce_for_address(address_to_h160(env.tx.caller)); @@ -237,8 +228,8 @@ where } } multivm::interface::ExecutionResult::Halt { reason } => { - // Need to decide what to do in the case of a halt. This might depend on the reason for the halt. - // TODO: FIXME + // Need to decide what to do in the case of a halt. This might depend on the reason for + // the halt. TODO: FIXME tracing::error!("tx execution halted: {}", reason); revm::primitives::ExecutionResult::Halt { reason: match reason { @@ -253,14 +244,10 @@ where }; let account_to_keys: HashMap> = - modified_keys - .iter() - .fold(HashMap::new(), |mut acc, (storage_key, value)| { - acc.entry(*storage_key.address()) - .or_default() - .insert(*storage_key, *value); - acc - }); + modified_keys.iter().fold(HashMap::new(), |mut acc, (storage_key, value)| { + acc.entry(*storage_key.address()).or_default().insert(*storage_key, *value); + acc + }); // List of touched accounts let mut accounts_touched: HashSet = Default::default(); @@ -268,7 +255,8 @@ where for x in account_to_keys.keys() { accounts_touched.insert(*x); } - // Also insert 'fake' accounts for bytecodes (to make sure that factory bytecodes get persisted). + // Also insert 'fake' accounts for bytecodes (to make sure that factory bytecodes get + // persisted). for k in bytecodes.keys() { accounts_touched.insert(h256_to_h160(&u256_to_h256(*k))); } @@ -328,10 +316,7 @@ where }) .collect(); - Ok(ResultAndState { - result: execution_result, - state, - }) + Ok(ResultAndState { result: execution_result, state }) } fn decode_l2_tx_result(output: Vec) -> Vec { @@ -383,10 +368,7 @@ mod tests { run_era_transaction::<_, ResultAndState, _>(&mut env, &mut MockDatabase::default(), ()) .expect("failed executing"); - assert!( - !res.state.is_empty(), - "unexpected failure: no states were touched" - ); + assert!(!res.state.is_empty(), "unexpected failure: no states were touched"); for (address, account) in res.state { assert!( account.is_touched(),