diff --git a/cmd/ethrex/utils.rs b/cmd/ethrex/utils.rs index e4eecc0c502..50cbfaf35ac 100644 --- a/cmd/ethrex/utils.rs +++ b/cmd/ethrex/utils.rs @@ -7,7 +7,6 @@ use ethrex_p2p::{ sync::SyncMode, types::{Node, NodeRecord}, }; -use ethrex_rlp::decode::RLPDecode; use hex::FromHexError; use secp256k1::{PublicKey, SecretKey}; use serde::{Deserialize, Serialize}; @@ -65,13 +64,6 @@ pub fn read_chain_file(chain_rlp_path: &str) -> Vec { decode::chain_file(chain_file).expect("Failed to decode chain rlp file") } -pub fn read_block_file(block_file_path: &str) -> Block { - let encoded_block = std::fs::read(block_file_path) - .unwrap_or_else(|_| panic!("Failed to read block file with path {block_file_path}")); - Block::decode(&encoded_block) - .unwrap_or_else(|_| panic!("Failed to decode block file {block_file_path}")) -} - pub fn parse_sync_mode(s: &str) -> eyre::Result { match s { "full" => Ok(SyncMode::Full), diff --git a/crates/common/serde_utils.rs b/crates/common/serde_utils.rs index c7ff3dafaa9..3d21f05680e 100644 --- a/crates/common/serde_utils.rs +++ b/crates/common/serde_utils.rs @@ -5,7 +5,6 @@ use serde::{Deserialize, Deserializer, Serializer, de::Error, ser::SerializeSeq} pub mod u256 { use super::*; use ethereum_types::U256; - use serde_json::Number; pub mod dec_str { use super::*; @@ -25,32 +24,6 @@ pub mod u256 { } } - pub fn deser_number<'de, D>(d: D) -> Result - where - D: Deserializer<'de>, - { - let value = Number::deserialize(d)?.to_string(); - U256::from_dec_str(&value).map_err(|e| D::Error::custom(e.to_string())) - } - - pub fn deser_number_opt<'de, D>(d: D) -> Result, D::Error> - where - D: Deserializer<'de>, - { - // Handle the null case explicitly - let opt = Option::::deserialize(d)?; - match opt { - Some(number) => { - // Convert number to string and parse to U256 - let value = number.to_string(); - U256::from_dec_str(&value) - .map(Some) - .map_err(|e| D::Error::custom(e.to_string())) - } - None => Ok(None), - } - } - pub fn deser_hex_str<'de, D>(d: D) -> Result where D: Deserializer<'de>, diff --git a/crates/common/types/block_execution_witness.rs b/crates/common/types/block_execution_witness.rs index 724a2517624..a970d96238b 100644 --- a/crates/common/types/block_execution_witness.rs +++ b/crates/common/types/block_execution_witness.rs @@ -1,24 +1,18 @@ use std::collections::{BTreeMap, BTreeSet}; -use std::fmt; -use std::str::FromStr; use crate::rkyv_utils::H160Wrapper; use crate::types::{Block, Code}; use crate::{ constants::EMPTY_KECCACK_HASH, types::{AccountState, AccountUpdate, BlockHeader, ChainConfig}, - utils::decode_hex, }; -use bytes::Bytes; use ethereum_types::{Address, H256, U256}; use ethrex_crypto::keccak::keccak_hash; use ethrex_rlp::error::RLPDecodeError; use ethrex_rlp::{decode::RLPDecode, encode::RLPEncode}; use ethrex_trie::{EMPTY_TRIE_HASH, Node, Trie, TrieError}; use rkyv::with::{Identity, MapKV}; -use serde::de::{SeqAccess, Visitor}; -use serde::ser::SerializeSeq; -use serde::{Deserialize, Deserializer, Serialize, Serializer, de}; +use serde::{Deserialize, Serialize}; /// State produced by the guest program execution inside the zkVM. It is /// essentially built from the `ExecutionWitness`. @@ -460,69 +454,6 @@ impl GuestProgramState { } } -pub fn serialize_code(map: &BTreeMap, serializer: S) -> Result -where - S: Serializer, -{ - let mut seq_serializer = serializer.serialize_seq(Some(map.len()))?; - for (code_hash, code) in map { - let code_hash = format!("0x{}", hex::encode(code_hash)); - let code = format!("0x{}", hex::encode(code)); - - let mut obj = serde_json::Map::new(); - obj.insert(code_hash, serde_json::Value::String(code)); - - seq_serializer.serialize_element(&obj)?; - } - seq_serializer.end() -} - -pub fn deserialize_code<'de, D>(deserializer: D) -> Result, D::Error> -where - D: Deserializer<'de>, -{ - struct BytesVecVisitor; - - impl<'de> Visitor<'de> for BytesVecVisitor { - type Value = BTreeMap; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a list of hex-encoded strings") - } - - fn visit_seq(self, mut seq: A) -> Result - where - A: SeqAccess<'de>, - { - let mut map = BTreeMap::new(); - - #[derive(Deserialize)] - struct CodeEntry(BTreeMap); - - while let Some(CodeEntry(entry)) = seq.next_element::()? { - if entry.len() != 1 { - return Err(de::Error::custom( - "Each object must contain exactly one key", - )); - } - - for (k, v) in entry { - let code_hash = - H256::from_str(k.trim_start_matches("0x")).map_err(de::Error::custom)?; - - let bytecode = - decode_hex(v.trim_start_matches("0x")).map_err(de::Error::custom)?; - - map.insert(code_hash, Bytes::from(bytecode)); - } - } - Ok(map) - } - } - - deserializer.deserialize_seq(BytesVecVisitor) -} - fn hash_address(address: &Address) -> Vec { keccak_hash(address.to_fixed_bytes()).to_vec() } diff --git a/crates/common/types/l2/fee_config.rs b/crates/common/types/l2/fee_config.rs index db508f98476..046313bb6bb 100644 --- a/crates/common/types/l2/fee_config.rs +++ b/crates/common/types/l2/fee_config.rs @@ -1,5 +1,5 @@ use bytes::Bytes; -use ethereum_types::{Address, H256, U256}; +use ethereum_types::Address; use rkyv::{Archive, Deserialize as RDeserialize, Serialize as RSerialize}; use serde::{Deserialize, Serialize}; @@ -216,24 +216,6 @@ impl Decoder { Ok(res) } - pub fn get_u256(&mut self) -> Result { - let res = U256::from_big_endian(self.bytes.get(self.offset..self.offset + 32).ok_or( - DecoderError::FailedToDeserializeStateDiff("Not enough bytes".to_string()), - )?); - self.offset += 32; - - Ok(res) - } - - pub fn get_h256(&mut self) -> Result { - let res = H256::from_slice(self.bytes.get(self.offset..self.offset + 32).ok_or( - DecoderError::FailedToDeserializeStateDiff("Not enough bytes".to_string()), - )?); - self.offset += 32; - - Ok(res) - } - pub fn get_u8(&mut self) -> Result { let res = self .bytes @@ -246,23 +228,6 @@ impl Decoder { Ok(*res) } - pub fn get_u16(&mut self) -> Result { - let res = u16::from_be_bytes( - self.bytes - .get(self.offset..self.offset + 2) - .ok_or(DecoderError::FailedToDeserializeStateDiff( - "Not enough bytes".to_string(), - ))? - .try_into() - .map_err(|_| { - DecoderError::FailedToDeserializeStateDiff("Cannot parse u16".to_string()) - })?, - ); - self.offset += 2; - - Ok(res) - } - pub fn get_u64(&mut self) -> Result { let res = u64::from_be_bytes( self.bytes @@ -279,13 +244,4 @@ impl Decoder { Ok(res) } - - pub fn get_bytes(&mut self, size: usize) -> Result { - let res = self.bytes.get(self.offset..self.offset + size).ok_or( - DecoderError::FailedToDeserializeStateDiff("Not enough bytes".to_string()), - )?; - self.offset += size; - - Ok(Bytes::copy_from_slice(res)) - } } diff --git a/crates/common/types/transaction.rs b/crates/common/types/transaction.rs index cdc7a9a0a5c..391df3005dc 100644 --- a/crates/common/types/transaction.rs +++ b/crates/common/types/transaction.rs @@ -603,11 +603,6 @@ impl EIP4844Transaction { self.rlp_encode_as_pooled_tx(&mut buf, blobs_bundle); buf.len() } - pub fn rlp_encode_as_pooled_tx_to_vec(&self, blobs_bundle: &BlobsBundle) -> Vec { - let mut buf = Vec::new(); - self.rlp_encode_as_pooled_tx(&mut buf, blobs_bundle); - buf - } } impl RLPEncode for EIP7702Transaction { diff --git a/crates/l2/common/src/l1_messages.rs b/crates/l2/common/src/l1_messages.rs index 1724dab3267..df87b498572 100644 --- a/crates/l2/common/src/l1_messages.rs +++ b/crates/l2/common/src/l1_messages.rs @@ -44,13 +44,6 @@ pub fn get_l1_message_hash(msg: &L1Message) -> H256 { keccak(msg.encode()) } -pub fn get_block_l1_message_hashes(receipts: &[Receipt]) -> Vec { - get_block_l1_messages(receipts) - .iter() - .map(get_l1_message_hash) - .collect() -} - pub fn get_block_l1_messages(receipts: &[Receipt]) -> Vec { static L1MESSAGE_EVENT_SELECTOR: LazyLock = LazyLock::new(|| keccak("L1Message(address,bytes32,uint256)".as_bytes())); diff --git a/crates/networking/p2p/peer_handler.rs b/crates/networking/p2p/peer_handler.rs index d41281dda62..905dcc3bc8a 100644 --- a/crates/networking/p2p/peer_handler.rs +++ b/crates/networking/p2p/peer_handler.rs @@ -5,12 +5,9 @@ use crate::{ rlpx::{ connection::server::PeerConnection, error::PeerConnectionError, - eth::{ - blocks::{ - BLOCK_HEADER_LIMIT, BlockBodies, BlockHeaders, GetBlockBodies, GetBlockHeaders, - HashOrNumber, - }, - receipts::GetReceipts, + eth::blocks::{ + BLOCK_HEADER_LIMIT, BlockBodies, BlockHeaders, GetBlockBodies, GetBlockHeaders, + HashOrNumber, }, message::Message as RLPxMessage, p2p::{Capability, SUPPORTED_ETH_CAPABILITIES}, @@ -29,7 +26,7 @@ use crate::{ use bytes::Bytes; use ethrex_common::{ BigEndianHash, H256, U256, - types::{AccountState, BlockBody, BlockHeader, Receipt, validate_block_body}, + types::{AccountState, BlockBody, BlockHeader, validate_block_body}, }; use ethrex_rlp::{decode::RLPDecode, encode::RLPEncode}; use ethrex_storage::Store; @@ -596,46 +593,6 @@ impl PeerHandler { Ok(None) } - /// Requests all receipts in a set of blocks from any suitable peer given their block hashes - /// Returns the lists of receipts or None if: - /// - There are no available peers (the node just started up or was rejected by all other nodes) - /// - No peer returned a valid response in the given time and retry limits - pub async fn request_receipts( - &mut self, - block_hashes: Vec, - ) -> Result>>, PeerHandlerError> { - let block_hashes_len = block_hashes.len(); - for _ in 0..REQUEST_RETRY_ATTEMPTS { - let request_id = rand::random(); - let request = RLPxMessage::GetReceipts(GetReceipts { - id: request_id, - block_hashes: block_hashes.clone(), - }); - match self.get_random_peer(&SUPPORTED_ETH_CAPABILITIES).await? { - None => return Ok(None), - Some((peer_id, mut connection)) => { - if let Some(receipts) = - match PeerHandler::make_request(&mut self.peer_table, peer_id, &mut connection, request, PEER_REPLY_TIMEOUT).await { - Ok(RLPxMessage::Receipts68(res)) => { - Some(res.get_receipts()) - } - Ok(RLPxMessage::Receipts69(res)) => { - Some(res.receipts.clone()) - } - _ => None - } - .and_then(|receipts| - // Check that the response is not empty and does not contain more bodies than the ones requested - (!receipts.is_empty() && receipts.len() <= block_hashes_len).then_some(receipts)) - { - return Ok(Some(receipts)); - } - } - } - } - Ok(None) - } - /// Requests an account range from any suitable peer given the state trie's root and the starting hash and the limit hash. /// Will also return a boolean indicating if there is more state to be fetched towards the right of the trie /// (Note that the boolean will be true even if the remaining state is ouside the boundary set by the limit hash) diff --git a/crates/networking/p2p/rlpx/connection/codec.rs b/crates/networking/p2p/rlpx/connection/codec.rs index c3315801e51..ffdc6dd3c28 100644 --- a/crates/networking/p2p/rlpx/connection/codec.rs +++ b/crates/networking/p2p/rlpx/connection/codec.rs @@ -239,19 +239,6 @@ impl Decoder for RLPxCodec { )?)) } - fn decode_eof(&mut self, buf: &mut BytesMut) -> Result, Self::Error> { - match self.decode(buf)? { - Some(frame) => Ok(Some(frame)), - None => { - if buf.is_empty() { - Ok(None) - } else { - Err(std::io::Error::other("bytes remaining on stream").into()) - } - } - } - } - fn framed(self, io: S) -> Framed where Self: Sized, diff --git a/crates/networking/p2p/sync.rs b/crates/networking/p2p/sync.rs index ecea0123230..3d3f24bca6c 100644 --- a/crates/networking/p2p/sync.rs +++ b/crates/networking/p2p/sync.rs @@ -23,7 +23,7 @@ use ethrex_common::types::Code; use ethrex_common::{ H256, constants::{EMPTY_KECCACK_HASH, EMPTY_TRIE_HASH}, - types::{AccountState, Block, BlockHash, BlockHeader}, + types::{AccountState, Block, BlockHeader}, }; use ethrex_rlp::{decode::RLPDecode, encode::RLPEncode, error::RLPDecodeError}; use ethrex_storage::{Store, error::StoreError}; @@ -585,31 +585,6 @@ async fn store_block_bodies( Ok(()) } -/// Fetches all receipts for the given block hashes via p2p and stores them -// TODO: remove allow when used again -#[allow(unused)] -async fn store_receipts( - mut block_hashes: Vec, - mut peers: PeerHandler, - store: Store, -) -> Result<(), SyncError> { - loop { - debug!("Requesting Receipts "); - if let Some(receipts) = peers.request_receipts(block_hashes.clone()).await? { - debug!(" Received {} Receipts", receipts.len()); - // Track which blocks we have already fetched receipts for - for (block_hash, receipts) in block_hashes.drain(0..receipts.len()).zip(receipts) { - store.add_receipts(block_hash, receipts).await?; - } - // Check if we need to ask for another batch - if block_hashes.is_empty() { - break; - } - } - } - Ok(()) -} - /// Persisted State during the Block Sync phase for SnapSync #[derive(Clone)] pub struct SnapBlockSyncState { diff --git a/crates/networking/p2p/types.rs b/crates/networking/p2p/types.rs index 0196e8834c0..442117d901e 100644 --- a/crates/networking/p2p/types.rs +++ b/crates/networking/p2p/types.rs @@ -44,12 +44,6 @@ pub struct Endpoint { pub tcp_port: u16, } -impl Endpoint { - pub fn tcp_address(&self) -> Option { - (self.tcp_port != 0).then_some(SocketAddr::new(self.ip, self.tcp_port)) - } -} - impl RLPEncode for Endpoint { fn encode(&self, buf: &mut dyn BufMut) { Encoder::new(buf) diff --git a/crates/networking/rpc/debug/execution_witness.rs b/crates/networking/rpc/debug/execution_witness.rs index c8677a48564..d936df7db49 100644 --- a/crates/networking/rpc/debug/execution_witness.rs +++ b/crates/networking/rpc/debug/execution_witness.rs @@ -66,6 +66,7 @@ impl TryFrom for RpcExecutionWitness { } // TODO: Ideally this would be a try_from but crate dependencies complicate this matter +// This function is used by ethrex-replay pub fn execution_witness_from_rpc_chain_config( rpc_witness: RpcExecutionWitness, chain_config: ChainConfig, diff --git a/crates/vm/levm/src/gas_cost.rs b/crates/vm/levm/src/gas_cost.rs index 9e745b27b37..aced5a035d1 100644 --- a/crates/vm/levm/src/gas_cost.rs +++ b/crates/vm/levm/src/gas_cost.rs @@ -574,17 +574,6 @@ pub fn tx_calldata(calldata: &Bytes) -> Result { Ok(calldata_cost) } -pub fn tx_creation(code_length: u64, number_of_words: u64) -> Result { - let mut creation_cost = code_length.checked_mul(CODE_DEPOSIT_COST).ok_or(OutOfGas)?; - creation_cost = creation_cost - .checked_add(CREATE_BASE_COST) - .ok_or(OutOfGas)?; - - // GInitCodeword * number_of_words rounded up. GinitCodeWord = 2 - let words_cost = number_of_words.checked_mul(2).ok_or(OutOfGas)?; - creation_cost.checked_add(words_cost).ok_or(OutOfGas.into()) -} - fn address_access_cost( address_was_cold: bool, static_cost: u64, diff --git a/crates/vm/levm/src/memory.rs b/crates/vm/levm/src/memory.rs index 4de205a8dbf..3c502527c9c 100644 --- a/crates/vm/levm/src/memory.rs +++ b/crates/vm/levm/src/memory.rs @@ -191,20 +191,6 @@ impl Memory { self.store(data, offset, data.len()) } - /// Stores the given data and data size at the given offset. - /// - /// Resizes memory to fit the given data. - #[inline(always)] - pub fn store_range(&mut self, offset: usize, size: usize, data: &[u8]) -> Result<(), VMError> { - if size == 0 { - return Ok(()); - } - - let new_size = offset.checked_add(size).ok_or(OutOfBounds)?; - self.resize(new_size)?; - self.store(data, offset, size) - } - /// Stores a word at the given offset, resizing memory if needed. #[inline(always)] pub fn store_word(&mut self, offset: usize, word: U256) -> Result<(), VMError> { diff --git a/crates/vm/levm/src/utils.rs b/crates/vm/levm/src/utils.rs index 68679fd901f..a4fc4914bbc 100644 --- a/crates/vm/levm/src/utils.rs +++ b/crates/vm/levm/src/utils.rs @@ -10,11 +10,9 @@ use crate::{ COLD_ADDRESS_ACCESS_COST, CREATE_BASE_COST, STANDARD_TOKEN_COST, TOTAL_COST_FLOOR_PER_TOKEN, WARM_ADDRESS_ACCESS_COST, }, - opcodes::Opcode, vm::{Substate, VM}, }; use ExceptionalHalt::OutOfGas; -use bitvec::{bitvec, order::Msb0, vec::BitVec}; use bytes::Bytes; use ethrex_common::{ Address, H256, U256, @@ -68,66 +66,6 @@ pub fn calculate_create2_address( Ok(generated_address) } -/// # Filter for jump target offsets. -/// -/// Used to filter which program offsets are not valid jump targets. Implemented as a sorted list of -/// offsets of bytes `0x5B` (`JUMPDEST`) within push constants. -#[derive(Debug)] -pub struct JumpTargetFilter { - bytecode: Bytes, - jumpdests: Option>, -} - -impl JumpTargetFilter { - /// Create an empty `JumpTargetFilter`. - pub fn new(bytecode: Bytes) -> Self { - Self { - bytecode, - jumpdests: None, - } - } - - /// Check whether a target jump address is blacklisted or not. - /// - /// Builds the jumpdest table on the first call, and caches it for future calls. - #[expect( - clippy::as_conversions, - clippy::arithmetic_side_effects, - clippy::indexing_slicing - )] - pub fn is_blacklisted(&mut self, address: usize) -> bool { - match self.jumpdests { - // Already built the jumpdest table, just check it - Some(ref jumpdests) => address >= jumpdests.len() || !jumpdests[address], - // First time we are called, need to build the jumpdest table - None => { - let code = &self.bytecode; - let len = code.len(); - let mut jumpdests = bitvec![u8, Msb0; 0; len]; // All false, size = len - - let mut i = 0; - while i < len { - let opcode = Opcode::from(code[i]); - if opcode == Opcode::JUMPDEST { - jumpdests.set(i, true); - } else if (Opcode::PUSH1..=Opcode::PUSH32).contains(&opcode) { - // PUSH1 (0x60) to PUSH32 (0x7f): skip 1 to 32 bytes - let skip = opcode as usize - Opcode::PUSH0 as usize; - i += skip; // Advance past data bytes - } - i += 1; - } - - let is_blacklisted = address >= jumpdests.len() || !jumpdests[address]; - - self.jumpdests = Some(jumpdests); - - is_blacklisted - } - } - } -} - // ================== Backup related functions ======================= /// Restore the state of the cache to the state it in the callframe backup.