diff --git a/Cargo.lock b/Cargo.lock index bca93f42f..5291e49c3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -297,6 +297,21 @@ dependencies = [ "syn", ] +[[package]] +name = "bit-set" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" + [[package]] name = "bitflags" version = "1.3.2" @@ -1796,6 +1811,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33ff8ae62cd3a9102e5637afc8452c55acf3844001bd5374e0b0bd7b6616c038" dependencies = [ "ahash 0.8.2", + "serde", ] [[package]] @@ -1859,6 +1875,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" @@ -3154,6 +3173,26 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "proptest" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0d9cc07f18492d879586c92b485def06bc850da3118075cd45d50e9c95b0e5" +dependencies = [ + "bit-set", + "bitflags", + "byteorder", + "lazy_static", + "num-traits", + "quick-error 2.0.1", + "rand 0.8.5", + "rand_chacha 0.3.1", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", +] + [[package]] name = "public-ip" version = "0.2.2" @@ -3191,6 +3230,18 @@ dependencies = [ "winapi", ] +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + [[package]] name = "quote" version = "1.0.23" @@ -3459,6 +3510,7 @@ dependencies = [ "codecs-derive", "ethers-core", "modular-bitfield", + "revm-interpreter", "serde", "test-fuzz", ] @@ -3806,6 +3858,7 @@ dependencies = [ "reth-codecs", "reth-rlp", "reth-rlp-derive", + "revm-interpreter", "secp256k1 0.24.2", "serde", "serde_json", @@ -3862,9 +3915,11 @@ dependencies = [ "rand 0.8.5", "reth-rlp", "reth-rlp-derive", + "revm-interpreter", "rlp", "secp256k1 0.24.2", "smol_str", + "tracing", ] [[package]] @@ -3992,6 +4047,7 @@ dependencies = [ "rand 0.8.5", "reth-metrics-derive", "reth-primitives", + "ruint", "serde", "thiserror", "tokio", @@ -4001,7 +4057,7 @@ dependencies = [ [[package]] name = "revm" version = "2.3.1" -source = "git+https://github.com/bluealloy/revm?branch=main#85f2b549631e597f2199ff4b5d58e5fb1c66ea4d" +source = "git+https://github.com/bluealloy/revm?rev=3a13c9c8a0cda728941f1b26db0beb1025744ea9#3a13c9c8a0cda728941f1b26db0beb1025744ea9" dependencies = [ "arrayref", "auto_impl", @@ -4012,16 +4068,38 @@ dependencies = [ "hex", "hex-literal", "num_enum", + "revm-interpreter", "revm_precompiles", "rlp", "ruint", "sha3", ] +[[package]] +name = "revm-interpreter" +version = "0.1.0" +source = "git+https://github.com/bluealloy/revm?rev=3a13c9c8a0cda728941f1b26db0beb1025744ea9#3a13c9c8a0cda728941f1b26db0beb1025744ea9" +dependencies = [ + "arbitrary", + "arrayref", + "auto_impl", + "bytes", + "derive_more", + "fixed-hash", + "hashbrown 0.13.1", + "hex", + "hex-literal", + "num_enum", + "rlp", + "ruint", + "serde", + "sha3", +] + [[package]] name = "revm_precompiles" version = "1.1.2" -source = "git+https://github.com/bluealloy/revm?branch=main#85f2b549631e597f2199ff4b5d58e5fb1c66ea4d" +source = "git+https://github.com/bluealloy/revm?rev=3a13c9c8a0cda728941f1b26db0beb1025744ea9#3a13c9c8a0cda728941f1b26db0beb1025744ea9" dependencies = [ "bytes", "hashbrown 0.13.1", @@ -4097,11 +4175,14 @@ version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ad3a104dc8c3867f653b0fec89c65e00b0ceb752718ad282177a7e0f33257ac" dependencies = [ + "arbitrary", "derive_more", "primitive-types", + "proptest", "rlp", "ruint-macro", "rustc_version", + "serde", "thiserror", ] @@ -4185,6 +4266,18 @@ version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5583e89e108996506031660fe09baa5011b9dd0341b89029313006d1fb508d70" +[[package]] +name = "rusty-fork" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb3dcc6e454c328bb824492db107ab7c0ae8fcffe4ad210136ef014458c1bc4f" +dependencies = [ + "fnv", + "quick-error 1.2.3", + "tempfile", + "wait-timeout", +] + [[package]] name = "ryu" version = "1.0.12" @@ -5352,6 +5445,15 @@ version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" +[[package]] +name = "wait-timeout" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f200f5b12eb75f8c1ed65abd4b2db8a6e1b138a20de009dacee265a2498f3f6" +dependencies = [ + "libc", +] + [[package]] name = "waker-fn" version = "1.1.0" diff --git a/bin/reth/src/test_eth_chain/models.rs b/bin/reth/src/test_eth_chain/models.rs index 709151e86..a3c5227c7 100644 --- a/bin/reth/src/test_eth_chain/models.rs +++ b/bin/reth/src/test_eth_chain/models.rs @@ -77,16 +77,16 @@ impl From
for SealedHeader { fn from(value: Header) -> Self { SealedHeader::new( RethHeader { - base_fee_per_gas: value.base_fee_per_gas.map(|v| v.0.as_u64()), + base_fee_per_gas: value.base_fee_per_gas.map(|v| v.0.to::()), beneficiary: value.coinbase, difficulty: value.difficulty.0, extra_data: value.extra_data.0, - gas_limit: value.gas_limit.0.as_u64(), - gas_used: value.gas_used.0.as_u64(), + gas_limit: value.gas_limit.0.to::(), + gas_used: value.gas_used.0.to::(), mix_hash: value.mix_hash, nonce: value.nonce.into_uint().as_u64(), - number: value.number.0.as_u64(), - timestamp: value.timestamp.0.as_u64(), + number: value.number.0.to::(), + timestamp: value.timestamp.0.to::(), transactions_root: value.transactions_trie, receipts_root: value.receipt_trie, ommers_hash: value.uncle_hash, diff --git a/bin/reth/src/test_eth_chain/runner.rs b/bin/reth/src/test_eth_chain/runner.rs index 6d55ae2be..c8308ae9e 100644 --- a/bin/reth/src/test_eth_chain/runner.rs +++ b/bin/reth/src/test_eth_chain/runner.rs @@ -128,7 +128,7 @@ pub async fn run_test(path: PathBuf) -> eyre::Result<()> { address, RethAccount { balance: account.balance.0, - nonce: account.nonce.0.as_u64(), + nonce: account.nonce.0.to::(), bytecode_hash: code_hash, }, )?; @@ -137,9 +137,10 @@ pub async fn run_test(path: PathBuf) -> eyre::Result<()> { } account.storage.iter().try_for_each(|(k, v)| { tracing::trace!("Update storage: {address} key:{:?} val:{:?}", k.0, v.0); - let mut key = H256::zero(); - k.0.to_big_endian(&mut key.0); - tx.put::(address, StorageEntry { key, value: v.0 }) + tx.put::( + address, + StorageEntry { key: H256::from_slice(&k.0.to_be_bytes::<32>()), value: v.0 }, + ) })?; Ok(()) @@ -154,7 +155,7 @@ pub async fn run_test(path: PathBuf) -> eyre::Result<()> { Ok(walker.map(|mut walker| { let mut map: HashMap> = HashMap::new(); while let Some(Ok((address, slot))) = walker.next() { - let key = U256::from_big_endian(&slot.key.0); + let key = U256::from_be_bytes(slot.key.0); map.entry(address).or_default().insert(key, slot.value); } map @@ -165,7 +166,7 @@ pub async fn run_test(path: PathBuf) -> eyre::Result<()> { // Initialize the execution stage // Hardcode the chain_id to Ethereum 1. let mut stage = - ExecutionStage::new(reth_executor::Config { chain_id: 1.into(), spec_upgrades }); + ExecutionStage::new(reth_executor::Config { chain_id: U256::from(1), spec_upgrades }); // Call execution stage let input = ExecInput::default(); @@ -188,7 +189,7 @@ pub async fn run_test(path: PathBuf) -> eyre::Result<()> { let storage = walker.map(|mut walker| { let mut map: HashMap> = HashMap::new(); while let Some(Ok((address, slot))) = walker.next() { - let key = U256::from_big_endian(&slot.key.0); + let key = U256::from_be_bytes(slot.key.0); map.entry(address).or_default().insert(key, slot.value); } map @@ -206,7 +207,7 @@ pub async fn run_test(path: PathBuf) -> eyre::Result<()> { our_account.balance )) } - if test_account.nonce.0.as_u64() != our_account.nonce { + if test_account.nonce.0.to::() != our_account.nonce { return Err(eyre!( "Account {address} nonce diff, expected {} got {}", test_account.nonce.0, diff --git a/bin/reth/src/util/chainspec.rs b/bin/reth/src/util/chainspec.rs index e0f9ee2f5..c0fc92cb6 100644 --- a/bin/reth/src/util/chainspec.rs +++ b/bin/reth/src/util/chainspec.rs @@ -1,6 +1,5 @@ use reth_primitives::{ - utils::serde_helpers::{deserialize_number, deserialize_stringified_u64}, - Address, Bytes, Header, H256, U256, + utils::serde_helpers::deserialize_stringified_u64, Address, Bytes, Header, H256, U256, }; use serde::{Deserialize, Serialize}; use std::{collections::HashMap, path::PathBuf}; @@ -32,7 +31,6 @@ pub struct Genesis { #[serde(deserialize_with = "deserialize_stringified_u64")] pub gas_limit: u64, /// The genesis header difficulty. - #[serde(deserialize_with = "deserialize_number")] pub difficulty: U256, /// The genesis header mix hash. pub mix_hash: H256, diff --git a/crates/common/rlp/Cargo.toml b/crates/common/rlp/Cargo.toml index b88818e84..304287496 100644 --- a/crates/common/rlp/Cargo.toml +++ b/crates/common/rlp/Cargo.toml @@ -16,6 +16,8 @@ enr = { version = "0.7", default-features = false, optional = true } rlp = { version = "0.5.2", default-features = false, optional = true } ethereum-types = { version = "0.14", features = ["codec"], optional = true } reth-rlp-derive = { version = "0.1", path = "../rlp-derive", optional = true } +tracing = "0.1.37" +revm-interpreter = { git = "https://github.com/bluealloy/revm", rev = "3a13c9c8a0cda728941f1b26db0beb1025744ea9", features = ["with-serde"] } [dev-dependencies] reth-rlp = { path = ".", package = "reth-rlp", features = [ diff --git a/crates/common/rlp/benches/bench.rs b/crates/common/rlp/benches/bench.rs index 34cb9c994..57a596192 100644 --- a/crates/common/rlp/benches/bench.rs +++ b/crates/common/rlp/benches/bench.rs @@ -33,10 +33,7 @@ fn bench_encode(c: &mut Criterion) { c.bench_function("encode_1000_u64", |b| { b.iter(|| { let mut out = BytesMut::new(); - reth_rlp::encode_list( - (0..1000u64).into_iter().collect::>().as_slice(), - &mut out, - ); + reth_rlp::encode_list((0..1000u64).collect::>().as_slice(), &mut out); }) }); } @@ -59,7 +56,7 @@ fn bench_decode(c: &mut Criterion) { }) }); c.bench_function("decode_1000_u64", |b| { - let input = (0..1000u64).into_iter().collect::>(); + let input = (0..1000u64).collect::>(); let mut data = BytesMut::new(); reth_rlp::encode_list(input.as_slice(), &mut data); b.iter(|| { diff --git a/crates/common/rlp/src/decode.rs b/crates/common/rlp/src/decode.rs index fa68dc741..afc761c3f 100644 --- a/crates/common/rlp/src/decode.rs +++ b/crates/common/rlp/src/decode.rs @@ -252,6 +252,7 @@ decode_integer!(ethnum::U256); mod ethereum_types_support { use super::*; use ethereum_types::*; + use revm_interpreter::{B160, B256, U256 as RU256}; macro_rules! fixed_hash_impl { ($t:ty) => { @@ -263,6 +264,9 @@ mod ethereum_types_support { }; } + fixed_hash_impl!(B160); + fixed_hash_impl!(B256); + fixed_hash_impl!(H64); fixed_hash_impl!(H128); fixed_hash_impl!(H160); @@ -302,6 +306,39 @@ mod ethereum_types_support { }; } + macro_rules! fixed_revm_uint_impl { + ($t:ty, $n_bytes:tt) => { + impl Decodable for $t { + fn decode(buf: &mut &[u8]) -> Result { + let h = Header::decode(buf)?; + if h.list { + return Err(DecodeError::UnexpectedList) + } + if h.payload_length > $n_bytes { + return Err(DecodeError::Overflow) + } + if buf.remaining() < h.payload_length { + return Err(DecodeError::InputTooShort) + } + // In the case of 0x80, the Header will be decoded, leaving h.payload_length to + // be zero. + // 0x80 is the canonical encoding of 0, so we return 0 here. + if h.payload_length == 0 { + return Ok(<$t>::from(0u8)) + } + let n = <$t>::from_be_bytes( + static_left_pad::<$n_bytes>(&buf[..h.payload_length]) + .ok_or(DecodeError::LeadingZero)?, + ); + buf.advance(h.payload_length); + Ok(n) + } + } + }; + } + + fixed_revm_uint_impl!(RU256, 32); + fixed_uint_impl!(U64, 8); fixed_uint_impl!(U128, 16); fixed_uint_impl!(U256, 32); diff --git a/crates/common/rlp/src/encode.rs b/crates/common/rlp/src/encode.rs index 46fa80140..23532cd62 100644 --- a/crates/common/rlp/src/encode.rs +++ b/crates/common/rlp/src/encode.rs @@ -240,6 +240,8 @@ mod ethereum_types_support { use super::*; use ethereum_types::*; + use revm_interpreter::{B160, B256, U256 as RU256}; + macro_rules! fixed_hash_impl { ($t:ty) => { impl Encodable for $t { @@ -255,6 +257,8 @@ mod ethereum_types_support { }; } + fixed_hash_impl!(B160); + fixed_hash_impl!(B256); fixed_hash_impl!(H64); fixed_hash_impl!(H128); fixed_hash_impl!(H160); @@ -289,6 +293,26 @@ mod ethereum_types_support { fixed_uint_impl!(U128, 16); fixed_uint_impl!(U256, 32); fixed_uint_impl!(U512, 64); + + macro_rules! fixed_revm_uint_impl { + ($t:ty, $n_bytes:tt) => { + impl Encodable for $t { + fn length(&self) -> usize { + if *self < <$t>::from(EMPTY_STRING_CODE) { + 1 + } else { + 1 + self.byte_len() + } + } + + fn encode(&self, out: &mut dyn bytes::BufMut) { + self.to_be_bytes_trimmed_vec().as_slice().encode(out) + } + } + }; + } + + fixed_revm_uint_impl!(RU256, 32); } macro_rules! slice_impl { diff --git a/crates/consensus/src/config.rs b/crates/consensus/src/config.rs index d63aa8395..b87e8ba3d 100644 --- a/crates/consensus/src/config.rs +++ b/crates/consensus/src/config.rs @@ -1,6 +1,6 @@ //! Reth block execution/validation configuration and constants use reth_executor::{Config as ExecutorConfig, SpecUpgrades}; -use reth_primitives::BlockNumber; +use reth_primitives::{BlockNumber, U256}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; @@ -80,7 +80,7 @@ impl Default for Config { impl From<&Config> for ExecutorConfig { fn from(value: &Config) -> Self { Self { - chain_id: value.chain_id.into(), + chain_id: U256::from(value.chain_id), spec_upgrades: SpecUpgrades { frontier: 0, homestead: value.homestead_block, diff --git a/crates/consensus/src/engine/mod.rs b/crates/consensus/src/engine/mod.rs index ff3ca4f2b..c3661dbc0 100644 --- a/crates/consensus/src/engine/mod.rs +++ b/crates/consensus/src/engine/mod.rs @@ -6,8 +6,8 @@ use reth_executor::{ use reth_interfaces::consensus::ForkchoiceState; use reth_primitives::{ proofs::{self, EMPTY_LIST_HASH}, - rpc::BlockId, - Header, SealedBlock, TransactionSigned, H64, + rpc::{BlockId, H256 as EthersH256}, + Header, SealedBlock, TransactionSigned, H64, U256, }; use reth_provider::{BlockProvider, HeaderProvider, StateProvider}; use reth_rlp::Decodable; @@ -120,7 +120,7 @@ impl EthConsensusEngine< return Err(EngineApiError::PayloadExtraData(payload.extra_data)) } - if payload.base_fee_per_gas.is_zero() { + if payload.base_fee_per_gas == U256::ZERO { return Err(EngineApiError::PayloadBaseFee(payload.base_fee_per_gas)) } @@ -142,7 +142,7 @@ impl EthConsensusEngine< gas_used: payload.gas_used.as_u64(), timestamp: payload.timestamp.as_u64(), mix_hash: payload.prev_randao, - base_fee_per_gas: Some(payload.base_fee_per_gas.as_u64()), + base_fee_per_gas: Some(payload.base_fee_per_gas.to::()), extra_data: payload.extra_data.0, // Defaults ommers_hash: EMPTY_LIST_HASH, @@ -184,13 +184,13 @@ impl ConsensusEngine return Ok(PayloadStatus::new(PayloadStatusEnum::Valid, block.hash())) } - let Some(parent) = self.client.block(BlockId::Hash(block.parent_hash))? else { + let Some(parent) = self.client.block(BlockId::Hash(EthersH256(block.parent_hash.0)))? else { // TODO: cache block for storing later return Ok(PayloadStatus::from_status(PayloadStatusEnum::Syncing)) }; if let Some(parent_td) = self.client.header_td(&block.parent_hash)? { - if parent_td <= self.config.merge_terminal_total_difficulty.into() { + if parent_td <= U256::from(self.config.merge_terminal_total_difficulty) { return Ok(PayloadStatus::from_status(PayloadStatusEnum::Invalid { validation_error: EngineApiError::PayloadPreMerge.to_string(), })) @@ -273,7 +273,7 @@ impl ConsensusEngine } = config; // Compare total difficulty values - let merge_terminal_td = self.config.merge_terminal_total_difficulty.into(); + let merge_terminal_td = U256::from(self.config.merge_terminal_total_difficulty); if merge_terminal_td != terminal_total_difficulty { return Err(EngineApiError::TerminalTD { execution: merge_terminal_td, @@ -290,7 +290,7 @@ impl ConsensusEngine } // Attempt to look up terminal block hash - let local_hash = self.client.block_hash(terminal_block_number.as_u64().into())?; + let local_hash = self.client.block_hash(U256::from(terminal_block_number.as_u64()))?; // Transition configuration exchange is successful if block hashes match match local_hash { @@ -372,13 +372,13 @@ mod tests { // Valid extra data let block_with_valid_extra_data = transform_block(block.clone(), |mut b| { - b.header.extra_data = BytesMut::zeroed(32).freeze().into(); + b.header.extra_data = BytesMut::zeroed(32).freeze(); b }); assert_matches!(engine.try_construct_block(block_with_valid_extra_data.into()), Ok(_)); // Invalid extra data - let block_with_invalid_extra_data: Bytes = BytesMut::zeroed(33).freeze().into(); + let block_with_invalid_extra_data: Bytes = BytesMut::zeroed(33).freeze(); let invalid_extra_data_block = transform_block(block.clone(), |mut b| { b.header.extra_data = block_with_invalid_extra_data.clone(); b @@ -395,7 +395,7 @@ mod tests { }); assert_matches!( engine.try_construct_block(block_with_zero_base_fee.into()), - Err(EngineApiError::PayloadBaseFee(val)) if val == 0.into() + Err(EngineApiError::PayloadBaseFee(val)) if val == U256::ZERO ); // Invalid encoded transactions @@ -421,7 +421,7 @@ mod tests { // None zero difficulty let block_with_difficulty = transform_block(block.clone(), |mut b| { - b.header.difficulty = 1.into(); + b.header.difficulty = U256::from(1); b }); assert_matches!( @@ -442,7 +442,7 @@ mod tests { ); // Valid block - let valid_block = block.clone(); + let valid_block = block; assert_matches!(engine.try_construct_block(valid_block.into()), Ok(_)); } @@ -514,7 +514,7 @@ mod tests { let (result_tx, result_rx) = oneshot::channel(); let parent = transform_block(random_block(100, None, None, Some(0)), |mut b| { - b.header.difficulty = config.merge_terminal_total_difficulty.into(); + b.header.difficulty = U256::from(config.merge_terminal_total_difficulty); b }); let block = random_block(101, Some(parent.hash()), None, Some(0)); @@ -551,7 +551,7 @@ mod tests { let parent_timestamp = block_timestamp + 10; let parent = transform_block(random_block(100, None, None, Some(0)), |mut b| { b.header.timestamp = parent_timestamp; - b.header.difficulty = (config.merge_terminal_total_difficulty + 1).into(); + b.header.difficulty = U256::from(config.merge_terminal_total_difficulty + 1); b }); let block = @@ -625,7 +625,7 @@ mod tests { tokio::spawn(engine); let transition_config = TransitionConfiguration { - terminal_total_difficulty: (config.merge_terminal_total_difficulty + 1).into(), + terminal_total_difficulty: U256::from(config.merge_terminal_total_difficulty + 1), ..Default::default() }; @@ -639,8 +639,8 @@ mod tests { assert_matches!( result_rx.await, Ok(Err(EngineApiError::TerminalTD { execution, consensus })) - if execution == config.merge_terminal_total_difficulty.into() - && consensus == transition_config.terminal_total_difficulty.into() + if execution == U256::from(config.merge_terminal_total_difficulty) + && consensus == U256::from(transition_config.terminal_total_difficulty) ); } @@ -663,7 +663,7 @@ mod tests { let execution_terminal_block = random_block(terminal_block_number, None, None, None); let transition_config = TransitionConfiguration { - terminal_total_difficulty: config.merge_terminal_total_difficulty.into(), + terminal_total_difficulty: U256::from(config.merge_terminal_total_difficulty), terminal_block_hash: consensus_terminal_block.hash(), terminal_block_number: terminal_block_number.into(), }; @@ -722,7 +722,7 @@ mod tests { let terminal_block = random_block(terminal_block_number, None, None, None); let transition_config = TransitionConfiguration { - terminal_total_difficulty: config.merge_terminal_total_difficulty.into(), + terminal_total_difficulty: U256::from(config.merge_terminal_total_difficulty), terminal_block_hash: terminal_block.hash(), terminal_block_number: terminal_block_number.into(), }; diff --git a/crates/consensus/src/verification.rs b/crates/consensus/src/verification.rs index df3856101..551463859 100644 --- a/crates/consensus/src/verification.rs +++ b/crates/consensus/src/verification.rs @@ -45,7 +45,7 @@ pub fn validate_header_standalone( // EIP-3675: Upgrade consensus to Proof-of-Stake: // https://eips.ethereum.org/EIPS/eip-3675#replacing-difficulty-with-0 if header.number >= config.paris_block { - if header.difficulty != U256::zero() { + if header.difficulty != U256::ZERO { return Err(Error::TheMergeDifficultyIsNotZero) } @@ -467,7 +467,7 @@ mod tests { transactions_root: hex!("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421").into(), receipts_root: hex!("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421").into(), logs_bloom: hex!("002400000000004000220000800002000000000000000000000000000000100000000000000000100000000000000021020000000800000006000000002100040000000c0004000000000008000008200000000000000000000000008000000001040000020000020000002000000800000002000020000000022010000000000000010002001000000000020200000000000001000200880000004000000900020000000000020000000040000000000000000000000000000080000000000001000002000000000000012000200020000000000000001000000000000020000010321400000000100000000000000000000000000000400000000000000000").into(), - difficulty: 0x00.into(), // total difficulty: 0xc70d815d562d3cfa955).into(), + difficulty: U256::ZERO, // total difficulty: 0xc70d815d562d3cfa955).into(), number: 0xf21d20, gas_limit: 0x1c9c380, gas_used: 0x6e813, diff --git a/crates/executor/Cargo.toml b/crates/executor/Cargo.toml index 32e80e135..7195e90ce 100644 --- a/crates/executor/Cargo.toml +++ b/crates/executor/Cargo.toml @@ -14,7 +14,8 @@ reth-rlp = { path = "../common/rlp" } reth-db = { path = "../storage/db" } reth-provider = { path = "../storage/provider" } -revm = { git = "https://github.com/bluealloy/revm", branch = "main"} +revm = { git = "https://github.com/bluealloy/revm", rev = "3a13c9c8a0cda728941f1b26db0beb1025744ea9" } + # remove from reth and reexport from revm hashbrown = "0.13" diff --git a/crates/executor/src/config.rs b/crates/executor/src/config.rs index c66526d31..ef1c92548 100644 --- a/crates/executor/src/config.rs +++ b/crates/executor/src/config.rs @@ -21,7 +21,7 @@ pub struct Config { impl Config { /// Create new config for ethereum. pub fn new_ethereum() -> Self { - Self { chain_id: 1.into(), spec_upgrades: SpecUpgrades::new_ethereum() } + Self { chain_id: U256::from(1), spec_upgrades: SpecUpgrades::new_ethereum() } } } diff --git a/crates/executor/src/executor.rs b/crates/executor/src/executor.rs index a352a59ae..c1d722000 100644 --- a/crates/executor/src/executor.rs +++ b/crates/executor/src/executor.rs @@ -13,7 +13,7 @@ use reth_primitives::{ use reth_provider::StateProvider; use revm::{ db::AccountState, Account as RevmAccount, AccountInfo, AnalysisKind, Bytecode, Database, - Return, SpecId, B160, EVM, U256 as evmU256, + Return, SpecId, EVM, }; use std::collections::BTreeMap; @@ -95,7 +95,7 @@ pub struct AccountChangeSet { /// Old and New account account change. pub account: AccountInfoChangeSet, /// Storage containing key -> (OldValue,NewValue). in case that old value is not existing - /// we can expect to have U256::zero(), same with new value. + /// we can expect to have U256::ZERO, same with new value. pub storage: BTreeMap, /// Just to make sure that we are taking selfdestruct cleaning we have this field that wipes /// storage. There are instances where storage is changed but account is not touched, so we @@ -124,7 +124,7 @@ pub struct ExecutionResult { /// BTreeMap is used to have sorted values pub fn commit_changes( db: &mut SubState, - changes: hashbrown::HashMap, + changes: hashbrown::HashMap, ) -> (BTreeMap, BTreeMap) { let mut change = BTreeMap::new(); let mut new_bytecodes = BTreeMap::new(); @@ -132,7 +132,7 @@ pub fn commit_changes( for (address, account) in changes { if account.is_destroyed { // get old account that we are destroying. - let db_account = match db.accounts.entry(B160(address.0)) { + let db_account = match db.accounts.entry(address) { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(_entry) => { panic!("Left panic to critically jumpout if happens, as every account shound be hot loaded."); @@ -141,7 +141,7 @@ pub fn commit_changes( // Insert into `change` a old account and None for new account // and mark storage to be mapped change.insert( - H160(address.0), + address, AccountChangeSet { account: AccountInfoChangeSet::Destroyed { old: to_reth_acc(&db_account.info) }, storage: BTreeMap::new(), @@ -175,7 +175,7 @@ pub fn commit_changes( // get old account that is going to be overwritten or none if it does not exist // and get new account that was just inserted. new account mut ref is used for // inserting storage - let (account_info_changeset, new_account) = match db.accounts.entry(B160(address.0)) { + let (account_info_changeset, new_account) = match db.accounts.entry(address) { Entry::Vacant(entry) => { let entry = entry.insert(Default::default()); entry.info = account.info.clone(); @@ -217,19 +217,13 @@ pub fn commit_changes( // insert storage into new db account. new_account.storage.extend(account.storage.into_iter().map(|(key, value)| { - storage.insert( - U256(*key.as_limbs()), - ( - U256(*value.original_value().as_limbs()), - U256(*value.present_value().as_limbs()), - ), - ); + storage.insert(key, (value.original_value(), value.present_value())); (key, value.present_value()) })); // Insert into change. change.insert( - H160(address.0), + address, AccountChangeSet { account: account_info_changeset, storage, wipe_storage }, ); } @@ -313,7 +307,7 @@ pub fn execute( evm.database(db); let spec_id = config.spec_upgrades.revm_spec(header.number); - evm.env.cfg.chain_id = evmU256::from_limbs(config.chain_id.0); + evm.env.cfg.chain_id = config.chain_id; evm.env.cfg.spec_id = config.spec_upgrades.revm_spec(header.number); evm.env.cfg.perf_all_precompiles_have_balance = false; evm.env.cfg.perf_analyse_created_bytecodes = AnalysisKind::Raw; @@ -447,7 +441,7 @@ pub fn block_reward_changeset( .into_iter() .map(|(beneficiary, reward)| -> Result<_, _> { let changeset = db - .basic(B160(beneficiary.0)) + .basic(beneficiary) .map_err(|_| Error::ProviderError)? // if account is present append `Changed` changeset for block reward .map(|acc| { @@ -458,7 +452,7 @@ pub fn block_reward_changeset( }) // if account is not present append `Created` changeset .unwrap_or(AccountInfoChangeSet::Created { - new: Account { nonce: 0, balance: reward.into(), bytecode_hash: None }, + new: Account { nonce: 0, balance: U256::from(reward), bytecode_hash: None }, }); Ok((beneficiary, changeset)) }) @@ -559,17 +553,24 @@ mod tests { // pre staet db.insert_account( H160(hex!("1000000000000000000000000000000000000000")), - Account { balance: 0x00.into(), nonce: 0x00, bytecode_hash: None }, + Account { balance: U256::ZERO, nonce: 0x00, bytecode_hash: None }, Some(hex!("5a465a905090036002900360015500").into()), HashMap::new(), ); - let account3_old_info = - Account { balance: 0x3635c9adc5dea00000u128.into(), nonce: 0x00, bytecode_hash: None }; + let account3_old_info = Account { + balance: U256::from(0x3635c9adc5dea00000u128), + nonce: 0x00, + bytecode_hash: None, + }; db.insert_account( H160(hex!("a94f5374fce5edbc8e2a8697c15331677e6ebf0b")), - Account { balance: 0x3635c9adc5dea00000u128.into(), nonce: 0x00, bytecode_hash: None }, + Account { + balance: U256::from(0x3635c9adc5dea00000u128), + nonce: 0x00, + bytecode_hash: None, + }, None, HashMap::new(), ); @@ -592,17 +593,20 @@ mod tests { assert_eq!(changesets.new_bytecodes.len(), 0, "Should have zero new bytecodes"); let account1 = H160(hex!("1000000000000000000000000000000000000000")); - let _account1_info = Account { balance: 0x00.into(), nonce: 0x00, bytecode_hash: None }; + let _account1_info = Account { balance: U256::ZERO, nonce: 0x00, bytecode_hash: None }; let account2 = H160(hex!("2adc25665018aa1fe0e6bc666dac8fc2697ff9ba")); let account2_info = Account { - balance: (0x1bc16d674ece94bau128 - 0x1bc16d674ec80000u128).into(), /* decrease for - * block reward */ + balance: U256::from(0x1bc16d674ece94bau128 - 0x1bc16d674ec80000u128), /* decrease for + * block reward */ nonce: 0x00, bytecode_hash: None, }; let account3 = H160(hex!("a94f5374fce5edbc8e2a8697c15331677e6ebf0b")); - let account3_info = - Account { balance: 0x3635c9adc5de996b46u128.into(), nonce: 0x01, bytecode_hash: None }; + let account3_info = Account { + balance: U256::from(0x3635c9adc5de996b46u128), + nonce: 0x01, + bytecode_hash: None, + }; assert_eq!( changesets.changeset.get(&account1).unwrap().account, @@ -623,7 +627,8 @@ mod tests { // check block rewards changeset. let mut block_rewarded_acc_info = account2_info; // add Blocks 2 eth reward and 2>>5 for one ommer - block_rewarded_acc_info.balance += (WEI_2ETH + (WEI_2ETH >> 5) * 1).into(); + block_rewarded_acc_info.balance += U256::from(WEI_2ETH + (WEI_2ETH >> 5)); + assert_eq!( out.block_reward, Some(BTreeMap::from([ @@ -639,7 +644,7 @@ mod tests { AccountInfoChangeSet::Created { new: Account { nonce: 0, - balance: ((8 * WEI_2ETH) >> 3).into(), + balance: U256::from((8 * WEI_2ETH) >> 3), bytecode_hash: None } } @@ -653,8 +658,8 @@ mod tests { let storage = &changesets.changeset.get(&account1).unwrap().storage; assert_eq!(storage.len(), 1, "Only one storage change"); assert_eq!( - storage.get(&1.into()), - Some(&(0.into(), 2.into())), + storage.get(&U256::from(1)), + Some(&(U256::ZERO, U256::from(2))), "Storage change from 0 to 2 on slot 1" ); } @@ -664,8 +669,8 @@ mod tests { let db: Arc> = test_utils::create_test_db(EnvKind::RW); let address = H160::zero(); let tx_num = 0; - let acc1 = Account { balance: 1.into(), nonce: 2, bytecode_hash: Some(H256::zero()) }; - let acc2 = Account { balance: 3.into(), nonce: 4, bytecode_hash: Some(H256::zero()) }; + let acc1 = Account { balance: U256::from(1), nonce: 2, bytecode_hash: Some(H256::zero()) }; + let acc2 = Account { balance: U256::from(3), nonce: 4, bytecode_hash: Some(H256::zero()) }; let tx = db.tx_mut().unwrap(); diff --git a/crates/executor/src/revm_wrap.rs b/crates/executor/src/revm_wrap.rs index d2988d392..a35e92048 100644 --- a/crates/executor/src/revm_wrap.rs +++ b/crates/executor/src/revm_wrap.rs @@ -6,7 +6,7 @@ use reth_primitives::{ use reth_provider::StateProvider; use revm::{ db::{CacheDB, DatabaseRef}, - BlockEnv, TransactTo, TxEnv, B160, B256, U256 as evmU256, + BlockEnv, TransactTo, TxEnv, }; /// SubState of database. Uses revm internal cache with binding to reth StateProvider trait. @@ -40,51 +40,50 @@ impl State { impl DatabaseRef for State { type Error = Error; - fn basic(&self, address: B160) -> Result, Self::Error> { - Ok(self.0.basic_account(H160(address.0))?.map(|account| revm::AccountInfo { - balance: evmU256::from_limbs(account.balance.0), + fn basic(&self, address: H160) -> Result, Self::Error> { + Ok(self.0.basic_account(address)?.map(|account| revm::AccountInfo { + balance: account.balance, nonce: account.nonce, - code_hash: B256(account.bytecode_hash.unwrap_or(KECCAK_EMPTY).0), + code_hash: account.bytecode_hash.unwrap_or(KECCAK_EMPTY), code: None, })) } - fn code_by_hash(&self, code_hash: B256) -> Result { - let bytecode = self.0.bytecode_by_hash(H256(code_hash.0))?.unwrap_or_default(); + fn code_by_hash(&self, code_hash: H256) -> Result { + let bytecode = self.0.bytecode_by_hash(code_hash)?.unwrap_or_default(); Ok(revm::Bytecode::new_raw(bytecode.0)) } - fn storage(&self, address: B160, index: evmU256) -> Result { + fn storage(&self, address: H160, index: U256) -> Result { let index = H256(index.to_be_bytes()); - let ret = - evmU256::from_limbs(self.0.storage(H160(address.0), index)?.unwrap_or_default().0); + let ret = self.0.storage(address, index)?.unwrap_or_default(); Ok(ret) } - fn block_hash(&self, number: evmU256) -> Result { - Ok(B256(self.0.block_hash(U256(*number.as_limbs()))?.unwrap_or_default().0)) + fn block_hash(&self, number: U256) -> Result { + Ok(self.0.block_hash(number)?.unwrap_or_default()) } } /// Fill block environment from Block. pub fn fill_block_env(block_env: &mut BlockEnv, header: &Header, after_merge: bool) { - block_env.number = evmU256::from(header.number); - block_env.coinbase = B160(header.beneficiary.0); - block_env.timestamp = evmU256::from(header.timestamp); + block_env.number = U256::from(header.number); + block_env.coinbase = header.beneficiary; + block_env.timestamp = U256::from(header.timestamp); if after_merge { - block_env.prevrandao = Some(B256(header.mix_hash.0)); - block_env.difficulty = evmU256::ZERO; + block_env.prevrandao = Some(header.mix_hash); + block_env.difficulty = U256::ZERO; } else { - block_env.difficulty = evmU256::from_limbs(header.difficulty.0); + block_env.difficulty = header.difficulty; block_env.prevrandao = None; } - block_env.basefee = evmU256::from(header.base_fee_per_gas.unwrap_or_default()); - block_env.gas_limit = evmU256::from(header.gas_limit); + block_env.basefee = U256::from(header.base_fee_per_gas.unwrap_or_default()); + block_env.gas_limit = U256::from(header.gas_limit); } /// Fill transaction environment from Transaction. pub fn fill_tx_env(tx_env: &mut TxEnv, transaction: &TransactionSignedEcRecovered) { - tx_env.caller = B160(transaction.signer().0); + tx_env.caller = transaction.signer(); match transaction.as_ref().as_ref() { Transaction::Legacy(TxLegacy { nonce, @@ -96,13 +95,13 @@ pub fn fill_tx_env(tx_env: &mut TxEnv, transaction: &TransactionSignedEcRecovere input, }) => { tx_env.gas_limit = *gas_limit; - tx_env.gas_price = evmU256::from(*gas_price); + tx_env.gas_price = U256::from(*gas_price); tx_env.gas_priority_fee = None; tx_env.transact_to = match to { - TransactionKind::Call(to) => TransactTo::Call(B160(to.0)), + TransactionKind::Call(to) => TransactTo::Call(*to), TransactionKind::Create => TransactTo::create(), }; - tx_env.value = evmU256::from(*value); + tx_env.value = U256::from(*value); tx_env.data = input.0.clone(); tx_env.chain_id = *chain_id; tx_env.nonce = Some(*nonce); @@ -118,13 +117,13 @@ pub fn fill_tx_env(tx_env: &mut TxEnv, transaction: &TransactionSignedEcRecovere access_list, }) => { tx_env.gas_limit = *gas_limit; - tx_env.gas_price = evmU256::from(*gas_price); + tx_env.gas_price = U256::from(*gas_price); tx_env.gas_priority_fee = None; tx_env.transact_to = match to { - TransactionKind::Call(to) => TransactTo::Call(B160(to.0)), + TransactionKind::Call(to) => TransactTo::Call(*to), TransactionKind::Create => TransactTo::create(), }; - tx_env.value = evmU256::from(*value); + tx_env.value = U256::from(*value); tx_env.data = input.0.clone(); tx_env.chain_id = Some(*chain_id); tx_env.nonce = Some(*nonce); @@ -133,10 +132,10 @@ pub fn fill_tx_env(tx_env: &mut TxEnv, transaction: &TransactionSignedEcRecovere .iter() .map(|l| { ( - B160(l.address.0), + l.address, l.storage_keys .iter() - .map(|k| evmU256::from_be_bytes(k.to_fixed_bytes())) + .map(|k| U256::from_be_bytes(k.to_fixed_bytes())) .collect(), ) }) @@ -154,13 +153,13 @@ pub fn fill_tx_env(tx_env: &mut TxEnv, transaction: &TransactionSignedEcRecovere access_list, }) => { tx_env.gas_limit = *gas_limit; - tx_env.gas_price = evmU256::from(*max_fee_per_gas); - tx_env.gas_priority_fee = Some(evmU256::from(*max_priority_fee_per_gas)); + tx_env.gas_price = U256::from(*max_fee_per_gas); + tx_env.gas_priority_fee = Some(U256::from(*max_priority_fee_per_gas)); tx_env.transact_to = match to { - TransactionKind::Call(to) => TransactTo::Call(B160(to.0)), + TransactionKind::Call(to) => TransactTo::Call(*to), TransactionKind::Create => TransactTo::create(), }; - tx_env.value = evmU256::from(*value); + tx_env.value = U256::from(*value); tx_env.data = input.0.clone(); tx_env.chain_id = Some(*chain_id); tx_env.nonce = Some(*nonce); @@ -169,10 +168,10 @@ pub fn fill_tx_env(tx_env: &mut TxEnv, transaction: &TransactionSignedEcRecovere .iter() .map(|l| { ( - B160(l.address.0), + l.address, l.storage_keys .iter() - .map(|k| evmU256::from_be_bytes(k.to_fixed_bytes())) + .map(|k| U256::from_be_bytes(k.to_fixed_bytes())) .collect(), ) }) @@ -196,9 +195,9 @@ pub fn is_log_equal(revm_log: &revm::Log, reth_log: &reth_primitives::Log) -> bo /// Create reth primitive [Account] from [revm::AccountInfo]. /// Check if revm bytecode hash is [KECCAK_EMPTY] and put None to reth [Account] pub fn to_reth_acc(revm_acc: &revm::AccountInfo) -> Account { - let code_hash = H256(revm_acc.code_hash.0); + let code_hash = revm_acc.code_hash; Account { - balance: U256(*revm_acc.balance.as_limbs()), + balance: revm_acc.balance, nonce: revm_acc.nonce, bytecode_hash: if code_hash == KECCAK_EMPTY { None } else { Some(code_hash) }, } diff --git a/crates/interfaces/src/test_utils/generators.rs b/crates/interfaces/src/test_utils/generators.rs index 527d425d8..1a88b3b42 100644 --- a/crates/interfaces/src/test_utils/generators.rs +++ b/crates/interfaces/src/test_utils/generators.rs @@ -80,8 +80,8 @@ pub fn sign_message(secret: H256, message: H256) -> Result::new(aes_secret.as_ref().into(), iv.as_ref().into())); + Some(Ctr64BE::::new(aes_secret.0.as_ref().into(), iv.as_ref().into())); self.egress_aes = - Some(Ctr64BE::::new(aes_secret.as_ref().into(), iv.as_ref().into())); + Some(Ctr64BE::::new(aes_secret.0.as_ref().into(), iv.as_ref().into())); let mac_secret: H256 = { let mut hasher = Keccak256::new(); - hasher.update(self.ephemeral_shared_secret.unwrap().as_ref()); - hasher.update(aes_secret.as_ref()); + hasher.update(self.ephemeral_shared_secret.unwrap().0.as_ref()); + hasher.update(aes_secret.0.as_ref()); H256::from(hasher.finalize().as_ref()) }; self.ingress_mac = Some(MAC::new(mac_secret)); diff --git a/crates/net/eth-wire/src/ethstream.rs b/crates/net/eth-wire/src/ethstream.rs index 19c24a2c7..c2ae998be 100644 --- a/crates/net/eth-wire/src/ethstream.rs +++ b/crates/net/eth-wire/src/ethstream.rs @@ -272,7 +272,7 @@ mod tests { let status = Status { version: EthVersion::Eth67 as u8, chain: Chain::Mainnet.into(), - total_difficulty: U256::from(0), + total_difficulty: U256::ZERO, blockhash: H256::random(), genesis, // Pass the current fork id. @@ -406,7 +406,7 @@ mod tests { let status = Status { version: EthVersion::Eth67 as u8, chain: Chain::Mainnet.into(), - total_difficulty: U256::from(0), + total_difficulty: U256::ZERO, blockhash: H256::random(), genesis, // Pass the current fork id. diff --git a/crates/net/eth-wire/src/types/blocks.rs b/crates/net/eth-wire/src/types/blocks.rs index dc60c2cf0..2ebe51b68 100644 --- a/crates/net/eth-wire/src/types/blocks.rs +++ b/crates/net/eth-wire/src/types/blocks.rs @@ -287,7 +287,7 @@ mod test { transactions_root: hex!("0000000000000000000000000000000000000000000000000000000000000000").into(), receipts_root: hex!("0000000000000000000000000000000000000000000000000000000000000000").into(), logs_bloom: hex!("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").into(), - difficulty: 0x8aeu64.into(), + difficulty: U256::from(0x8aeu64), number: 0xd05u64, gas_limit: 0x115cu64, gas_used: 0x15b3u64, @@ -317,7 +317,7 @@ mod test { transactions_root: hex!("0000000000000000000000000000000000000000000000000000000000000000").into(), receipts_root: hex!("0000000000000000000000000000000000000000000000000000000000000000").into(), logs_bloom: hex!("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").into(), - difficulty: 0x8aeu64.into(), + difficulty: U256::from(0x8aeu64), number: 0xd05u64, gas_limit: 0x115cu64, gas_used: 0x15b3u64, @@ -389,9 +389,9 @@ mod test { Signature { odd_y_parity: false, r: - U256::from_str("64b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12").unwrap(), + U256::from_str("0x64b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12").unwrap(), s: - U256::from_str("64b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10").unwrap(), + U256::from_str("0x64b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10").unwrap(), } ), TransactionSigned::from_transaction_and_signature(Transaction::Legacy(TxLegacy { @@ -406,9 +406,9 @@ mod test { }), Signature { odd_y_parity: false, r: - U256::from_str("52f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb").unwrap(), + U256::from_str("0x52f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb").unwrap(), s: - U256::from_str("52f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb").unwrap(), + U256::from_str("0x52f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb").unwrap(), }, ), ], @@ -427,7 +427,7 @@ mod test { hex!("0000000000000000000000000000000000000000000000000000000000000000").into(), logs_bloom: hex!("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - ).into(), difficulty: 0x8aeu64.into(), + ).into(), difficulty: U256::from(0x8aeu64), number: 0xd05u64, gas_limit: 0x115cu64, gas_used: 0x15b3u64, @@ -470,9 +470,9 @@ mod test { Signature { odd_y_parity: false, r: - U256::from_str("64b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12").unwrap(), + U256::from_str("0x64b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12").unwrap(), s: - U256::from_str("64b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10").unwrap(), + U256::from_str("0x64b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10").unwrap(), } ), TransactionSigned::from_transaction_and_signature(Transaction::Legacy(TxLegacy { @@ -488,9 +488,9 @@ mod test { Signature { odd_y_parity: false, r: - U256::from_str("52f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb").unwrap(), + U256::from_str("0x52f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb").unwrap(), s: - U256::from_str("52f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb").unwrap(), + U256::from_str("0x52f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb").unwrap(), }, ), ], @@ -509,7 +509,7 @@ mod test { hex!("0000000000000000000000000000000000000000000000000000000000000000").into(), logs_bloom: hex!("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - ).into(), difficulty: 0x8aeu64.into(), + ).into(), difficulty: U256::from(0x8aeu64), number: 0xd05u64, gas_limit: 0x115cu64, gas_used: 0x15b3u64, diff --git a/crates/net/eth-wire/src/types/status.rs b/crates/net/eth-wire/src/types/status.rs index aca87a995..799f56e34 100644 --- a/crates/net/eth-wire/src/types/status.rs +++ b/crates/net/eth-wire/src/types/status.rs @@ -97,7 +97,7 @@ impl Default for Status { Status { version: EthVersion::Eth67 as u8, chain: Chain::Named(ethers_core::types::Chain::Mainnet), - total_difficulty: 17_179_869_184u64.into(), + total_difficulty: U256::from(17_179_869_184u64), blockhash: MAINNET_GENESIS, genesis: MAINNET_GENESIS, forkid: Hardfork::Frontier.fork_id(), diff --git a/crates/net/eth-wire/src/types/transactions.rs b/crates/net/eth-wire/src/types/transactions.rs index 61b19bda2..6e06369bb 100644 --- a/crates/net/eth-wire/src/types/transactions.rs +++ b/crates/net/eth-wire/src/types/transactions.rs @@ -130,11 +130,11 @@ mod test { Signature { odd_y_parity: false, r: U256::from_str( - "64b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12", + "0x64b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12", ) .unwrap(), s: U256::from_str( - "64b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10", + "0x64b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10", ) .unwrap(), }, @@ -154,11 +154,11 @@ mod test { Signature { odd_y_parity: false, r: U256::from_str( - "52f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", + "0x52f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", ) .unwrap(), s: U256::from_str( - "52f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", + "0x52f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", ) .unwrap(), }, @@ -192,11 +192,11 @@ mod test { Signature { odd_y_parity: false, r: U256::from_str( - "64b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12", + "0x64b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12", ) .unwrap(), s: U256::from_str( - "64b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10", + "0x64b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10", ) .unwrap(), }, @@ -216,11 +216,11 @@ mod test { Signature { odd_y_parity: false, r: U256::from_str( - "52f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", + "0x52f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", ) .unwrap(), s: U256::from_str( - "52f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", + "0x52f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", ) .unwrap(), }, @@ -257,11 +257,11 @@ mod test { Signature { odd_y_parity: true, r: U256::from_str( - "35b7bfeb9ad9ece2cbafaaf8e202e706b4cfaeb233f46198f00b44d4a566a981", + "0x35b7bfeb9ad9ece2cbafaaf8e202e706b4cfaeb233f46198f00b44d4a566a981", ) .unwrap(), s: U256::from_str( - "612638fb29427ca33b9a3be2a0a561beecfe0269655be160d35e72d366a6a860", + "0x612638fb29427ca33b9a3be2a0a561beecfe0269655be160d35e72d366a6a860", ) .unwrap(), }, @@ -283,11 +283,11 @@ mod test { Signature { odd_y_parity: true, r: U256::from_str( - "59e6b67f48fb32e7e570dfb11e042b5ad2e55e3ce3ce9cd989c7e06e07feeafd", + "0x59e6b67f48fb32e7e570dfb11e042b5ad2e55e3ce3ce9cd989c7e06e07feeafd", ) .unwrap(), s: U256::from_str( - "016b83f4f980694ed2eee4d10667242b1f40dc406901b34125b008d334d47469", + "0x016b83f4f980694ed2eee4d10667242b1f40dc406901b34125b008d334d47469", ) .unwrap(), }, @@ -307,11 +307,11 @@ mod test { Signature { odd_y_parity: false, r: U256::from_str( - "ce6834447c0a4193c40382e6c57ae33b241379c5418caac9cdc18d786fd12071", + "0xce6834447c0a4193c40382e6c57ae33b241379c5418caac9cdc18d786fd12071", ) .unwrap(), s: U256::from_str( - "3ca3ae86580e94550d7c071e3a02eadb5a77830947c9225165cf9100901bee88", + "0x3ca3ae86580e94550d7c071e3a02eadb5a77830947c9225165cf9100901bee88", ) .unwrap(), }, @@ -331,11 +331,11 @@ mod test { Signature { odd_y_parity: false, r: U256::from_str( - "e24d8bd32ad906d6f8b8d7741e08d1959df021698b19ee232feba15361587d0a", + "0xe24d8bd32ad906d6f8b8d7741e08d1959df021698b19ee232feba15361587d0a", ) .unwrap(), s: U256::from_str( - "5406ad177223213df262cb66ccbb2f46bfdccfdfbbb5ffdda9e2c02d977631da", + "0x5406ad177223213df262cb66ccbb2f46bfdccfdfbbb5ffdda9e2c02d977631da", ) .unwrap(), }, @@ -355,11 +355,11 @@ mod test { Signature { odd_y_parity: false, r: U256::from_str( - "eb96ca19e8a77102767a41fc85a36afd5c61ccb09911cec5d3e86e193d9c5ae", + "0xeb96ca19e8a77102767a41fc85a36afd5c61ccb09911cec5d3e86e193d9c5ae", ) .unwrap(), s: U256::from_str( - "3a456401896b1b6055311536bf00a718568c744d8c1f9df59879e8350220ca18", + "0x3a456401896b1b6055311536bf00a718568c744d8c1f9df59879e8350220ca18", ) .unwrap(), }, @@ -400,11 +400,11 @@ mod test { Signature { odd_y_parity: true, r: U256::from_str( - "35b7bfeb9ad9ece2cbafaaf8e202e706b4cfaeb233f46198f00b44d4a566a981", + "0x35b7bfeb9ad9ece2cbafaaf8e202e706b4cfaeb233f46198f00b44d4a566a981", ) .unwrap(), s: U256::from_str( - "612638fb29427ca33b9a3be2a0a561beecfe0269655be160d35e72d366a6a860", + "0x612638fb29427ca33b9a3be2a0a561beecfe0269655be160d35e72d366a6a860", ) .unwrap(), }, @@ -426,11 +426,11 @@ mod test { Signature { odd_y_parity: true, r: U256::from_str( - "59e6b67f48fb32e7e570dfb11e042b5ad2e55e3ce3ce9cd989c7e06e07feeafd", + "0x59e6b67f48fb32e7e570dfb11e042b5ad2e55e3ce3ce9cd989c7e06e07feeafd", ) .unwrap(), s: U256::from_str( - "016b83f4f980694ed2eee4d10667242b1f40dc406901b34125b008d334d47469", + "0x016b83f4f980694ed2eee4d10667242b1f40dc406901b34125b008d334d47469", ) .unwrap(), }, @@ -450,11 +450,11 @@ mod test { Signature { odd_y_parity: false, r: U256::from_str( - "ce6834447c0a4193c40382e6c57ae33b241379c5418caac9cdc18d786fd12071", + "0xce6834447c0a4193c40382e6c57ae33b241379c5418caac9cdc18d786fd12071", ) .unwrap(), s: U256::from_str( - "3ca3ae86580e94550d7c071e3a02eadb5a77830947c9225165cf9100901bee88", + "0x3ca3ae86580e94550d7c071e3a02eadb5a77830947c9225165cf9100901bee88", ) .unwrap(), }, @@ -474,11 +474,11 @@ mod test { Signature { odd_y_parity: false, r: U256::from_str( - "e24d8bd32ad906d6f8b8d7741e08d1959df021698b19ee232feba15361587d0a", + "0xe24d8bd32ad906d6f8b8d7741e08d1959df021698b19ee232feba15361587d0a", ) .unwrap(), s: U256::from_str( - "5406ad177223213df262cb66ccbb2f46bfdccfdfbbb5ffdda9e2c02d977631da", + "0x5406ad177223213df262cb66ccbb2f46bfdccfdfbbb5ffdda9e2c02d977631da", ) .unwrap(), }, @@ -498,11 +498,11 @@ mod test { Signature { odd_y_parity: false, r: U256::from_str( - "eb96ca19e8a77102767a41fc85a36afd5c61ccb09911cec5d3e86e193d9c5ae", + "0xeb96ca19e8a77102767a41fc85a36afd5c61ccb09911cec5d3e86e193d9c5ae", ) .unwrap(), s: U256::from_str( - "3a456401896b1b6055311536bf00a718568c744d8c1f9df59879e8350220ca18", + "0x3a456401896b1b6055311536bf00a718568c744d8c1f9df59879e8350220ca18", ) .unwrap(), }, diff --git a/crates/net/network/src/eth_requests.rs b/crates/net/network/src/eth_requests.rs index 4c921a8c4..7fc739abe 100644 --- a/crates/net/network/src/eth_requests.rs +++ b/crates/net/network/src/eth_requests.rs @@ -7,7 +7,7 @@ use reth_eth_wire::{ GetReceipts, NodeData, Receipts, }; use reth_interfaces::p2p::error::RequestResult; -use reth_primitives::{BlockHashOrNumber, Header, HeadersDirection, PeerId}; +use reth_primitives::{rpc, BlockHashOrNumber, Header, HeadersDirection, PeerId, U256}; use reth_provider::{BlockProvider, HeaderProvider}; use std::{ borrow::Borrow, @@ -83,7 +83,7 @@ where let mut block: BlockHashOrNumber = match start_block { BlockHashOrNumber::Hash(start) => start.into(), BlockHashOrNumber::Number(num) => { - if let Some(hash) = self.client.block_hash(num.into()).unwrap_or_default() { + if let Some(hash) = self.client.block_hash(U256::from(num)).unwrap_or_default() { hash.into() } else { return headers @@ -161,7 +161,9 @@ where let mut total_bytes = APPROX_BODY_SIZE; for hash in request.0 { - if let Some(block) = self.client.block(hash.into()).unwrap_or_default() { + if let Some(block) = + self.client.block(rpc::BlockId::Hash(rpc::H256(hash.0))).unwrap_or_default() + { let body = BlockBody { transactions: block.body, ommers: block.ommers }; bodies.push(body); diff --git a/crates/net/rpc-types/src/eth/engine.rs b/crates/net/rpc-types/src/eth/engine.rs index 7b1b8f651..e14082231 100644 --- a/crates/net/rpc-types/src/eth/engine.rs +++ b/crates/net/rpc-types/src/eth/engine.rs @@ -56,7 +56,7 @@ impl From for ExecutionPayload { gas_used: value.gas_used.into(), timestamp: value.timestamp.into(), extra_data: value.extra_data.clone().into(), - base_fee_per_gas: value.base_fee_per_gas.unwrap_or_default().into(), + base_fee_per_gas: U256::from(value.base_fee_per_gas.unwrap_or_default()), block_hash: value.hash(), transactions, withdrawal: None, diff --git a/crates/net/rpc-types/src/eth/transaction/request.rs b/crates/net/rpc-types/src/eth/transaction/request.rs index f84ac9b84..64e12094d 100644 --- a/crates/net/rpc-types/src/eth/transaction/request.rs +++ b/crates/net/rpc-types/src/eth/transaction/request.rs @@ -63,10 +63,10 @@ impl TransactionRequest { // legacy transaction (Some(_), None, None) => { Some(TypedTransactionRequest::Legacy(LegacyTransactionRequest { - nonce: nonce.unwrap_or(U256::zero()), + nonce: nonce.unwrap_or(U256::ZERO), gas_price: gas_price.unwrap_or_default(), gas_limit: gas.unwrap_or_default(), - value: value.unwrap_or(U256::zero()), + value: value.unwrap_or(U256::ZERO), input: data.unwrap_or_default(), kind: match to { Some(to) => TransactionKind::Call(to), @@ -78,10 +78,10 @@ impl TransactionRequest { // EIP2930 (_, None, Some(access_list)) => { Some(TypedTransactionRequest::EIP2930(EIP2930TransactionRequest { - nonce: nonce.unwrap_or(U256::zero()), + nonce: nonce.unwrap_or(U256::ZERO), gas_price: gas_price.unwrap_or_default(), gas_limit: gas.unwrap_or_default(), - value: value.unwrap_or(U256::zero()), + value: value.unwrap_or(U256::ZERO), input: data.unwrap_or_default(), kind: match to { Some(to) => TransactionKind::Call(to), @@ -95,11 +95,11 @@ impl TransactionRequest { (None, Some(_), access_list) | (None, None, access_list @ None) => { // Empty fields fall back to the canonical transaction schema. Some(TypedTransactionRequest::EIP1559(EIP1559TransactionRequest { - nonce: nonce.unwrap_or(U256::zero()), + nonce: nonce.unwrap_or(U256::ZERO), max_fee_per_gas: max_fee_per_gas.unwrap_or_default(), - max_priority_fee_per_gas: max_priority_fee_per_gas.unwrap_or(U256::zero()), + max_priority_fee_per_gas: max_priority_fee_per_gas.unwrap_or(U256::ZERO), gas_limit: gas.unwrap_or_default(), - value: value.unwrap_or(U256::zero()), + value: value.unwrap_or(U256::ZERO), input: data.unwrap_or_default(), kind: match to { Some(to) => TransactionKind::Call(to), diff --git a/crates/net/rpc/src/eth/api/server.rs b/crates/net/rpc/src/eth/api/server.rs index ce5f02f70..1bcff91b8 100644 --- a/crates/net/rpc/src/eth/api/server.rs +++ b/crates/net/rpc/src/eth/api/server.rs @@ -42,10 +42,9 @@ where } fn block_number(&self) -> Result { - Ok(EthApiSpec::chain_info(self) - .with_message("failed to read chain info")? - .best_number - .into()) + Ok(U256::from( + EthApiSpec::chain_info(self).with_message("failed to read chain info")?.best_number, + )) } async fn chain_id(&self) -> Result> { diff --git a/crates/primitives/Cargo.toml b/crates/primitives/Cargo.toml index a63950f36..f5f0b93dc 100644 --- a/crates/primitives/Cargo.toml +++ b/crates/primitives/Cargo.toml @@ -17,6 +17,8 @@ reth-rlp = { path = "../common/rlp", features = [ reth-rlp-derive = { path = "../common/rlp-derive" } reth-codecs = { version = "0.1.0", path = "../storage/codecs" } +revm-interpreter = { git = "https://github.com/bluealloy/revm", rev = "3a13c9c8a0cda728941f1b26db0beb1025744ea9", features = ["with-serde"] } + # ethereum ethers-core = { git = "https://github.com/gakonst/ethers-rs", default-features = false } parity-scale-codec = { version = "3.2.1", features = ["derive", "bytes"] } @@ -58,6 +60,8 @@ serde_json = "1.0" hex-literal = "0.3" test-fuzz = "3.0.4" rand = "0.8" +revm-interpreter = { git = "https://github.com/bluealloy/revm", rev = "3a13c9c8a0cda728941f1b26db0beb1025744ea9", features = ["with-serde", "arbitrary"] } + # necessary so we don't hit a "undeclared 'std'": # https://github.com/paradigmxyz/reth/pull/177#discussion_r1021172198 diff --git a/crates/primitives/src/account.rs b/crates/primitives/src/account.rs index f78781243..6d96a2c51 100644 --- a/crates/primitives/src/account.rs +++ b/crates/primitives/src/account.rs @@ -22,7 +22,7 @@ impl Account { #[cfg(test)] mod tests { - use crate::Account; + use crate::{Account, U256}; use reth_codecs::Compact; #[test] @@ -32,7 +32,7 @@ mod tests { let len = acc.to_compact(&mut buf); assert_eq!(len, 2); - acc.balance = 2.into(); + acc.balance = U256::from(2); let len = acc.to_compact(&mut buf); assert_eq!(len, 3); diff --git a/crates/primitives/src/bloom.rs b/crates/primitives/src/bloom.rs index 48f2ec56c..d26f737ce 100644 --- a/crates/primitives/src/bloom.rs +++ b/crates/primitives/src/bloom.rs @@ -8,7 +8,7 @@ pub const BLOOM_BYTE_LENGTH: usize = 256; // See Section 4.3.1 "Transaction Receipt" of the Yellow Paper fn m3_2048(bloom: &mut Bloom, x: &[u8]) { let hash = keccak256(x); - let h = hash.as_ref(); + let h: &[u8; 32] = hash.as_ref(); for i in [0, 2, 4] { let bit = (h[i + 1] as usize + ((h[i] as usize) << 8)) & 0x7FF; bloom.0[BLOOM_BYTE_LENGTH - 1 - bit / 8] |= 1 << (bit % 8); diff --git a/crates/primitives/src/chain.rs b/crates/primitives/src/chain.rs index 8be1ecf44..99a9e015e 100644 --- a/crates/primitives/src/chain.rs +++ b/crates/primitives/src/chain.rs @@ -61,7 +61,7 @@ impl From for Chain { impl From for Chain { fn from(id: U256) -> Self { - id.as_u64().into() + id.to::().into() } } @@ -82,7 +82,7 @@ impl From for U64 { impl From for U256 { fn from(c: Chain) -> Self { - u64::from(c).into() + U256::from(u64::from(c)) } } diff --git a/crates/primitives/src/header.rs b/crates/primitives/src/header.rs index 2aa9f1574..4b56c8487 100644 --- a/crates/primitives/src/header.rs +++ b/crates/primitives/src/header.rs @@ -183,9 +183,9 @@ impl Decodable for Header { receipts_root: Decodable::decode(buf)?, logs_bloom: Decodable::decode(buf)?, difficulty: Decodable::decode(buf)?, - number: U256::decode(buf)?.as_u64(), - gas_limit: U256::decode(buf)?.as_u64(), - gas_used: U256::decode(buf)?.as_u64(), + number: U256::decode(buf)?.to::(), + gas_limit: U256::decode(buf)?.to::(), + gas_used: U256::decode(buf)?.to::(), timestamp: Decodable::decode(buf)?, extra_data: Decodable::decode(buf)?, mix_hash: Decodable::decode(buf)?, @@ -194,7 +194,7 @@ impl Decodable for Header { }; let consumed = started_len - buf.len(); if consumed < rlp_head.payload_length { - this.base_fee_per_gas = Some(U256::decode(buf)?.as_u64()); + this.base_fee_per_gas = Some(U256::decode(buf)?.to::()); } let consumed = started_len - buf.len(); if consumed != rlp_head.payload_length { @@ -356,7 +356,7 @@ impl From for bool { #[cfg(test)] mod tests { use super::{Decodable, Encodable, Header, H256}; - use crate::Address; + use crate::{Address, U256}; use ethers_core::{ types::Bytes, utils::hex::{self, FromHex}, @@ -369,7 +369,7 @@ mod tests { fn test_encode_block_header() { let expected = hex::decode("f901f9a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000940000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008208ae820d0582115c8215b3821a0a827788a00000000000000000000000000000000000000000000000000000000000000000880000000000000000").unwrap(); let header = Header { - difficulty: 0x8ae_u64.into(), + difficulty: U256::from(0x8ae_u64), number: 0xd05_u64, gas_limit: 0x115c_u64, gas_used: 0x15b3_u64, @@ -401,7 +401,7 @@ mod tests { transactions_root: H256::from_str("50f738580ed699f0469702c7ccc63ed2e51bc034be9479b7bff4e68dee84accf").unwrap(), receipts_root: H256::from_str("29b0562f7140574dd0d50dee8a271b22e1a0a7b78fca58f7c60370d8317ba2a9").unwrap(), logs_bloom: <[u8; 256]>::from_hex("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap().into(), - difficulty: 0x020000.into(), + difficulty: U256::from(0x020000), number: 0x01_u64, gas_limit: 0x016345785d8a0000_u64, gas_used: 0x015534_u64, @@ -419,7 +419,7 @@ mod tests { fn test_decode_block_header() { let data = hex::decode("f901f9a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000940000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008208ae820d0582115c8215b3821a0a827788a00000000000000000000000000000000000000000000000000000000000000000880000000000000000").unwrap(); let expected = Header { - difficulty: 0x8aeu64.into(), + difficulty: U256::from(0x8aeu64), number: 0xd05u64, gas_limit: 0x115cu64, gas_used: 0x15b3u64, diff --git a/crates/primitives/src/jsonu256.rs b/crates/primitives/src/jsonu256.rs index 6b21a78e8..acc609552 100644 --- a/crates/primitives/src/jsonu256.rs +++ b/crates/primitives/src/jsonu256.rs @@ -48,12 +48,12 @@ impl<'a> Visitor<'a> for JsonU256Visitor { E: Error, { let value = match value.len() { - 0 => U256::from(0), - 2 if value.starts_with("0x") => U256::zero(), - _ if value.starts_with("0x") => U256::from_str(&value[2..]).map_err(|e| { + 0 => U256::ZERO, + 2 if value.starts_with("0x") => U256::ZERO, + _ if value.starts_with("0x") => U256::from_str(value).map_err(|e| { Error::custom(format!("Parsing JsonU256 as hex failed {value}: {e}")) })?, - _ => U256::from_dec_str(value).map_err(|e| { + _ => U256::from_str_radix(value, 10).map_err(|e| { Error::custom(format!("Parsing JsonU256 as decimal failed {value}: {e:?}")) })?, }; @@ -81,9 +81,9 @@ mod test { assert_eq!( deserialized, vec![ - JsonU256(U256::from(0)), - JsonU256(U256::from(0)), - JsonU256(U256::from(0)), + JsonU256(U256::ZERO), + JsonU256(U256::ZERO), + JsonU256(U256::ZERO), JsonU256(U256::from(10)), JsonU256(U256::from(10)), JsonU256(U256::from(16)), diff --git a/crates/primitives/src/lib.rs b/crates/primitives/src/lib.rs index 0a6369fb4..bd91a80f1 100644 --- a/crates/primitives/src/lib.rs +++ b/crates/primitives/src/lib.rs @@ -77,8 +77,9 @@ pub type TransitionId = u64; pub use ethers_core::{ types as rpc, - types::{BigEndianHash, H128, H160, H256, H512, H64, U128, U256, U64}, + types::{BigEndianHash, H128, H512, H64, U128, U64}, }; +pub use revm_interpreter::{B160 as H160, B256 as H256, U256}; #[doc(hidden)] mod __reexport { diff --git a/crates/primitives/src/transaction/mod.rs b/crates/primitives/src/transaction/mod.rs index 9c334745f..3ed11ea7d 100644 --- a/crates/primitives/src/transaction/mod.rs +++ b/crates/primitives/src/transaction/mod.rs @@ -927,9 +927,9 @@ mod tests { }); let expected_signature = Signature { odd_y_parity: false, - r: U256::from_str("eb96ca19e8a77102767a41fc85a36afd5c61ccb09911cec5d3e86e193d9c5ae") + r: U256::from_str("0xeb96ca19e8a77102767a41fc85a36afd5c61ccb09911cec5d3e86e193d9c5ae") .unwrap(), - s: U256::from_str("3a456401896b1b6055311536bf00a718568c744d8c1f9df59879e8350220ca18") + s: U256::from_str("0x3a456401896b1b6055311536bf00a718568c744d8c1f9df59879e8350220ca18") .unwrap(), }; let expected = @@ -955,9 +955,9 @@ mod tests { }); let expected_signature = Signature { odd_y_parity: false, - r: U256::from_str("e24d8bd32ad906d6f8b8d7741e08d1959df021698b19ee232feba15361587d0a") + r: U256::from_str("0xe24d8bd32ad906d6f8b8d7741e08d1959df021698b19ee232feba15361587d0a") .unwrap(), - s: U256::from_str("5406ad177223213df262cb66ccbb2f46bfdccfdfbbb5ffdda9e2c02d977631da") + s: U256::from_str("0x5406ad177223213df262cb66ccbb2f46bfdccfdfbbb5ffdda9e2c02d977631da") .unwrap(), }; @@ -980,9 +980,9 @@ mod tests { let expected_signature = Signature { odd_y_parity: false, - r: U256::from_str("ce6834447c0a4193c40382e6c57ae33b241379c5418caac9cdc18d786fd12071") + r: U256::from_str("0xce6834447c0a4193c40382e6c57ae33b241379c5418caac9cdc18d786fd12071") .unwrap(), - s: U256::from_str("3ca3ae86580e94550d7c071e3a02eadb5a77830947c9225165cf9100901bee88") + s: U256::from_str("0x3ca3ae86580e94550d7c071e3a02eadb5a77830947c9225165cf9100901bee88") .unwrap(), }; @@ -1007,9 +1007,9 @@ mod tests { let expected_signature = Signature { odd_y_parity: true, - r: U256::from_str("59e6b67f48fb32e7e570dfb11e042b5ad2e55e3ce3ce9cd989c7e06e07feeafd") + r: U256::from_str("0x59e6b67f48fb32e7e570dfb11e042b5ad2e55e3ce3ce9cd989c7e06e07feeafd") .unwrap(), - s: U256::from_str("016b83f4f980694ed2eee4d10667242b1f40dc406901b34125b008d334d47469") + s: U256::from_str("0x016b83f4f980694ed2eee4d10667242b1f40dc406901b34125b008d334d47469") .unwrap(), }; @@ -1031,9 +1031,9 @@ mod tests { }); let signature = Signature { odd_y_parity: true, - r: U256::from_str("35b7bfeb9ad9ece2cbafaaf8e202e706b4cfaeb233f46198f00b44d4a566a981") + r: U256::from_str("0x35b7bfeb9ad9ece2cbafaaf8e202e706b4cfaeb233f46198f00b44d4a566a981") .unwrap(), - s: U256::from_str("612638fb29427ca33b9a3be2a0a561beecfe0269655be160d35e72d366a6a860") + s: U256::from_str("0x612638fb29427ca33b9a3be2a0a561beecfe0269655be160d35e72d366a6a860") .unwrap(), }; @@ -1076,8 +1076,12 @@ mod tests { }); let sig = Signature { - r: hex!("2a378831cf81d99a3f06a18ae1b6ca366817ab4d88a70053c41d7a8f0368e031").into(), - s: hex!("450d831a05b6e418724436c05c155e0a1b7b921015d0fbc2f667aed709ac4fb5").into(), + r: U256::from_be_bytes(hex!( + "2a378831cf81d99a3f06a18ae1b6ca366817ab4d88a70053c41d7a8f0368e031" + )), + s: U256::from_be_bytes(hex!( + "450d831a05b6e418724436c05c155e0a1b7b921015d0fbc2f667aed709ac4fb5" + )), odd_y_parity: false, }; @@ -1107,8 +1111,10 @@ mod tests { }); let sig = Signature { - r: hex!("840cfc572845f5786e702984c2a582528cad4b49b2a10b9db1be7fca90058565").into(), - s: hex!("25e7109ceb98168d95b09b18bbf6b685130e0562f233877d492b94eee0c5b6d1").into(), + r: U256::from_str("0x840cfc572845f5786e702984c2a582528cad4b49b2a10b9db1be7fca90058565") + .unwrap(), + s: U256::from_str("0x25e7109ceb98168d95b09b18bbf6b685130e0562f233877d492b94eee0c5b6d1") + .unwrap(), odd_y_parity: false, }; diff --git a/crates/primitives/src/transaction/signature.rs b/crates/primitives/src/transaction/signature.rs index ac6e22401..431c50a54 100644 --- a/crates/primitives/src/transaction/signature.rs +++ b/crates/primitives/src/transaction/signature.rs @@ -72,8 +72,8 @@ impl Signature { pub(crate) fn recover_signer(&self, hash: H256) -> Option
{ let mut sig: [u8; 65] = [0; 65]; - self.r.to_big_endian(&mut sig[0..32]); - self.s.to_big_endian(&mut sig[32..64]); + sig[0..32].copy_from_slice(&self.r.to_be_bytes::<32>()); + sig[32..64].copy_from_slice(&self.s.to_be_bytes::<32>()); sig[64] = self.odd_y_parity as u8; // NOTE: we are removing error from underlying crypto library as it will restrain primitive diff --git a/crates/stages/src/stages/execution.rs b/crates/stages/src/stages/execution.rs index ea783aa8f..ba7e84ce8 100644 --- a/crates/stages/src/stages/execution.rs +++ b/crates/stages/src/stages/execution.rs @@ -57,7 +57,9 @@ pub struct ExecutionStage { impl Default for ExecutionStage { fn default() -> Self { - Self { config: Config { chain_id: 1.into(), spec_upgrades: SpecUpgrades::new_ethereum() } } + Self { + config: Config { chain_id: U256::from(1), spec_upgrades: SpecUpgrades::new_ethereum() }, + } } } @@ -234,8 +236,7 @@ impl Stage for ExecutionStage { // insert storage changeset let storage_id = TransitionIdAddress((current_transition_id, address)); for (key, (old_value, new_value)) in storage { - let mut hkey = H256::zero(); - key.to_big_endian(&mut hkey.0); + let hkey = H256(key.to_be_bytes()); trace!(target: "sync::stages::execution", ?address, current_transition_id, ?hkey, ?old_value, ?new_value, "Applying storage changeset"); @@ -254,7 +255,7 @@ impl Stage for ExecutionStage { address, Some(StorageEntry { key: hkey, value: old_value }), )?; - if !new_value.is_zero() { + if new_value != U256::ZERO { tx.put::( address, StorageEntry { key: hkey, value: new_value }, @@ -357,7 +358,7 @@ impl Stage for ExecutionStage { for (key, storage) in storage_chageset_batch.into_iter().rev() { let address = key.address(); tx.put::(address, storage.clone())?; - if storage.value == U256::zero() { + if storage.value == U256::ZERO { // delete value that is zero tx.delete::(address, Some(storage))?; } @@ -425,7 +426,7 @@ mod tests { db_tx .put::( acc1, - Account { nonce: 0, balance: 0.into(), bytecode_hash: Some(code_hash) }, + Account { nonce: 0, balance: U256::ZERO, bytecode_hash: Some(code_hash) }, ) .unwrap(); db_tx @@ -447,13 +448,19 @@ mod tests { // check post state let account1 = H160(hex!("1000000000000000000000000000000000000000")); let account1_info = - Account { balance: 0x00.into(), nonce: 0x00, bytecode_hash: Some(code_hash) }; + Account { balance: U256::ZERO, nonce: 0x00, bytecode_hash: Some(code_hash) }; let account2 = H160(hex!("2adc25665018aa1fe0e6bc666dac8fc2697ff9ba")); - let account2_info = - Account { balance: (0x1bc16d674ece94bau128).into(), nonce: 0x00, bytecode_hash: None }; + let account2_info = Account { + balance: U256::from(0x1bc16d674ece94bau128), + nonce: 0x00, + bytecode_hash: None, + }; let account3 = H160(hex!("a94f5374fce5edbc8e2a8697c15331677e6ebf0b")); - let account3_info = - Account { balance: 0x3635c9adc5de996b46u128.into(), nonce: 0x01, bytecode_hash: None }; + let account3_info = Account { + balance: U256::from(0x3635c9adc5de996b46u128), + nonce: 0x01, + bytecode_hash: None, + }; // assert accounts assert_eq!( @@ -475,7 +482,7 @@ mod tests { // Get on dupsort would return only first value. This is good enought for this test. assert_eq!( tx.get::(account1), - Ok(Some(StorageEntry { key: H256::from_low_u64_be(1), value: 2.into() })), + Ok(Some(StorageEntry { key: H256::from_low_u64_be(1), value: U256::from(2) })), "Post changed of a account" ); } @@ -507,7 +514,7 @@ mod tests { // pre state let db_tx = tx.deref_mut(); let acc1 = H160(hex!("1000000000000000000000000000000000000000")); - let acc1_info = Account { nonce: 0, balance: 0.into(), bytecode_hash: Some(code_hash) }; + let acc1_info = Account { nonce: 0, balance: U256::ZERO, bytecode_hash: Some(code_hash) }; let acc2 = H160(hex!("a94f5374fce5edbc8e2a8697c15331677e6ebf0b")); let acc2_info = Account { nonce: 0, balance, bytecode_hash: None }; diff --git a/crates/stages/src/stages/headers.rs b/crates/stages/src/stages/headers.rs index b092a7ac8..6046a206f 100644 --- a/crates/stages/src/stages/headers.rs +++ b/crates/stages/src/stages/headers.rs @@ -506,7 +506,7 @@ mod tests { self.tx.insert_headers(std::iter::once(&head))?; // patch td table for `update_head` call self.tx.commit(|tx| { - tx.put::(head.num_hash().into(), U256::zero().into()) + tx.put::(head.num_hash().into(), U256::ZERO.into()) })?; // use previous progress as seed size diff --git a/crates/storage/codecs/Cargo.toml b/crates/storage/codecs/Cargo.toml index 873743b37..9266be23d 100644 --- a/crates/storage/codecs/Cargo.toml +++ b/crates/storage/codecs/Cargo.toml @@ -17,6 +17,7 @@ no_codec = ["codecs-derive/no_codec"] bytes = "1.2.1" codecs-derive = { version = "0.1.0", path = "./derive", default-features = false } ethers-core = { git = "https://github.com/gakonst/ethers-rs", default-features = false } +revm-interpreter = { git = "https://github.com/bluealloy/revm", rev = "3a13c9c8a0cda728941f1b26db0beb1025744ea9", features = ["with-serde"] } [dev-dependencies] serde = "1.0" diff --git a/crates/storage/codecs/src/lib.rs b/crates/storage/codecs/src/lib.rs index 6deb90a83..082fd7eee 100644 --- a/crates/storage/codecs/src/lib.rs +++ b/crates/storage/codecs/src/lib.rs @@ -1,6 +1,7 @@ use bytes::{Buf, Bytes}; pub use codecs_derive::*; -use ethers_core::types::{Bloom, H160, H256, U256}; +use ethers_core::types::Bloom; +use revm_interpreter::{B160 as H160, B256 as H256, U256}; /// Trait that implements the `Compact` codec. /// @@ -188,9 +189,8 @@ where impl Compact for U256 { fn to_compact(self, buf: &mut impl bytes::BufMut) -> usize { - let mut inner = vec![0; 32]; - self.to_big_endian(&mut inner); - let size = 32 - (self.leading_zeros() / 8) as usize; + let inner: [u8; 32] = self.to_be_bytes(); + let size = 32 - (self.leading_zeros() / 8); buf.put_slice(&inner[32 - size..]); size } @@ -200,10 +200,10 @@ impl Compact for U256 { let mut arr = [0; 32]; arr[(32 - len)..].copy_from_slice(&buf[..len]); buf.advance(len); - return (U256::from_big_endian(&arr), buf) + return (U256::from_be_bytes(arr), buf) } - (U256::zero(), buf) + (U256::ZERO, buf) } } @@ -281,7 +281,9 @@ impl Compact for bool { #[cfg(test)] mod tests { use super::*; - use ethers_core::types::Address; + use revm_interpreter::B160; + + pub type Address = B160; #[test] fn compact_bytes() { @@ -397,9 +399,9 @@ mod tests { fn compact_u256() { let mut buf = vec![]; - assert_eq!(U256::zero().to_compact(&mut buf), 0); + assert_eq!(U256::ZERO.to_compact(&mut buf), 0); assert!(buf.is_empty()); - assert_eq!(U256::from_compact(&buf, 0), (U256::zero(), vec![].as_slice())); + assert_eq!(U256::from_compact(&buf, 0), (U256::ZERO, vec![].as_slice())); assert_eq!(U256::from(2).to_compact(&mut buf), 1); assert_eq!(buf, vec![2u8]); @@ -443,7 +445,7 @@ mod tests { fn default() -> Self { TestStruct { f_u64: 1u64, // 4 bits | 1 byte - f_u256: 1u64.into(), // 6 bits | 1 byte + f_u256: U256::from(1u64), // 6 bits | 1 byte f_bool_f: false, // 1 bit | 0 bytes f_bool_t: true, // 1 bit | 0 bytes f_option_none: None, // 1 bit | 0 bytes diff --git a/crates/storage/db/src/implementation/mdbx/mod.rs b/crates/storage/db/src/implementation/mdbx/mod.rs index 5fbc98b2c..6668a46dc 100644 --- a/crates/storage/db/src/implementation/mdbx/mod.rs +++ b/crates/storage/db/src/implementation/mdbx/mod.rs @@ -295,7 +295,7 @@ mod tests { let value = Account { nonce: 18446744073709551615, bytecode_hash: Some(H256::random()), - balance: U256::max_value(), + balance: U256::MAX, }; let key = Address::from_str("0xa2c122be93b0074270ebee7f6b7292c7deb45047") .expect(ERROR_ETH_ADDRESS); @@ -442,7 +442,7 @@ mod tests { // NOTE: Both values are present assert_eq!(Some(Ok((key1, value00.clone()))), walker.next()); - assert_eq!(Some(Ok((key1, value01.clone()))), walker.next()); + assert_eq!(Some(Ok((key1, value01))), walker.next()); assert_eq!(None, walker.next()); } diff --git a/crates/storage/db/src/tables/codecs/compact.rs b/crates/storage/db/src/tables/codecs/compact.rs index 8a3b96eac..b58bda1d0 100644 --- a/crates/storage/db/src/tables/codecs/compact.rs +++ b/crates/storage/db/src/tables/codecs/compact.rs @@ -45,6 +45,7 @@ impl_compression_for_compact!( ); impl_compression_for_compact!(AccountBeforeTx, TransactionSigned); impl_compression_for_compact!(CompactU256); +impl_compression_for_compact!(H256, H160); /// Adds wrapper structs for some primitive types so they can use StructFlags from Compact, when /// used as pure table values. diff --git a/crates/storage/db/src/tables/codecs/scale.rs b/crates/storage/db/src/tables/codecs/scale.rs index 121e4526f..0ff87197d 100644 --- a/crates/storage/db/src/tables/codecs/scale.rs +++ b/crates/storage/db/src/tables/codecs/scale.rs @@ -45,5 +45,5 @@ macro_rules! impl_compression_for_scale { impl ScaleValue for Vec {} impl sealed::Sealed for Vec {} -impl_compression_for_scale!(U256, H256, H160); +impl_compression_for_scale!(U256); impl_compression_for_scale!(u8, u32, u16, u64); diff --git a/crates/storage/libmdbx-rs/tests/cursor.rs b/crates/storage/libmdbx-rs/tests/cursor.rs index 7f73f4bd8..cadc18a90 100644 --- a/crates/storage/libmdbx-rs/tests/cursor.rs +++ b/crates/storage/libmdbx-rs/tests/cursor.rs @@ -237,17 +237,17 @@ fn test_iter_dup() { assert_eq!(items, cursor.iter_dup_start().flatten().collect::>>().unwrap()); assert_eq!( - items.iter().copied().into_iter().skip(3).collect::>(), + items.iter().copied().skip(3).collect::>(), cursor.iter_dup_from(b"b").flatten().collect::>>().unwrap() ); assert_eq!( - items.iter().copied().into_iter().skip(3).collect::>(), + items.iter().copied().skip(3).collect::>(), cursor.iter_dup_from(b"ab").flatten().collect::>>().unwrap() ); assert_eq!( - items.iter().copied().into_iter().skip(9).collect::>(), + items.iter().copied().skip(9).collect::>(), cursor.iter_dup_from(b"d").flatten().collect::>>().unwrap() ); diff --git a/crates/storage/provider/src/block.rs b/crates/storage/provider/src/block.rs index b67b90e62..d7a109944 100644 --- a/crates/storage/provider/src/block.rs +++ b/crates/storage/provider/src/block.rs @@ -71,13 +71,13 @@ pub trait BlockProvider: BlockHashProvider + Send + Sync { /// Get the hash of the block by matching the given id. fn block_hash_for_id(&self, block_id: BlockId) -> Result> { match block_id { - BlockId::Hash(hash) => Ok(Some(hash)), + BlockId::Hash(hash) => Ok(Some(H256(hash.0))), BlockId::Number(num) => { if matches!(num, BlockNumber::Latest) { return Ok(Some(self.chain_info()?.best_hash)) } self.convert_block_number(num)? - .map(|num| self.block_hash(num.into())) + .map(|num| self.block_hash(U256::from(num))) .transpose() .map(|maybe_hash| maybe_hash.flatten()) } @@ -90,7 +90,7 @@ pub trait BlockProvider: BlockHashProvider + Send + Sync { block_id: BlockId, ) -> Result> { match block_id { - BlockId::Hash(hash) => self.block_number(hash), + BlockId::Hash(hash) => self.block_number(H256(hash.0)), BlockId::Number(num) => self.convert_block_number(num), } } diff --git a/crates/storage/provider/src/db_provider/storage.rs b/crates/storage/provider/src/db_provider/storage.rs index 3c1f41aef..f3d753ce8 100644 --- a/crates/storage/provider/src/db_provider/storage.rs +++ b/crates/storage/provider/src/db_provider/storage.rs @@ -130,7 +130,7 @@ impl<'a, 'b, TX: DbTx<'a>> AccountProvider for HistoricalStateProviderRef<'a, 'b impl<'a, 'b, TX: DbTx<'a>> BlockHashProvider for HistoricalStateProviderRef<'a, 'b, TX> { /// Get block hash by number. fn block_hash(&self, number: U256) -> Result> { - self.tx.get::(number.as_u64()).map_err(Into::into) + self.tx.get::(number.to::()).map_err(Into::into) } } @@ -232,7 +232,7 @@ impl<'a, 'b, TX: DbTx<'a>> AccountProvider for LatestStateProviderRef<'a, 'b, TX impl<'a, 'b, TX: DbTx<'a>> BlockHashProvider for LatestStateProviderRef<'a, 'b, TX> { /// Get block hash by number. fn block_hash(&self, number: U256) -> Result> { - self.db.get::(number.as_u64()).map_err(Into::into) + self.db.get::(number.to::()).map_err(Into::into) } } diff --git a/crates/storage/provider/src/test_utils/mock.rs b/crates/storage/provider/src/test_utils/mock.rs index 4744d7001..fceb38a4b 100644 --- a/crates/storage/provider/src/test_utils/mock.rs +++ b/crates/storage/provider/src/test_utils/mock.rs @@ -117,7 +117,7 @@ impl BlockHashProvider for MockEthProvider { let hash = lock.iter().find_map( |(hash, b)| { - if b.number == number.as_u64() { + if b.number == number.to::() { Some(*hash) } else { None @@ -136,7 +136,7 @@ impl BlockProvider for MockEthProvider { fn block(&self, id: BlockId) -> Result> { let lock = self.blocks.lock(); match id { - BlockId::Hash(hash) => Ok(lock.get(&hash).cloned()), + BlockId::Hash(hash) => Ok(lock.get(&H256(hash.0)).cloned()), BlockId::Number(BlockNumber::Number(num)) => { Ok(lock.values().find(|b| b.number == num.as_u64()).cloned()) } diff --git a/crates/transaction-pool/Cargo.toml b/crates/transaction-pool/Cargo.toml index 5e9ea1405..617ca1e72 100644 --- a/crates/transaction-pool/Cargo.toml +++ b/crates/transaction-pool/Cargo.toml @@ -38,6 +38,10 @@ serde = { version = "1.0", features = ["derive", "rc"] } fnv = "1.0.7" bitflags = "1.3" +# ruint +# Using the uint! requires the crate to be imported +ruint = "1.7.0" + [dev-dependencies] paste = "1.0" rand = "0.8" diff --git a/crates/transaction-pool/src/pool/txpool.rs b/crates/transaction-pool/src/pool/txpool.rs index 68e49c016..9e9c2faba 100644 --- a/crates/transaction-pool/src/pool/txpool.rs +++ b/crates/transaction-pool/src/pool/txpool.rs @@ -18,6 +18,7 @@ use crate::{ }; use fnv::FnvHashMap; use reth_primitives::{TxHash, H256}; +use ruint::uint; use std::{ cmp::Ordering, collections::{btree_map::Entry, hash_map, BTreeMap, HashMap}, @@ -29,7 +30,7 @@ use std::{ /// The minimal value the basefee can decrease to /// /// The `BASE_FEE_MAX_CHANGE_DENOMINATOR` (https://eips.ethereum.org/EIPS/eip-1559) is `8`, or 12.5%, once the base fee has dropped to `7` WEI it cannot decrease further because 12.5% of 7 is less than 1. -pub(crate) const MIN_PROTOCOL_BASE_FEE: U256 = U256([7, 0, 0, 0]); +pub(crate) const MIN_PROTOCOL_BASE_FEE: U256 = uint!(0x7_U256); /// A pool that manages transactions. /// @@ -806,7 +807,7 @@ impl AllTransactions { let transaction = Arc::new(self.ensure_valid(transaction)?); let tx_id = *transaction.id(); let mut state = TxState::default(); - let mut cumulative_cost = U256::zero(); + let mut cumulative_cost = U256::ZERO; let mut updates = Vec::new(); let predecessor = @@ -1126,7 +1127,7 @@ mod tests { #[test] fn test_simple_insert() { - let on_chain_balance = U256::zero(); + let on_chain_balance = U256::ZERO; let on_chain_nonce = 0; let mut f = MockTransactionFactory::default(); let mut pool = AllTransactions::default(); @@ -1169,7 +1170,7 @@ mod tests { #[test] fn insert_replace() { - let on_chain_balance = U256::zero(); + let on_chain_balance = U256::ZERO; let on_chain_nonce = 0; let mut f = MockTransactionFactory::default(); let mut pool = AllTransactions::default(); @@ -1191,7 +1192,7 @@ mod tests { // insert nonce then nonce - 1 #[test] fn insert_previous() { - let on_chain_balance = U256::zero(); + let on_chain_balance = U256::ZERO; let on_chain_nonce = 0; let mut f = MockTransactionFactory::default(); let mut pool = AllTransactions::default(); @@ -1226,7 +1227,8 @@ mod tests { let on_chain_nonce = 0; let mut f = MockTransactionFactory::default(); let mut pool = AllTransactions::default(); - let tx = MockTransaction::eip1559().inc_nonce().set_gas_price(100u64.into()).inc_limit(); + let tx = + MockTransaction::eip1559().inc_nonce().set_gas_price(U256::from(100u64)).inc_limit(); let first = f.validated(tx.clone()); let _res = pool.insert_tx(first.clone(), on_chain_balance, on_chain_nonce).unwrap(); @@ -1257,7 +1259,7 @@ mod tests { let on_chain_nonce = 0; let mut f = MockTransactionFactory::default(); let mut pool = AllTransactions::default(); - pool.pending_basefee = pool.minimal_protocol_basefee + 1; + pool.pending_basefee = pool.minimal_protocol_basefee.checked_add(U256::from(1)).unwrap(); let tx = MockTransaction::eip1559().inc_nonce().inc_limit(); let first = f.validated(tx.clone()); diff --git a/crates/transaction-pool/src/test_util/mock.rs b/crates/transaction-pool/src/test_util/mock.rs index 05b54fb67..85f611464 100644 --- a/crates/transaction-pool/src/test_util/mock.rs +++ b/crates/transaction-pool/src/test_util/mock.rs @@ -115,7 +115,7 @@ impl MockTransaction { hash: H256::random(), sender: Address::random(), nonce: 0, - gas_price: U256::zero(), + gas_price: U256::ZERO, gas_limit: 0, value: Default::default(), } @@ -247,14 +247,14 @@ impl MockTransaction { /// Returns a new transaction with a higher gas price +1 pub fn inc_price(&self) -> Self { let mut next = self.clone(); - let gas = self.get_gas_price() + 1; + let gas = self.get_gas_price().checked_add(U256::from(1)).unwrap(); next.with_gas_price(gas) } /// Returns a new transaction with a higher value pub fn inc_value(&self) -> Self { let mut next = self.clone(); - let val = self.get_value() + 1; + let val = self.get_value().checked_add(U256::from(1)).unwrap(); next.with_value(val) } @@ -354,9 +354,9 @@ impl FromRecoveredTransaction for MockTransaction { hash, sender, nonce, - gas_price: gas_price.into(), + gas_price: U256::from(gas_price), gas_limit, - value: value.into(), + value: U256::from(value), }, Transaction::Eip1559(TxEip1559 { chain_id, @@ -372,10 +372,10 @@ impl FromRecoveredTransaction for MockTransaction { hash, sender, nonce, - max_fee_per_gas: max_fee_per_gas.into(), - max_priority_fee_per_gas: max_priority_fee_per_gas.into(), + max_fee_per_gas: U256::from(max_fee_per_gas), + max_priority_fee_per_gas: U256::from(max_priority_fee_per_gas), gas_limit, - value: value.into(), + value: U256::from(value), }, Transaction::Eip2930 { .. } => { unimplemented!() diff --git a/crates/transaction-pool/src/test_util/pool.rs b/crates/transaction-pool/src/test_util/pool.rs index a42e1987f..a90868a9d 100644 --- a/crates/transaction-pool/src/test_util/pool.rs +++ b/crates/transaction-pool/src/test_util/pool.rs @@ -218,9 +218,9 @@ pub struct ExecutedScenarios { fn test_on_chain_nonce_scenario() { let config = MockSimulatorConfig { num_senders: 10, - balance: 200_000u64.into(), + balance: U256::from(200_000u64), scenarios: vec![ScenarioType::OnchainNonce], - base_fee: 10u64.into(), + base_fee: U256::from(10u64), tx_generator: MockTransactionDistribution::new(30, 10..100), }; let mut simulator = MockTransactionSimulator::new(rand::thread_rng(), config);