diff --git a/Cargo.lock b/Cargo.lock index 0e7394dd37..eacb0fdd1e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -99,11 +99,142 @@ version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f" +[[package]] +name = "alloy" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45855eb65e9cc70294ebea1279f6d8ee0636bf2ed3897683ebbae2739975ae8c" +dependencies = [ + "alloy-consensus", + "alloy-core", + "alloy-eips", + "alloy-genesis", + "alloy-rpc-types", + "alloy-serde", + "alloy-signer", + "alloy-signer-local", +] + +[[package]] +name = "alloy-consensus" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58047cc851e58c26224521d1ecda466e3d746ebca0274cd5427aa660a88c353" +dependencies = [ + "alloy-eips", + "alloy-primitives", + "alloy-rlp", + "alloy-serde", + "c-kzg", + "serde", +] + +[[package]] +name = "alloy-core" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "529fc6310dc1126c8de51c376cbc59c79c7f662bd742be7dc67055d5421a81b4" +dependencies = [ + "alloy-dyn-abi", + "alloy-json-abi", + "alloy-primitives", + "alloy-rlp", + "alloy-sol-types", +] + +[[package]] +name = "alloy-dyn-abi" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413902aa18a97569e60f679c23f46a18db1656d87ab4d4e49d0e1e52042f66df" +dependencies = [ + "alloy-json-abi", + "alloy-primitives", + "alloy-sol-type-parser", + "alloy-sol-types", + "const-hex", + "itoa", + "serde", + "serde_json", + "winnow 0.6.13", +] + +[[package]] +name = "alloy-eips" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d32a3e14fa0d152d00bd8daf605eb74ad397efb0f54bd7155585823dddb4401e" +dependencies = [ + "alloy-primitives", + "alloy-rlp", + "alloy-serde", + "c-kzg", + "once_cell", + "serde", + "sha2", +] + +[[package]] +name = "alloy-genesis" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20cb76c8a3913f2466c5488f3a915e3a15d15596bdc935558c1a9be75e9ec508" +dependencies = [ + "alloy-primitives", + "alloy-serde", + "serde", +] + +[[package]] +name = "alloy-json-abi" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc05b04ac331a9f07e3a4036ef7926e49a8bf84a99a1ccfc7e2ab55a5fcbb372" +dependencies = [ + "alloy-primitives", + "alloy-sol-type-parser", + "serde", + "serde_json", +] + +[[package]] +name = "alloy-json-rpc" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e76a9feec2352c78545d1a37415699817bae8dc41654bd1bfe57d6cdd5433bd" +dependencies = [ + "alloy-primitives", + "serde", + "serde_json", + "thiserror", + "tracing", +] + +[[package]] +name = "alloy-network" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3223d71dc78f464b2743418d0be8b5c894313e272105a6206ad5e867d67b3ce2" +dependencies = [ + "alloy-consensus", + "alloy-eips", + "alloy-json-rpc", + "alloy-primitives", + "alloy-rpc-types-eth", + "alloy-serde", + "alloy-signer", + "alloy-sol-types", + "async-trait", + "auto_impl", + "futures-utils-wasm", + "thiserror", +] + [[package]] name = "alloy-primitives" -version = "0.7.4" +version = "0.7.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db8aa973e647ec336810a9356af8aea787249c9d00b1525359f3db29a68d231b" +checksum = "ccb3ead547f4532bc8af961649942f0b9c16ee9226e26caa3f38420651cc0bf4" dependencies = [ "alloy-rlp", "bytes", @@ -127,10 +258,161 @@ version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8d58d9f5da7b40e9bfff0b7e7816700be4019db97d4b6359fe7f94a9e22e42ac" dependencies = [ + "alloy-rlp-derive", "arrayvec", "bytes", ] +[[package]] +name = "alloy-rlp-derive" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83524c1f6162fcb5b0decf775498a125066c86dda6066ed609531b0e912f85a" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.60", +] + +[[package]] +name = "alloy-rpc-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e5d76f1e8b22f48b7b8f985782b68e7eb3938780e50e8b646a53e41a598cdf5" +dependencies = [ + "alloy-rpc-types-eth", + "alloy-serde", + "serde", +] + +[[package]] +name = "alloy-rpc-types-eth" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "605fa8462732bb8fd0645a9941e12961e079d45ae6a44634c826f8229c187bdf" +dependencies = [ + "alloy-consensus", + "alloy-eips", + "alloy-primitives", + "alloy-rlp", + "alloy-serde", + "alloy-sol-types", + "itertools 0.13.0", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "alloy-serde" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15c5b9057acc02aee1b8aac2b5a0729cb0f73d080082c111313e5d1f92a96630" +dependencies = [ + "alloy-primitives", + "serde", + "serde_json", +] + +[[package]] +name = "alloy-signer" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37f10592696f4ab8b687d5a8ab55e998a14ea0ca5f8eb20ad74a96ad671bb54a" +dependencies = [ + "alloy-primitives", + "async-trait", + "auto_impl", + "elliptic-curve", + "k256", + "thiserror", +] + +[[package]] +name = "alloy-signer-local" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b537f3e55f30753578f4623d5f66ddad8fa582af3fa6b15bad23dd1b9775228" +dependencies = [ + "alloy-consensus", + "alloy-network", + "alloy-primitives", + "alloy-signer", + "async-trait", + "k256", + "rand", + "thiserror", +] + +[[package]] +name = "alloy-sol-macro" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b40397ddcdcc266f59f959770f601ce1280e699a91fc1862f29cef91707cd09" +dependencies = [ + "alloy-sol-macro-expander", + "alloy-sol-macro-input", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.60", +] + +[[package]] +name = "alloy-sol-macro-expander" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "867a5469d61480fea08c7333ffeca52d5b621f5ca2e44f271b117ec1fc9a0525" +dependencies = [ + "alloy-sol-macro-input", + "const-hex", + "heck 0.5.0", + "indexmap", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.60", + "syn-solidity", + "tiny-keccak", +] + +[[package]] +name = "alloy-sol-macro-input" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e482dc33a32b6fadbc0f599adea520bd3aaa585c141a80b404d0a3e3fa72528" +dependencies = [ + "const-hex", + "dunce", + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.60", + "syn-solidity", +] + +[[package]] +name = "alloy-sol-type-parser" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbcba3ca07cf7975f15d871b721fb18031eec8bce51103907f6dcce00b255d98" +dependencies = [ + "serde", + "winnow 0.6.13", +] + +[[package]] +name = "alloy-sol-types" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a91ca40fa20793ae9c3841b83e74569d1cc9af29a2f5237314fd3452d51e38c7" +dependencies = [ + "alloy-primitives", + "alloy-sol-macro", + "const-hex", + "serde", +] + [[package]] name = "android-tzdata" version = "0.1.1" @@ -1411,6 +1693,7 @@ dependencies = [ name = "eth-types" version = "0.11.0" dependencies = [ + "alloy", "base64 0.13.1", "ethers-core", "ethers-signers", @@ -1936,6 +2219,12 @@ dependencies = [ "slab", ] +[[package]] +name = "futures-utils-wasm" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42012b0f064e01aa58b545fe3727f90f7dd4020f4a3ea735b50344965f5a57e9" + [[package]] name = "fxhash" version = "0.2.1" @@ -2274,6 +2563,9 @@ name = "hex" version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +dependencies = [ + "serde", +] [[package]] name = "hex-literal" @@ -2557,6 +2849,15 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.11" @@ -3430,6 +3731,30 @@ dependencies = [ "toml_edit 0.20.7", ] +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + [[package]] name = "proc-macro2" version = "1.0.81" @@ -3823,9 +4148,9 @@ dependencies = [ [[package]] name = "ruint" -version = "1.12.1" +version = "1.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f308135fef9fc398342da5472ce7c484529df23743fb7c734e0f3d472971e62" +checksum = "2c3cc4c2511671f327125da14133d0c5c5d137f006a1017a16f557bc85b16286" dependencies = [ "alloy-rlp", "ark-ff 0.3.0", @@ -3847,9 +4172,9 @@ dependencies = [ [[package]] name = "ruint-macro" -version = "1.2.0" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f86854cf50259291520509879a5c294c3c9a4c334e9ff65071c51e42ef1e2343" +checksum = "48fd7bd8a6377e15ad9d42a8ec25371b94ddc67abe7c8b9127bec79bebaaae18" [[package]] name = "rustc-demangle" @@ -4540,6 +4865,18 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn-solidity" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c837dc8852cb7074e46b444afb81783140dab12c58867b49fb3898fbafedf7ea" +dependencies = [ + "paste", + "proc-macro2", + "quote", + "syn 2.0.60", +] + [[package]] name = "sync_wrapper" version = "0.1.2" @@ -4832,7 +5169,7 @@ dependencies = [ "serde", "serde_spanned", "toml_datetime", - "winnow", + "winnow 0.5.40", ] [[package]] @@ -4843,7 +5180,7 @@ checksum = "70f427fce4d84c72b5b732388bf4a9f4531b53f74e2887e3ecb2481f68f66d81" dependencies = [ "indexmap", "toml_datetime", - "winnow", + "winnow 0.5.40", ] [[package]] @@ -5369,6 +5706,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "winnow" +version = "0.6.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59b5e5f6c299a3c7890b876a2a587f3115162487e704907d9b6cd29473052ba1" +dependencies = [ + "memchr", +] + [[package]] name = "winreg" version = "0.50.0" diff --git a/Cargo.toml b/Cargo.toml index 76e6357800..034f41d84c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,6 +22,7 @@ edition = "2021" license = "MIT OR Apache-2.0" [workspace.dependencies] +alloy = { version = "0.2", default-features = false } anyhow = "1.0" ark-std = "0.3" base64 = "0.13.0" diff --git a/aggregator/src/chunk.rs b/aggregator/src/chunk.rs index 697d35237c..3e7940971b 100644 --- a/aggregator/src/chunk.rs +++ b/aggregator/src/chunk.rs @@ -72,7 +72,7 @@ impl ChunkInfo { let post_state_root = traces .last() .expect("at least 1 block needed") - .header + .eth_block .state_root; let withdraw_root = traces.last().unwrap().withdraw_trie_root; let chain_id = traces.first().unwrap().chain_id; diff --git a/bus-mapping/src/circuit_input_builder/l2.rs b/bus-mapping/src/circuit_input_builder/l2.rs index 97a0ac805f..d8c8c23494 100644 --- a/bus-mapping/src/circuit_input_builder/l2.rs +++ b/bus-mapping/src/circuit_input_builder/l2.rs @@ -24,7 +24,7 @@ impl CircuitInputBuilder { fn apply_l2_trace(&mut self, block_trace: BlockTrace) -> Result<(), Error> { log::trace!( "apply_l2_trace start, block num {:?}", - block_trace.header.number + block_trace.eth_block.number ); //self.sdb.list_accounts(); //dump_code_db(&self.code_db); @@ -120,7 +120,7 @@ impl CircuitInputBuilder { let old_root = l2_trace.storage_trace.root_before; log::debug!( "building zktrie state for block {:?}, old root {}", - l2_trace.header.number, + l2_trace.eth_block.number, hex::encode(old_root), ); diff --git a/eth-types/Cargo.toml b/eth-types/Cargo.toml index 82904ec0b0..fc3d9a7d80 100644 --- a/eth-types/Cargo.toml +++ b/eth-types/Cargo.toml @@ -5,6 +5,14 @@ edition.workspace = true license.workspace = true [dependencies] +alloy = { workspace = true, features = [ + "consensus", + "eips", + "rlp", + "rpc-types-eth", + "signer-local", + "std" +] } ethers-core.workspace = true ethers-signers.workspace = true hex.workspace = true @@ -27,6 +35,10 @@ base64.workspace = true revm-precompile.workspace = true revm-primitives.workspace = true +[dev-dependencies] +ethers-core.workspace = true +ethers-signers.workspace = true + [features] default = ["warn-unimplemented"] warn-unimplemented = [] diff --git a/eth-types/src/bytecode.rs b/eth-types/src/bytecode.rs index eed188ccfb..761ed68e48 100644 --- a/eth-types/src/bytecode.rs +++ b/eth-types/src/bytecode.rs @@ -108,8 +108,7 @@ impl Bytecode { // Write the op code self.write_op((OpcodeId::push_n(n)).expect("valid push size")); - let mut bytes = [0u8; 32]; - value.to_little_endian(&mut bytes); + let mut bytes = value.to_le_bytes(); // Write the bytes MSB to LSB for i in 0..n { self.write(bytes[(n - 1 - i) as usize], false); @@ -275,7 +274,8 @@ impl<'a> Iterator for BytecodeIterator<'a> { *value_byte = self.0.next().unwrap().value; } - OpcodeWithData::PushWithData(n as u8, Word::from(value.as_slice())) + OpcodeWithData::PushWithData(n as u8, Word::from_le_slice(value.as_slice())) + // FIXME: le or be? } else { OpcodeWithData::Opcode(op) } @@ -355,7 +355,7 @@ macro_rules! bytecode_internal { impl Bytecode { /// Helper function for `PUSH0` pub fn op_push0(&mut self) -> &mut Self { - self.push(0, Word::zero()) + self.push(0, Word::ZERO) } } diff --git a/eth-types/src/constants.rs b/eth-types/src/constants.rs index 82f49f7a9d..1cae74edc2 100644 --- a/eth-types/src/constants.rs +++ b/eth-types/src/constants.rs @@ -2,9 +2,7 @@ use std::str::FromStr; -use ethers_core::types::{Address, U256}; - -use crate::l2_types::BlockTrace; +use crate::{address, l2_types::BlockTrace, Address, U256}; /// Read env var with default value pub fn read_env_var(var_name: &'static str, default: T) -> T { @@ -14,14 +12,14 @@ pub fn read_env_var(var_name: &'static str, default: T) -> T } /// Scroll coinbase -pub const SCROLL_COINBASE: &str = "0x5300000000000000000000000000000000000005"; +pub const SCROLL_COINBASE: Address = address!("5300000000000000000000000000000000000005"); /// Get COINBASE constant used for circuit pub fn get_coinbase_constant() -> Address { let default_coinbase = if cfg!(feature = "scroll") { - Address::from_str(SCROLL_COINBASE).unwrap() + SCROLL_COINBASE } else { - Address::zero() + Address::ZERO }; read_env_var("COINBASE", default_coinbase) } @@ -35,12 +33,12 @@ pub fn set_env_coinbase(coinbase: &Address) -> String { /// Get DIFFICULTY constant used for circuit pub fn get_difficulty_constant() -> U256 { - read_env_var("DIFFICULTY", U256::zero()) + read_env_var("DIFFICULTY", U256::ZERO) } /// Set scroll block constants using trace pub fn set_scroll_block_constants_with_trace(trace: &BlockTrace) { - set_scroll_block_constants(&trace.coinbase.address, trace.chain_id, U256::zero()) + set_scroll_block_constants(&trace.coinbase.address, trace.chain_id, U256::ZERO) } /// Set scroll block constants diff --git a/eth-types/src/evm_types/block_utils.rs b/eth-types/src/evm_types/block_utils.rs index 4c450e88a1..2f98935aa8 100644 --- a/eth-types/src/evm_types/block_utils.rs +++ b/eth-types/src/evm_types/block_utils.rs @@ -1,7 +1,6 @@ //! Helper constants and utility functions for block -use crate::{U256, U64}; -use ethers_core::utils::keccak256; +use crate::{keccak256, U256}; /// Maximum range of previous blocks allowed inside BLOCKHASH opcode pub const NUM_PREV_BLOCK_ALLOWED: u64 = 256; @@ -11,10 +10,12 @@ pub const NUM_PREV_BLOCK_ALLOWED: u64 = 256; pub fn calculate_block_hash(chain_id: u64, block_number: U256) -> (Vec, U256) { let mut input = vec![0; 16]; - U64([chain_id]).to_big_endian(&mut input[..8]); - U64([block_number.low_u64()]).to_big_endian(&mut input[8..]); + let chain_id = chain_id.to_be_bytes(); + let block_number = block_number.to::().to_be_bytes(); + input[..8].copy_from_slice(&chain_id); + input[8..].copy_from_slice(&block_number); - let output = U256::from_big_endian(&keccak256(&input)); + let output = U256::from_be_slice(keccak256(&input).as_slice()); (input, output) } @@ -24,6 +25,6 @@ pub fn is_valid_block_number(block_number: U256, current_block_number: U256) -> block_number < current_block_number && block_number >= current_block_number - .checked_sub(NUM_PREV_BLOCK_ALLOWED.into()) + .checked_sub(U256::from_limbs([NUM_PREV_BLOCK_ALLOWED, 0, 0, 0])) .unwrap_or_default() } diff --git a/eth-types/src/evm_types/gas_utils.rs b/eth-types/src/evm_types/gas_utils.rs index a754b1658e..bc1efd8a6a 100644 --- a/eth-types/src/evm_types/gas_utils.rs +++ b/eth-types/src/evm_types/gas_utils.rs @@ -39,8 +39,7 @@ pub fn memory_copier_gas_cost( pub fn eip150_gas(gas_left: u64, gas_specified: Word) -> u64 { let capped_gas = gas_left - gas_left / 64; - if gas_specified.bits() <= 64 { - let gas_specified = gas_specified.low_u64(); + if let Ok(gas_specified) = u64::try_from(gas_specified) { if gas_specified < capped_gas { return gas_specified; } diff --git a/eth-types/src/evm_types/memory.rs b/eth-types/src/evm_types/memory.rs index e437df9f47..a2b273fc9c 100644 --- a/eth-types/src/evm_types/memory.rs +++ b/eth-types/src/evm_types/memory.rs @@ -1,5 +1,5 @@ //! Doc this -use crate::{DebugByte, Error, ToBigEndian, Word}; +use crate::{DebugByte, Error, Word}; use core::{ ops::{Add, AddAssign, Index, IndexMut, Mul, MulAssign, Range, Sub, SubAssign}, str::FromStr, @@ -74,10 +74,9 @@ impl TryFrom for MemoryAddress { type Error = Error; fn try_from(word: Word) -> Result { - if word.bits() > core::mem::size_of::() * 8 { - return Err(Error::WordToMemAddr); - } - Ok(MemoryAddress(word.as_usize())) + usize::try_from(word) + .map(MemoryAddress) + .map_err(|_| Error::WordToMemAddr) } } @@ -297,7 +296,7 @@ impl Memory { /// Reads an entire [`Word`] which starts at the provided [`MemoryAddress`] /// `addr` and finnishes at `addr + 32`. pub fn read_word(&self, addr: MemoryAddress) -> Word { - Word::from_big_endian(&self.read_chunk(MemoryRange::new_with_length(addr, 32))) + Word::from_be_slice(&self.read_chunk(MemoryRange::new_with_length(addr, 32))) } /// Reads an chunk of memory[offset..offset+length]. Zeros will be padded if @@ -341,10 +340,10 @@ impl Memory { /// then do nothing. pub fn extend_for_range(&mut self, offset: Word, length: Word) { // `length` should be checked for overflow during gas cost calculation. - let length = length.as_usize(); + let length: usize = length.to(); if length != 0 { // `dst_offset` should be within range if length is non-zero. - let offset = offset.as_usize(); + let offset: usize = offset.to(); self.extend_at_least(offset + length); } } @@ -356,11 +355,11 @@ impl Memory { // `length` should be checked for overflow during gas cost calculation. // Otherwise should return an out of gas error previously. - let length = length.as_usize(); + let length: usize = length.to(); if length != 0 { // `dst_offset` should be within range if length is non-zero. // https://github.com/ethereum/go-ethereum/blob/bb4ac2d396de254898a5f44b1ea2086bfe5bd193/core/vm/common.go#L37 - let dst_offset = dst_offset.as_u64(); + let dst_offset: u64 = dst_offset.to(); // Reset data offset to the maximum value of Uint64 if overflow. let src_offset = u64::try_from(src_offset).unwrap_or(u64::MAX); diff --git a/eth-types/src/evm_types/stack.rs b/eth-types/src/evm_types/stack.rs index 2b7d77df49..16c40f9c77 100644 --- a/eth-types/src/evm_types/stack.rs +++ b/eth-types/src/evm_types/stack.rs @@ -1,5 +1,5 @@ //! Doc this -use crate::{DebugWord, Error, ToBigEndian, Word}; +use crate::{DebugWord, Error, Word}; use core::str::FromStr; use serde::{ser::SerializeSeq, Deserialize, Serialize, Serializer}; use std::fmt; diff --git a/eth-types/src/evm_types/storage.rs b/eth-types/src/evm_types/storage.rs index 86a1f63455..6832ec241f 100644 --- a/eth-types/src/evm_types/storage.rs +++ b/eth-types/src/evm_types/storage.rs @@ -1,5 +1,5 @@ //! Doc this -use crate::{DebugWord, Error, ToBigEndian, Word}; +use crate::{DebugWord, Error, Word}; use serde::{ser::SerializeMap, Serialize, Serializer}; use std::{collections::HashMap, fmt}; diff --git a/eth-types/src/evm_types/transient_storage.rs b/eth-types/src/evm_types/transient_storage.rs index 9b5063a22c..e50c064337 100644 --- a/eth-types/src/evm_types/transient_storage.rs +++ b/eth-types/src/evm_types/transient_storage.rs @@ -1,5 +1,5 @@ //! Doc this -use crate::{DebugWord, Error, ToBigEndian, Word}; +use crate::{DebugWord, Error, Word}; use serde::{ser::SerializeMap, Serialize, Serializer}; use std::{collections::HashMap, fmt}; diff --git a/eth-types/src/geth_types.rs b/eth-types/src/geth_types.rs index 9c534e8589..f833a1732d 100644 --- a/eth-types/src/geth_types.rs +++ b/eth-types/src/geth_types.rs @@ -4,12 +4,8 @@ use crate::l2_types::BlockTrace; use crate::{ sign_types::{biguint_to_32bytes_le, ct_option_ok_or, recover_pk2, SignData, SECP256K1_Q}, - AccessList, Address, Block, Bytes, Error, GethExecTrace, Hash, ToBigEndian, ToLittleEndian, - Word, U64, -}; -use ethers_core::types::{ - transaction::eip2718::TypedTransaction, Eip1559TransactionRequest, Eip2930TransactionRequest, - NameOrAddress, TransactionRequest, H256, + AccessList, Address, Block, Bytes, Error, GethExecTrace, Hash, SignableTransaction, + TransactionRequest, TxKind, TxSignature, TypedTransaction, Word, H256, }; use halo2curves::{group::ff::PrimeField, secp256k1::Fq}; use num::Integer; @@ -76,27 +72,35 @@ impl TxType { /// Get the type of transaction pub fn get_tx_type(tx: &crate::Transaction) -> Self { + // Transaction type: + // - Some(3) for EIP-4844 transaction + // - Some(2) for EIP-1559 transaction + // - Some(1) for AccessList transaction + // - None or Some(0) for Legacy match tx.transaction_type { - Some(x) if x == U64::from(1) => Self::Eip2930, - Some(x) if x == U64::from(2) => Self::Eip1559, - Some(x) if x == U64::from(0x7e) => Self::L1Msg, - _ => { + Some(1) => Self::Eip2930, + Some(2) => Self::Eip1559, + Some(0x7e) => Self::L1Msg, + None | Some(0) => { + let sig = tx.signature.unwrap_or_default(); + let v = sig.v.to::(); if cfg!(feature = "scroll") { - if tx.v.is_zero() && tx.r.is_zero() && tx.s.is_zero() { + if v == 0 && sig.r.is_zero() && sig.s.is_zero() { Self::L1Msg } else { - match tx.v.as_u64() { + match v { 0 | 1 | 27 | 28 => Self::PreEip155, _ => Self::Eip155, } } } else { - match tx.v.as_u64() { + match v { 0 | 1 | 27 | 28 => Self::PreEip155, _ => Self::Eip155, } } } + Some(x) => panic!("Unknown transaction type: {}", x), // panics on 4844 } } @@ -125,39 +129,6 @@ impl TxType { } } -/// Get the RLP bytes for signing -pub fn get_rlp_unsigned(tx: &crate::Transaction) -> Vec { - let sig_v = tx.v; - match TxType::get_tx_type(tx) { - TxType::Eip155 => { - let mut tx: TransactionRequest = tx.into(); - tx.chain_id = Some(tx.chain_id.unwrap_or_else(|| { - let recv_v = TxType::Eip155.get_recovery_id(sig_v.as_u64()) as u64; - (sig_v - recv_v - 35) / 2 - })); - tx.rlp().to_vec() - } - TxType::PreEip155 => { - let tx: TransactionRequest = tx.into(); - tx.rlp_unsigned().to_vec() - } - TxType::Eip1559 => { - let tx: Eip1559TransactionRequest = tx.into(); - let typed_tx: TypedTransaction = tx.into(); - typed_tx.rlp().to_vec() - } - TxType::Eip2930 => { - let tx: Eip2930TransactionRequest = tx.into(); - let typed_tx: TypedTransaction = tx.into(); - typed_tx.rlp().to_vec() - } - TxType::L1Msg => { - // L1 msg does not have signature - vec![] - } - } -} - /// Definition of all of the data related to an account. #[serde_as] #[derive(PartialEq, Eq, Debug, Default, Clone, Serialize)] @@ -205,7 +176,7 @@ pub struct BlockConstants { /// time pub timestamp: Word, /// number - pub number: U64, + pub number: u64, /// difficulty pub difficulty: Word, /// gas limit @@ -218,13 +189,17 @@ impl TryFrom<&Block> for BlockConstants { type Error = Error; fn try_from(block: &Block) -> Result { + let header = &block.header; Ok(Self { - coinbase: block.author.ok_or(Error::IncompleteBlock)?, - timestamp: block.timestamp, - number: block.number.ok_or(Error::IncompleteBlock)?, - difficulty: block.difficulty, - gas_limit: block.gas_limit, - base_fee: block.base_fee_per_gas.ok_or(Error::IncompleteBlock)?, + coinbase: header.miner, + timestamp: Word::from(header.timestamp), + number: header.number.ok_or(Error::IncompleteBlock)?, + difficulty: header.difficulty, + gas_limit: Word::from(header.gas_limit), + base_fee: header + .base_fee_per_gas + .map(Word::from) + .ok_or(Error::IncompleteBlock)?, }) } } @@ -234,7 +209,7 @@ impl BlockConstants { pub fn new( coinbase: Address, timestamp: Word, - number: U64, + number: u64, difficulty: Word, gas_limit: Word, base_fee: Word, @@ -299,17 +274,20 @@ impl From<&Transaction> for crate::Transaction { crate::Transaction { from: tx.from, to: tx.to, - nonce: tx.nonce, - gas: tx.gas_limit, + nonce: tx.nonce.to(), + gas: tx.gas_limit.to(), value: tx.value, - gas_price: tx.gas_price, - max_priority_fee_per_gas: tx.gas_tip_cap, - max_fee_per_gas: tx.gas_fee_cap, + gas_price: tx.gas_price.map(|g| g.to()), + max_priority_fee_per_gas: tx.gas_tip_cap.map(|g| g.to()), + max_fee_per_gas: tx.gas_fee_cap.map(|g| g.to()), input: tx.call_data.clone(), access_list: tx.access_list.clone(), - v: tx.v.into(), - r: tx.r, - s: tx.s, + signature: Some(TxSignature { + v: Word::from(tx.v), + r: tx.r, + s: tx.s, + ..Default::default() + }), hash: tx.hash, ..Default::default() } @@ -318,21 +296,22 @@ impl From<&Transaction> for crate::Transaction { impl From<&crate::Transaction> for Transaction { fn from(tx: &crate::Transaction) -> Transaction { + let signature = tx.signature.unwrap_or_default(); Transaction { tx_type: TxType::get_tx_type(tx), from: tx.from, to: tx.to, - nonce: tx.nonce, - gas_limit: tx.gas, + nonce: Word::from(tx.nonce), + gas_limit: Word::from(tx.gas), value: tx.value, - gas_price: tx.gas_price, - gas_tip_cap: tx.max_priority_fee_per_gas, - gas_fee_cap: tx.max_fee_per_gas, + gas_price: tx.gas_price.map(Word::from), + gas_tip_cap: tx.max_priority_fee_per_gas.map(Word::from), + gas_fee_cap: tx.max_fee_per_gas.map(Word::from), call_data: tx.input.clone(), access_list: tx.access_list.clone(), - v: tx.v.as_u64(), - r: tx.r, - s: tx.s, + v: signature.v.to(), + r: signature.r, + s: signature.s, rlp_bytes: tx.rlp().to_vec(), rlp_unsigned_bytes: get_rlp_unsigned(tx), hash: tx.hash, @@ -344,12 +323,12 @@ impl From<&Transaction> for TransactionRequest { fn from(tx: &Transaction) -> TransactionRequest { TransactionRequest { from: Some(tx.from), - to: tx.to.map(NameOrAddress::Address), - gas: Some(tx.gas_limit), - gas_price: tx.gas_price, + to: tx.to.map(TxKind::Call), + gas: Some(tx.gas_limit.to()), + gas_price: tx.gas_price.map(|g| g.to()), value: Some(tx.value), data: Some(tx.call_data.clone()), - nonce: Some(tx.nonce), + nonce: Some(tx.nonce.to()), ..Default::default() } } diff --git a/eth-types/src/l2_predeployed.rs b/eth-types/src/l2_predeployed.rs index a3d8eb072d..18aa13716e 100644 --- a/eth-types/src/l2_predeployed.rs +++ b/eth-types/src/l2_predeployed.rs @@ -2,52 +2,47 @@ // Copied from https://github.com/scroll-tech/go-ethereum/blob/8dc419a70b94f5ca185dcf818a48a3bd2eefc392/rollup/rcfg/config.go#L42 -use crate::Address; +use crate::{address, Address, U256}; /// helper for L2MessageQueue contract pub mod message_queue { use super::*; - use crate::U256; - use std::{str::FromStr, sync::LazyLock}; /// address of L2MessageQueue predeploy - pub static ADDRESS: LazyLock
= - LazyLock::new(|| Address::from_str("0x5300000000000000000000000000000000000000").unwrap()); + pub const ADDRESS: Address = address!("5300000000000000000000000000000000000000"); /// the slot of withdraw root in L2MessageQueue - pub static WITHDRAW_TRIE_ROOT_SLOT: U256 = U256::zero(); + pub const WITHDRAW_TRIE_ROOT_SLOT: U256 = U256::ZERO; } /// Helper for L1GasPriceOracle contract #[allow(missing_docs)] pub mod l1_gas_price_oracle { - use revm_primitives::HashMap; + use super::*; - use crate::{geth_types::Account, Address, U256}; - use std::{str::FromStr, sync::LazyLock}; + use crate::{geth_types::Account, Bytes}; + use std::sync::LazyLock; /// L1GasPriceOracle predeployed address - pub static ADDRESS: LazyLock
= - LazyLock::new(|| Address::from_str("0x5300000000000000000000000000000000000002").unwrap()); + pub const ADDRESS: Address = address!("5300000000000000000000000000000000000002"); /// L1 base fee slot in L1GasPriceOracle - pub static BASE_FEE_SLOT: LazyLock = LazyLock::new(|| U256::from(1)); + pub const BASE_FEE_SLOT: U256 = U256::from_limbs([1, 0, 0, 0]); /// The following 2 slots will be depreciated after curie fork /// L1 overhead slot in L1GasPriceOracle - pub static OVERHEAD_SLOT: LazyLock = LazyLock::new(|| U256::from(2)); + pub const OVERHEAD_SLOT: U256 = U256::from_limbs([2, 0, 0, 0]); /// L1 scalar slot in L1GasPriceOracle - pub static SCALAR_SLOT: LazyLock = LazyLock::new(|| U256::from(3)); + pub const SCALAR_SLOT: U256 = U256::from_limbs([3, 0, 0, 0]); /// THe following 3 slots plus `BASE_FEE_SLOT` will be used for l1 fee after curie fork /// L1 BlobBaseFee slot in L1GasPriceOracle after Curie fork - pub static L1_BLOB_BASEFEE_SLOT: LazyLock = LazyLock::new(|| U256::from(5)); + pub const L1_BLOB_BASEFEE_SLOT: U256 = U256::from_limbs([5, 0, 0, 0]); /// L1 commitScalar slot in L1GasPriceOracle after Curie fork - pub static COMMIT_SCALAR_SLOT: LazyLock = LazyLock::new(|| U256::from(6)); + pub const COMMIT_SCALAR_SLOT: U256 = U256::from_limbs([6, 0, 0, 0]); /// L1 blob_scalar slot in L1GasPriceOracle after Curie fork - pub static BLOB_SCALAR_SLOT: LazyLock = LazyLock::new(|| U256::from(7)); - pub static IS_CURIE_SLOT: LazyLock = LazyLock::new(|| U256::from(8)); - pub static INITIAL_COMMIT_SCALAR: LazyLock = - LazyLock::new(|| U256::from(230759955285u64)); - pub static INITIAL_BLOB_SCALAR: LazyLock = LazyLock::new(|| U256::from(417565260)); + pub const BLOB_SCALAR_SLOT: U256 = U256::from_limbs([7, 0, 0, 0]); + pub const IS_CURIE_SLOT: U256 = U256::from_limbs([8, 0, 0, 0]); + pub const INITIAL_COMMIT_SCALAR: U256 = U256::from_limbs([230759955285, 0, 0, 0]); + pub const INITIAL_BLOB_SCALAR: U256 = U256::from_limbs([417565260, 0, 0, 0]); /// Bytecode before curie hardfork /// curl 127.0.0.1:8545 -X POST -H "Content-Type: application/json" --data @@ -64,18 +59,19 @@ pub mod l1_gas_price_oracle { /// Default contract state for testing pub fn default_contract_account() -> Account { - let storages: Vec<(U256, U256)> = vec![ - (*BASE_FEE_SLOT, U256::from(1u64)), - (*L1_BLOB_BASEFEE_SLOT, U256::from(1u64)), - (*COMMIT_SCALAR_SLOT, *INITIAL_COMMIT_SCALAR), - (*BLOB_SCALAR_SLOT, *INITIAL_BLOB_SCALAR), + const STORAGES: [(U256, U256); 4] = [ + (BASE_FEE_SLOT, U256::from_limbs([1, 0, 0, 0])), + (L1_BLOB_BASEFEE_SLOT, U256::from_limbs([1, 0, 0, 0])), + (COMMIT_SCALAR_SLOT, INITIAL_COMMIT_SCALAR), + (BLOB_SCALAR_SLOT, INITIAL_BLOB_SCALAR), ]; + Account { - address: *ADDRESS, - nonce: U256::zero(), - balance: U256::from(1u64), - code: Vec::new().into(), - storage: HashMap::from_iter(storages), + address: ADDRESS, + nonce: U256::ZERO, + balance: U256::from_limbs([1, 0, 0, 0]), + code: Bytes::new(), + storage: std::collections::HashMap::from_iter(STORAGES), } } } diff --git a/eth-types/src/l2_types.rs b/eth-types/src/l2_types.rs index b9f489f838..430b9c1944 100644 --- a/eth-types/src/l2_types.rs +++ b/eth-types/src/l2_types.rs @@ -2,12 +2,9 @@ use crate::{ evm_types::{Gas, GasCost, OpcodeId, ProgramCounter}, - EthBlock, GethCallTrace, GethExecError, GethExecStep, GethExecTrace, GethPrestateTrace, Hash, - ToBigEndian, Transaction, H256, -}; -use ethers_core::types::{ - transaction::eip2930::{AccessList, AccessListItem}, - Address, Bytes, U256, U64, + AccessList, AccessListItem, Address, BlockTransactions, Bytes, ChainId, EthBlock, + GethCallTrace, GethExecError, GethExecStep, GethExecTrace, GethPrestateTrace, Hash, ToWord, + Transaction, TxSignature, H256, U256, U64, }; use itertools::Itertools; use serde::{Deserialize, Serialize}; @@ -33,7 +30,8 @@ pub struct BlockTraceV2 { /// coinbase's status AFTER execution pub coinbase: AccountTrace, /// block - pub header: EthBlock, + #[serde(rename = "header")] + pub eth_block: EthBlock, /// txs pub transactions: Vec, /// Accessed bytecodes with hashes @@ -60,7 +58,7 @@ impl From for BlockTraceV2 { codes, chain_id: b.chain_id, coinbase: b.coinbase, - header: b.header, + eth_block: b.eth_block, transactions: b.transactions, storage_trace: b.storage_trace, start_l1_queue_index: b.start_l1_queue_index, @@ -88,7 +86,8 @@ pub struct BlockTrace { /// coinbase's status AFTER execution pub coinbase: AccountTrace, /// block - pub header: EthBlock, + #[serde(rename = "header")] + pub eth_block: EthBlock, /// txs pub transactions: Vec, /// execution results @@ -136,17 +135,13 @@ impl BlockTrace { pub fn da_encode_header(&self) -> Vec { // https://github.com/scroll-tech/da-codec/blob/b842a0f961ad9180e16b50121ef667e15e071a26/encoding/codecv2/codecv2.go#L97 let num_txs = (self.num_l1_txs() + self.num_l2_txs()) as u16; + let header = &self.eth_block.header; std::iter::empty() // Block Values - .chain(self.header.number.unwrap().as_u64().to_be_bytes()) - .chain(self.header.timestamp.as_u64().to_be_bytes()) - .chain( - self.header - .base_fee_per_gas - .unwrap_or_default() - .to_be_bytes(), - ) - .chain(self.header.gas_limit.as_u64().to_be_bytes()) + .chain(header.number.unwrap().to_be_bytes()) + .chain(header.timestamp.to_be_bytes()) + .chain(header.base_fee_per_gas.unwrap_or_default().to_be_bytes()) + .chain((header.gas_limit as u64).to_be_bytes()) .chain(num_txs.to_be_bytes()) .collect_vec() // the `num_l1_txs` is not used for chunk hashing yet. @@ -154,22 +149,22 @@ impl BlockTrace { } impl From for EthBlock { - fn from(b: BlockTrace) -> Self { + fn from(mut b: BlockTrace) -> Self { let mut txs = Vec::new(); for (idx, tx_data) in b.transactions.iter().enumerate() { - let tx_idx = Some(U64::from(idx)); + let header = &b.eth_block.header; let tx = tx_data.to_eth_tx( - b.header.hash, - b.header.number, - tx_idx, - b.header.base_fee_per_gas, + header.hash, + header.number, + Some(idx as u64), + header.base_fee_per_gas, ); txs.push(tx) } + b.eth_block.header.difficulty = U256::ZERO; EthBlock { - transactions: txs, - difficulty: 0.into(), - ..b.header + transactions: BlockTransactions::Full(txs), + ..b.eth_block } } } @@ -178,42 +173,35 @@ impl From<&BlockTrace> for EthBlock { fn from(b: &BlockTrace) -> Self { let mut txs = Vec::new(); for (idx, tx_data) in b.transactions.iter().enumerate() { - let tx_idx = Some(U64::from(idx)); + let header = &b.eth_block.header; let tx = tx_data.to_eth_tx( - b.header.hash, - b.header.number, - tx_idx, - b.header.base_fee_per_gas, + header.hash, + header.number, + Some(idx as u64), + header.base_fee_per_gas, ); txs.push(tx) } + let mut blk = b.eth_block.clone(); + blk.header.difficulty = U256::ZERO; EthBlock { - transactions: txs, - difficulty: 0.into(), - ..b.header.clone() + transactions: BlockTransactions::Full(txs), + ..b.eth_block.clone() } } } impl From<&BlockTraceV2> for revm_primitives::BlockEnv { fn from(block: &BlockTraceV2) -> Self { + let header = &block.eth_block.header; revm_primitives::BlockEnv { - number: revm_primitives::U256::from(block.header.number.unwrap().as_u64()), - coinbase: block.coinbase.address.0.into(), - timestamp: revm_primitives::U256::from_be_bytes(block.header.timestamp.to_be_bytes()), - gas_limit: revm_primitives::U256::from_be_bytes(block.header.gas_limit.to_be_bytes()), - basefee: revm_primitives::U256::from_be_bytes( - block - .header - .base_fee_per_gas - .unwrap_or_default() - .to_be_bytes(), - ), - difficulty: revm_primitives::U256::from_be_bytes(block.header.difficulty.to_be_bytes()), - prevrandao: block - .header - .mix_hash - .map(|h| revm_primitives::B256::from(h.to_fixed_bytes())), + number: U256::from(header.number.unwrap()), + coinbase: block.coinbase.address, + timestamp: U256::from(header.timestamp), + gas_limit: U256::from(header.gas_limit), + basefee: U256::from(header.base_fee_per_gas.unwrap()), + difficulty: header.difficulty, + prevrandao: header.mix_hash, blob_excess_gas_and_price: None, } } @@ -221,23 +209,15 @@ impl From<&BlockTraceV2> for revm_primitives::BlockEnv { impl From<&BlockTrace> for revm_primitives::BlockEnv { fn from(block: &BlockTrace) -> Self { + let header = &block.eth_block.header; revm_primitives::BlockEnv { - number: revm_primitives::U256::from(block.header.number.unwrap().as_u64()), - coinbase: block.coinbase.address.0.into(), - timestamp: revm_primitives::U256::from_be_bytes(block.header.timestamp.to_be_bytes()), - gas_limit: revm_primitives::U256::from_be_bytes(block.header.gas_limit.to_be_bytes()), - basefee: revm_primitives::U256::from_be_bytes( - block - .header - .base_fee_per_gas - .unwrap_or_default() - .to_be_bytes(), - ), - difficulty: revm_primitives::U256::from_be_bytes(block.header.difficulty.to_be_bytes()), - prevrandao: block - .header - .mix_hash - .map(|h| revm_primitives::B256::from(h.to_fixed_bytes())), + number: U256::from(header.number.unwrap()), + coinbase: block.coinbase.address, + timestamp: U256::from(header.timestamp), + gas_limit: U256::from(header.gas_limit), + basefee: U256::from(header.base_fee_per_gas.unwrap()), + difficulty: header.difficulty, + prevrandao: header.mix_hash, blob_excess_gas_and_price: None, } } @@ -296,27 +276,28 @@ impl TransactionTrace { pub fn is_l1_tx(&self) -> bool { self.type_ == 0x7e } + /// transfer to eth type tx pub fn to_eth_tx( &self, block_hash: Option, - block_number: Option, - transaction_index: Option, - base_fee_per_gas: Option, + block_number: Option, + transaction_index: Option, + base_fee_per_gas: Option, ) -> Transaction { let gas_price = if self.type_ == 2 { - let priority_fee_per_gas = std::cmp::min( - self.gas_tip_cap.unwrap(), - self.gas_fee_cap.unwrap() - base_fee_per_gas.unwrap(), - ); - let effective_gas_price = priority_fee_per_gas + base_fee_per_gas.unwrap(); + let gas_tip_cap = self.gas_tip_cap.unwrap().to::(); + let gas_fee_cap = self.gas_fee_cap.unwrap().to::(); + let base_fee_per_gas = base_fee_per_gas.unwrap(); + let priority_fee_per_gas = std::cmp::min(gas_tip_cap, gas_fee_cap - base_fee_per_gas); + let effective_gas_price = priority_fee_per_gas + base_fee_per_gas; effective_gas_price } else { - self.gas_price + self.gas_price.to::() }; Transaction { hash: self.tx_hash, - nonce: U256::from(self.nonce), + nonce: self.nonce, block_hash, block_number, transaction_index, @@ -324,18 +305,21 @@ impl TransactionTrace { to: self.to, value: self.value, gas_price: Some(gas_price), - gas: U256::from(self.gas), + gas: self.gas as u128, input: self.data.clone(), - v: self.v, - r: self.r, - s: self.s, + signature: Some(TxSignature { + v: self.v.to(), + r: self.r, + s: self.s, + ..Default::default() + }), // FIXME: is this correct? None for legacy? - transaction_type: Some(U64::from(self.type_ as u64)), + transaction_type: Some(self.type_), access_list: self.access_list.as_ref().map(|al| AccessList(al.clone())), - max_priority_fee_per_gas: self.gas_tip_cap, - max_fee_per_gas: self.gas_fee_cap, - chain_id: Some(self.chain_id), - other: Default::default(), + max_priority_fee_per_gas: self.gas_tip_cap.map(|v| v.to::()), + max_fee_per_gas: self.gas_fee_cap.map(|v| v.to::()), + chain_id: Some(self.chain_id.to::()), + ..Default::default() } } } @@ -343,17 +327,17 @@ impl TransactionTrace { impl From<&TransactionTrace> for revm_primitives::TxEnv { fn from(tx: &TransactionTrace) -> Self { revm_primitives::TxEnv { - caller: tx.from.0.into(), + caller: tx.from, gas_limit: tx.gas, - gas_price: revm_primitives::U256::from_be_bytes(tx.gas_price.to_be_bytes()), + gas_price: tx.gas_price, transact_to: match tx.to { Some(to) => revm_primitives::TransactTo::Call(to.0.into()), None => revm_primitives::TransactTo::Create, }, - value: revm_primitives::U256::from_be_bytes(tx.value.to_be_bytes()), - data: revm_primitives::Bytes::copy_from_slice(tx.data.as_ref()), + value: tx.value, + data: tx.data.clone(), nonce: Some(tx.nonce), - chain_id: Some(tx.chain_id.as_u64()), + chain_id: Some(tx.chain_id.to()), access_list: tx .access_list .as_ref() @@ -361,21 +345,14 @@ impl From<&TransactionTrace> for revm_primitives::TxEnv { v.iter() .map(|e| { ( - e.address.0.into(), - e.storage_keys - .iter() - .map(|s| { - revm_primitives::U256::from_be_bytes(s.to_fixed_bytes()) - }) - .collect(), + e.address, + e.storage_keys.iter().map(|s| s.to_word()).collect(), ) }) .collect() }) .unwrap_or_default(), - gas_priority_fee: tx - .gas_tip_cap - .map(|g| revm_primitives::U256::from_be_bytes(g.to_be_bytes())), + gas_priority_fee: tx.gas_tip_cap, ..Default::default() } } @@ -452,7 +429,7 @@ impl From for GethExecTrace { fn from(e: ExecutionResult) -> Self { let struct_logs = e.exec_steps.into_iter().map(GethExecStep::from).collect(); GethExecTrace { - l1_fee: e.l1_fee.as_u64(), + l1_fee: e.l1_fee.to(), gas: Gas(e.gas), failed: e.failed, return_value: e.return_value, diff --git a/eth-types/src/l2_types/trace.rs b/eth-types/src/l2_types/trace.rs index 28bcf14be9..b48bd14dab 100644 --- a/eth-types/src/l2_types/trace.rs +++ b/eth-types/src/l2_types/trace.rs @@ -3,9 +3,8 @@ use crate::{ l2_types::BlockTrace, state_db::{CodeDB, StateDB}, utils::is_precompiled, - Address, Error, H256, + Address, Bytes, Error, H256, }; -use ethers_core::types::Bytes; use itertools::Itertools; use super::ExecStep; @@ -24,7 +23,10 @@ pub fn collect_codes( .collect_vec()); } - log::debug!("collect_codes for block {:?}", block.header.number); + log::debug!( + "collect_codes for block {:?}", + block.eth_block.header.number + ); if sdb.is_none() { log::warn!("collect_codes without sdb can be slow"); } @@ -115,7 +117,10 @@ pub fn collect_codes( log::warn!("unable to fetch code from step. {step:?}"); continue; } - log::info!("trace extcodecopy! block {:?}", block.header.number); + log::info!( + "trace extcodecopy! block {:?}", + block.eth_block.header.number + ); trace_code(&mut codes, code.unwrap(), step, None, sdb, block); } @@ -157,7 +162,7 @@ fn trace_code( &code.len(), step.op, step.gas, - block.header.number, + block.eth_block.header.number, ); hash } diff --git a/eth-types/src/lib.rs b/eth-types/src/lib.rs index d518ef95a2..feccf34818 100644 --- a/eth-types/src/lib.rs +++ b/eth-types/src/lib.rs @@ -36,19 +36,20 @@ pub mod state_db; pub mod utils; use crate::evm_types::{Gas, GasCost, OpcodeId, ProgramCounter}; -pub use bytecode::Bytecode; -pub use error::Error; -use ethers_core::types; -pub use ethers_core::{ - abi::ethereum_types::{BigEndianHash, U512}, - types::{ - transaction::{ - eip2930::{AccessList, AccessListItem}, - response::Transaction, - }, - Address, Block, Bytes, Signature, H160, H256, H64, U256, U64, +pub use alloy::{ + consensus::{SignableTransaction, TypedTransaction}, + core::primitives::{ + address, b256 as h256, keccak256, ruint::uint, Address, Bytes, ChainId, Signature, TxKind, + B256 as H256, B64 as H64, U256, U512, U64, + }, + rpc::types::{ + transaction::Signature as TxSignature, AccessList, AccessListItem, Block, + BlockTransactions, Header as EthBlockHeader, Transaction, TransactionInput, + TransactionRequest, }, }; +pub use bytecode::Bytecode; +pub use error::Error; use serde::{de, Deserialize, Deserializer, Serialize}; use std::{ collections::{HashMap, HashSet}, @@ -103,18 +104,6 @@ pub trait ToAddress { fn to_address(&self) -> Address; } -/// Trait used do convert a scalar value to a 32 byte array in big endian. -pub trait ToBigEndian { - /// Convert the value to a 32 byte array in big endian. - fn to_be_bytes(&self) -> [u8; 32]; -} - -/// Trait used to convert a scalar value to a 32 byte array in little endian. -pub trait ToLittleEndian { - /// Convert the value to a 32 byte array in little endian. - fn to_le_bytes(&self) -> [u8; 32]; -} - /// Trait used to convert a scalar value to a 16x u16 array in little endian. pub trait ToU16LittleEndian { /// Convert the value to a 16x u16 array in little endian. @@ -143,42 +132,15 @@ impl<'de> Deserialize<'de> for DebugU256 { } } -impl ToBigEndian for DebugU256 { - /// Encode the value as byte array in big endian. - fn to_be_bytes(&self) -> [u8; 32] { - let mut bytes = [0u8; 32]; - self.to_big_endian(&mut bytes); - bytes - } -} - impl ToWord for DebugU256 { fn to_word(&self) -> Word { - U256(self.0) + U256::from_limbs(self.0) } } /// Ethereum Word (256 bits). pub type Word = U256; -impl ToBigEndian for U256 { - /// Encode the value as byte array in big endian. - fn to_be_bytes(&self) -> [u8; 32] { - let mut bytes = [0u8; 32]; - self.to_big_endian(&mut bytes); - bytes - } -} - -impl ToLittleEndian for U256 { - /// Encode the value as byte array in little endian. - fn to_le_bytes(&self) -> [u8; 32] { - let mut bytes = [0u8; 32]; - self.to_little_endian(&mut bytes); - bytes - } -} - impl ToU16LittleEndian for U256 { /// Encode the value as 16x u16 array in little endian. /// @@ -189,7 +151,7 @@ impl ToU16LittleEndian for U256 { /// ] fn to_le_u16_array(&self) -> [u16; 16] { let mut u16_array: [u16; 16] = [0; 16]; - for (idx, u64_cell) in self.0.into_iter().enumerate() { + for (idx, u64_cell) in self.as_limbs().iter().copied().enumerate() { u16_array[idx * 4] = (u64_cell & 0xffff) as u16; u16_array[idx * 4 + 1] = ((u64_cell >> 16) & 0xffff) as u16; u16_array[idx * 4 + 2] = ((u64_cell >> 32) & 0xffff) as u16; @@ -206,28 +168,28 @@ impl ToAddress for U256 { } /// Ethereum Hash (256 bits). -pub type Hash = types::H256; +pub type Hash = alloy::core::primitives::B256; impl ToWord for Hash { fn to_word(&self) -> Word { - Word::from(self.as_bytes()) + Word::from_be_slice(self.as_slice()) } } impl ToWord for Address { fn to_word(&self) -> Word { let mut bytes = [0u8; 32]; - bytes[32 - Self::len_bytes()..].copy_from_slice(self.as_bytes()); - Word::from(bytes) + bytes[32 - Self::len_bytes()..].copy_from_slice(self.as_slice()); + Word::from_be_bytes(bytes) } } impl ToWord for bool { fn to_word(&self) -> Word { if *self { - Word::one() + Word::from_limbs([1, 0, 0, 0]) } else { - Word::zero() + Word::ZERO } } } @@ -271,13 +233,11 @@ impl ToWord for Word { /// Code hash related /// the empty keccak code hash -pub static KECCAK_CODE_HASH_EMPTY: LazyLock = LazyLock::new(|| { - Hash::from_str("0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470").unwrap() -}); +pub const KECCAK_CODE_HASH_EMPTY: Hash = + h256!("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"); /// the empty poseidon code hash -pub static POSEIDON_CODE_HASH_EMPTY: LazyLock = LazyLock::new(|| { - Hash::from_str("0x2098f5fb9e239eab3ceac3f27b81e481dc3124d55ffed523a839ee8446b64864").unwrap() -}); +pub const POSEIDON_CODE_HASH_EMPTY: Hash = + h256!("2098f5fb9e239eab3ceac3f27b81e481dc3124d55ffed523a839ee8446b64864"); /// Struct used to define the storage proof #[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize)] pub struct StorageProof { @@ -846,23 +806,6 @@ impl GethCallTrace { } } -#[macro_export] -/// Create an [`Address`] from a hex string. Panics on invalid input. -macro_rules! address { - ($addr_hex:expr) => {{ - use std::str::FromStr; - $crate::Address::from_str(&$addr_hex).expect("invalid hex Address") - }}; -} - -#[macro_export] -/// Create a [`Word`] from a hex string. Panics on invalid input. -macro_rules! word { - ($word_hex:expr) => { - $crate::Word::from_str_radix(&$word_hex, 16).expect("invalid hex Word") - }; -} - #[macro_export] /// Create a [`Word`] to [`Word`] HashMap from pairs of hex strings. Panics on /// invalid input. @@ -873,7 +816,7 @@ macro_rules! word_map { ($($key_hex:expr => $value_hex:expr),*) => { { std::collections::HashMap::from_iter([( - $(word!($key_hex), word!($value_hex)),* + $(uint!($key_hex), uint!($value_hex)),* )]) } } diff --git a/eth-types/src/sign_types.rs b/eth-types/src/sign_types.rs index e81f9109c7..d64bd5abc8 100644 --- a/eth-types/src/sign_types.rs +++ b/eth-types/src/sign_types.rs @@ -3,17 +3,10 @@ use crate::{ address, geth_types::{Transaction, TxType}, - word, Error, Word, H256, -}; -use ethers_core::{ - k256::{ - ecdsa::{RecoveryId, Signature as K256Signature, SigningKey, VerifyingKey}, - elliptic_curve::{consts::U32, sec1::ToEncodedPoint}, - PublicKey as K256PublicKey, - }, - types::{Address, Bytes, Signature, TransactionRequest, U256}, - utils::keccak256, + keccak256, uint, Address, Bytes, Error, Signature, TransactionInput, TransactionRequest, + TypedTransaction, Word, H256, U256, }; +use alloy::signers::local::PrivateKeySigner; use halo2curves::{ ff::FromUniformBytes, group::{ @@ -68,32 +61,33 @@ pub struct SignData { /// (nonce=0, gas=0, gas_price=0, to=0, value=0, data="") /// using the dummy private key = 1 pub fn get_dummy_tx() -> (TransactionRequest, Signature) { - let mut sk_be_scalar = [0u8; 32]; - sk_be_scalar[31] = 1_u8; + let sk_be_scalar = H256::with_last_byte(1); - let sk = SigningKey::from_bytes((&sk_be_scalar).into()).expect("sign key = 1"); - let wallet = ethers_signers::Wallet::from(sk); + let sk = PrivateKeySigner::from_bytes(&sk_be_scalar).expect("sign key = 1"); - let tx = TransactionRequest::new() + let mut tx = TransactionRequest::default() .nonce(0) - .gas(0) - .gas_price(U256::zero()) - .to(Address::zero()) - .value(U256::zero()) - .data(Bytes::default()); - let sighash: H256 = keccak256(tx.rlp_unsigned()).into(); - - let sig = wallet - .sign_hash(sighash) - .expect("sign dummy tx using dummy sk"); - assert_eq!(sig.v, 28); + .gas_limit(0) + .to(Address::with_last_byte(0)) + .value(U256::ZERO) + .input(TransactionInput::both(Bytes::default())) + .transaction_type(0); + tx.set_gas_price(0); + tx.complete_legacy().unwrap(); + let TypedTransaction::Legacy(mut tx_built) = tx.clone().build_unsigned().unwrap() else { + panic!("Failed to build typed tx"); + }; + + let sig = sk.sign_transaction_sync(&mut tx_built).unwrap(); + + assert_eq!(sig.v().to_u64(), 1); assert_eq!( - sig.r, - word!("4faabf49beea23083894651a6f34baaf3dc29b396fb5baf8b8454773f328df61") + sig.r(), + uint!(0x4faabf49beea23083894651a6f34baaf3dc29b396fb5baf8b8454773f328df61_U256) ); assert_eq!( - sig.s, - word!("0x75ae2dd5e4e688c9dbc6db7e75bafcb04ea141ca20332be9809a444d541272c1") + sig.s(), + uint!(0x75ae2dd5e4e688c9dbc6db7e75bafcb04ea141ca20332be9809a444d541272c1_U256) ); (tx, sig) @@ -126,7 +120,7 @@ static SIGN_DATA_DEFAULT: LazyLock = LazyLock::new(|| { let sign_data = tx.sign_data().unwrap(); assert_eq!( sign_data.get_addr(), - address!("0x7e5f4552091a69125d5dfcb7b8c2659029395bdf") + address!("7e5f4552091a69125d5dfcb7b8c2659029395bdf") ); sign_data @@ -223,3 +217,36 @@ pub fn pk_bytes_le(pk: &Secp256k1Affine) -> [u8; 64] { pk_le[32..].copy_from_slice(&pk_coord.y().to_bytes()); pk_le } + +#[cfg(test)] +pub(crate) mod tests { + use ethers_core::{ + k256::ecdsa::SigningKey, + types::{Address, Bytes, Signature, TransactionRequest, H256, U256}, + utils::keccak256, + }; + + pub fn get_dummy_tx_ethers() -> (TransactionRequest, Signature) { + let mut sk_be_scalar = [0u8; 32]; + sk_be_scalar[31] = 1_u8; + + let sk = SigningKey::from_bytes((&sk_be_scalar).into()).expect("sign key = 1"); + let wallet = ethers_signers::Wallet::from(sk); + + let tx = TransactionRequest::new() + .chain_id(2) + .nonce(0) + .gas(0) + .gas_price(U256::zero()) + .to(Address::zero()) + .value(U256::zero()) + .data(Bytes::default()); + let sighash: H256 = keccak256(tx.rlp_unsigned()).into(); + + let sig = wallet + .sign_hash(sighash) + .expect("sign dummy tx using dummy sk"); + + (tx, sig) + } +} diff --git a/eth-types/src/state_db.rs b/eth-types/src/state_db.rs index f092cdfd27..de332ed85f 100644 --- a/eth-types/src/state_db.rs +++ b/eth-types/src/state_db.rs @@ -15,12 +15,12 @@ static ACCOUNT_ZERO: LazyLock = LazyLock::new(Account::zero); static EMPTY_CODE_HASH: LazyLock = LazyLock::new(|| CodeDB::hash(&[])); /// bytes of empty code hash, in little endian order. pub static EMPTY_CODE_HASH_LE: LazyLock<[u8; 32]> = LazyLock::new(|| { - let mut bytes = EMPTY_CODE_HASH.to_fixed_bytes(); + let mut bytes = EMPTY_CODE_HASH.0; bytes.reverse(); bytes }); -const VALUE_ZERO: Word = Word::zero(); +const VALUE_ZERO: Word = Word::ZERO; /// Memory storage for contract code by code hash. #[derive(Debug)] @@ -62,7 +62,7 @@ impl CodeDB { /// Compute hash of given code. pub fn hash(code: &[u8]) -> Hash { - H256(hash_code(code).into()) + hash_code(code) } } @@ -88,12 +88,12 @@ impl Account { /// Return an empty account, with all values set at zero. pub fn zero() -> Self { Self { - nonce: Word::zero(), - balance: Word::zero(), + nonce: Word::ZERO, + balance: Word::ZERO, storage: HashMap::new(), code_hash: CodeDB::empty_code_hash(), - keccak_code_hash: *KECCAK_CODE_HASH_EMPTY, - code_size: Word::zero(), + keccak_code_hash: KECCAK_CODE_HASH_EMPTY, + code_size: Word::ZERO, } } @@ -101,12 +101,12 @@ impl Account { pub fn is_empty(&self) -> bool { debug_assert_ne!( self.code_hash, - Hash::zero(), + Hash::ZERO, "codehash inside statedb should never be 0, {self:?}" ); let is_code_hash_empty = self.code_hash.eq(&CodeDB::empty_code_hash()); if is_code_hash_empty { - debug_assert_eq!(Word::zero(), self.code_size); + debug_assert_eq!(Word::ZERO, self.code_size); } self.nonce.is_zero() && self.balance.is_zero() && is_code_hash_empty } @@ -116,7 +116,7 @@ impl Account { /// to be 0 pub fn code_hash_read(&self) -> Hash { if self.is_empty() { - Hash::zero() + Hash::ZERO } else { self.code_hash } @@ -251,7 +251,7 @@ impl StateDB { let found = if acc.storage.contains_key(key) { true } else { - acc.storage.insert(*key, Word::zero()); + acc.storage.insert(*key, Word::ZERO); false }; (found, acc.storage.get_mut(key).expect("key not inserted")) @@ -280,14 +280,14 @@ impl StateDB { /// Get nonce of account with `addr`. pub fn get_nonce(&self, addr: &Address) -> u64 { let (_, account) = self.get_account(addr); - account.nonce.as_u64() + account.nonce.to() } /// Increase nonce of account with `addr` and return the previous value. pub fn increase_nonce(&mut self, addr: &Address) -> u64 { let (_, account) = self.get_account_mut(addr); - let nonce = account.nonce.as_u64(); - account.nonce = account.nonce + 1; + let nonce: u64 = account.nonce.to(); + account.nonce = account.nonce + Word::from_limbs([1, 0, 0, 0]); nonce } @@ -388,7 +388,7 @@ mod statedb_tests { // Get non-existing storage key for non-existing account let (found, value) = statedb.get_storage(&addr_a, &Word::from(2)); assert!(!found); - assert_eq!(value, &Word::zero()); + assert_eq!(value, &Word::ZERO); // Get mut non-existing account and set nonce let (found, acc) = statedb.get_account_mut(&addr_a); @@ -404,7 +404,7 @@ mod statedb_tests { // Get non-existing storage key for existing account and set value let (found, value) = statedb.get_storage_mut(&addr_a, &Word::from(2)); assert!(!found); - assert_eq!(value, &Word::zero()); + assert_eq!(value, &Word::ZERO); *value = Word::from(101); // Get existing storage key and check value @@ -415,13 +415,13 @@ mod statedb_tests { // Get non-existing storage key for non-existing account and set value let (found, value) = statedb.get_storage_mut(&addr_b, &Word::from(3)); assert!(!found); - assert_eq!(value, &Word::zero()); + assert_eq!(value, &Word::ZERO); *value = Word::from(102); // Get existing account and check nonce let (found, acc) = statedb.get_account(&addr_b); assert!(found); - assert_eq!(acc.nonce, Word::zero()); + assert_eq!(acc.nonce, Word::ZERO); // Get existing storage key and check value let (found, value) = statedb.get_storage(&addr_b, &Word::from(3)); diff --git a/eth-types/src/utils.rs b/eth-types/src/utils.rs index 77c71044fc..be6a10ae93 100644 --- a/eth-types/src/utils.rs +++ b/eth-types/src/utils.rs @@ -1,6 +1,7 @@ //! Some handy helpers -use crate::Address; +use crate::geth_types::TxType; +use crate::{Address, SignableTransaction, Signature, TransactionRequest}; use revm_precompile::Precompiles; mod codehash; @@ -12,5 +13,132 @@ pub fn is_precompiled(address: &Address) -> bool { let precompiles = Precompiles::bernoulli(); #[cfg(not(feature = "scroll"))] let precompiles = Precompiles::berlin(); - precompiles.get(address.as_fixed_bytes().into()).is_some() + precompiles.get(address).is_some() +} + +pub trait TxRlpExt { + fn rlp(&self) -> Vec; + fn rlp_unsigned(&self) -> Vec; + + fn rlp_signed(&self, sig: &Signature) -> Vec; +} + +impl TxRlpExt for crate::Transaction { + fn rlp(&self) -> Vec { + todo!() + } + + fn rlp_unsigned(&self) -> Vec { + let tx_type = TxType::get_tx_type(self); + let mut tx_req = self.clone().into_request(); + match tx_type { + TxType::Eip155 => { + let sig_v = self.signature.unwrap_or_default().v.to::(); + tx_req.chain_id = Some(self.chain_id.unwrap_or_else(|| { + let recv_v = TxType::Eip155.get_recovery_id(sig_v) as u64; + (sig_v - recv_v - 35) / 2 + })); + } + TxType::PreEip155 => { + tx_req.chain_id = None; + } + TxType::L1Msg => return vec![], // L1Msg is not signed + _ => {} + }; + + // sanity check + #[cfg(debug_assertions)] + match tx_type { + TxType::Eip155 | TxType::PreEip155 => { + tx_req.complete_legacy().unwrap(); + assert_eq!(tx_req.preferred_type(), alloy::consensus::TxType::Legacy); + } + TxType::Eip1559 => { + tx_req.complete_1559().unwrap(); + assert_eq!(tx_req.preferred_type(), alloy::consensus::TxType::Eip1559); + } + TxType::Eip2930 => { + tx_req.complete_2930().unwrap(); + assert_eq!(tx_req.preferred_type(), alloy::consensus::TxType::Eip2930); + } + TxType::L1Msg => unreachable!("L1Msg is not signed"), + } + + let tx = tx_req.build_typed_tx().unwrap(); + match tx_type { + TxType::Eip155 | TxType::PreEip155 => tx.legacy().unwrap().encoded_for_signing(), + TxType::Eip1559 => tx.eip1559().unwrap().encoded_for_signing(), + TxType::Eip2930 => tx.eip2930().unwrap().encoded_for_signing(), + TxType::L1Msg => unreachable!("L1Msg is not signed"), + } + } +} + +#[cfg(test)] +pub mod tests { + use crate::geth_types::TxType; + + /// (old) Get the type of transaction + pub fn get_tx_type_ethers(tx: ðers_core::types::Transaction) -> TxType { + use ethers_core::types::U64; + match tx.transaction_type { + Some(x) if x == U64::from(1) => TxType::Eip2930, + Some(x) if x == U64::from(2) => TxType::Eip1559, + Some(x) if x == U64::from(0x7e) => TxType::L1Msg, + _ => { + if cfg!(feature = "scroll") { + if tx.v.is_zero() && tx.r.is_zero() && tx.s.is_zero() { + TxType::L1Msg + } else { + match tx.v.as_u64() { + 0 | 1 | 27 | 28 => TxType::PreEip155, + _ => TxType::Eip155, + } + } + } else { + match tx.v.as_u64() { + 0 | 1 | 27 | 28 => TxType::PreEip155, + _ => TxType::Eip155, + } + } + } + } + } + + /// (old) Get the RLP bytes for signing + pub fn get_rlp_unsigned_ethers(tx: ðers_core::types::Transaction) -> Vec { + use ethers_core::types::{ + transaction::eip2718::TypedTransaction, Eip1559TransactionRequest, + Eip2930TransactionRequest, TransactionRequest, + }; + let sig_v = tx.v; + match get_tx_type_ethers(tx) { + TxType::Eip155 => { + let mut tx: TransactionRequest = tx.into(); + tx.chain_id = Some(tx.chain_id.unwrap_or_else(|| { + let recv_v = TxType::Eip155.get_recovery_id(sig_v.as_u64()) as u64; + (sig_v - recv_v - 35) / 2 + })); + tx.rlp().to_vec() + } + TxType::PreEip155 => { + let tx: TransactionRequest = tx.into(); + tx.rlp_unsigned().to_vec() + } + TxType::Eip1559 => { + let tx: Eip1559TransactionRequest = tx.into(); + let typed_tx: TypedTransaction = tx.into(); + typed_tx.rlp().to_vec() + } + TxType::Eip2930 => { + let tx: Eip2930TransactionRequest = tx.into(); + let typed_tx: TypedTransaction = tx.into(); + typed_tx.rlp().to_vec() + } + TxType::L1Msg => { + // L1 msg does not have signature + vec![] + } + } + } } diff --git a/eth-types/src/utils/codehash.rs b/eth-types/src/utils/codehash.rs index 7abac7598e..58cc1ee800 100644 --- a/eth-types/src/utils/codehash.rs +++ b/eth-types/src/utils/codehash.rs @@ -1,16 +1,6 @@ //! Some handy helpers -use crate::{Address, Hash}; -use revm_precompile::Precompiles; - -/// Check if address is a precompiled or not. -pub fn is_precompiled(address: &Address) -> bool { - #[cfg(feature = "scroll")] - let precompiles = Precompiles::bernoulli(); - #[cfg(not(feature = "scroll"))] - let precompiles = Precompiles::berlin(); - precompiles.get(address.as_fixed_bytes().into()).is_some() -} +use crate::Hash; /// Default number of bytes to pack into a field element. pub const POSEIDON_HASH_BYTES_IN_FIELD: usize = 31; @@ -25,7 +15,7 @@ pub fn hash_code(code: &[u8]) -> Hash { /// Keccak code hash pub fn hash_code_keccak(code: &[u8]) -> Hash { - crate::H256(ethers_core::utils::keccak256(code)) + crate::keccak256(code) } /// Poseidon code hash @@ -38,8 +28,7 @@ pub fn hash_code_poseidon(code: &[u8]) -> Hash { let fls = (0..(code.len() / bytes_in_field)) .map(|i| i * bytes_in_field) .map(|i| { - let mut buf: [u8; 32] = [0; 32]; - U256::from_big_endian(&code[i..i + bytes_in_field]).to_little_endian(&mut buf); + let buf: [u8; 32] = U256::from_be_slice(&code[i..i + bytes_in_field]).to_le_bytes(); Fr::from_bytes(&buf).unwrap() }); let msgs: Vec<_> = fls @@ -50,8 +39,7 @@ pub fn hash_code_poseidon(code: &[u8]) -> Hash { // pad to bytes_in_field let mut last_buf = vec![0u8; bytes_in_field]; last_buf.as_mut_slice()[..last_code.len()].copy_from_slice(last_code); - let mut buf: [u8; 32] = [0; 32]; - U256::from_big_endian(&last_buf).to_little_endian(&mut buf); + let buf: [u8; 32] = U256::from_be_slice(&last_buf).to_le_bytes(); Some(Fr::from_bytes(&buf).unwrap()) }) .collect(); @@ -64,9 +52,9 @@ pub fn hash_code_poseidon(code: &[u8]) -> Hash { Fr::hash_msg(&msgs, Some(code.len() as u128 * HASHABLE_DOMAIN_SPEC)) }; - let mut buf: [u8; 32] = [0; 32]; - U256::from_little_endian(h.to_repr().as_ref()).to_big_endian(&mut buf); - Hash::from_slice(&buf) + U256::from_le_slice(h.to_repr().as_ref()) + .to_be_bytes() + .into() } #[test] diff --git a/prover/src/types.rs b/prover/src/types.rs index e733dc5454..28e40bcc13 100644 --- a/prover/src/types.rs +++ b/prover/src/types.rs @@ -35,7 +35,7 @@ impl ChunkProvingTask { self.block_traces .first() .map_or(0, |trace: &BlockTrace| { - trace.header.number.expect("block num").low_u64() + trace.eth_block.number.expect("block num").low_u64() }) .to_string() } diff --git a/prover/src/zkevm/capacity_checker.rs b/prover/src/zkevm/capacity_checker.rs index 4536f1b7f9..d5c27863d4 100644 --- a/prover/src/zkevm/capacity_checker.rs +++ b/prover/src/zkevm/capacity_checker.rs @@ -155,7 +155,7 @@ impl CircuitCapacityChecker { .as_ref() .map(|state| state.root()) .map(|root| H256(*root)) - .unwrap_or(trace.header.state_root); + .unwrap_or(trace.eth_block.state_root); // notice the trace has included all code required for builidng witness block, // so we do not need to pick them from previous one, but we still keep the // old codedb in previous run for some dedup work diff --git a/prover/src/zkevm/circuit/builder.rs b/prover/src/zkevm/circuit/builder.rs index 8f96a7c59a..641642aa5a 100644 --- a/prover/src/zkevm/circuit/builder.rs +++ b/prover/src/zkevm/circuit/builder.rs @@ -119,8 +119,8 @@ pub fn block_traces_to_witness_block(block_traces: Vec) -> Result) -> Result